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
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 _snake_case : Dict = logging.get_logger(__name__) _snake_case : Optional[int] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _snake_case : str = { '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' ), }, } _snake_case : List[str] = { '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, } _snake_case : int = { '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 _UpperCAmelCase ( _UpperCamelCase ): """simple docstring""" a_ = VOCAB_FILES_NAMES a_ = PRETRAINED_VOCAB_FILES_MAP a_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a_ = PRETRAINED_INIT_CONFIGURATION a_ = ["""input_ids""", """attention_mask"""] a_ = DistilBertTokenizer def __init__( self : Union[str, Any] , lowerCAmelCase_ : Union[str, Any]=None , lowerCAmelCase_ : Union[str, Any]=None , lowerCAmelCase_ : int=True , lowerCAmelCase_ : List[Any]="[UNK]" , lowerCAmelCase_ : int="[SEP]" , lowerCAmelCase_ : Optional[int]="[PAD]" , lowerCAmelCase_ : int="[CLS]" , lowerCAmelCase_ : Dict="[MASK]" , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : Tuple=None , **lowerCAmelCase_ : Optional[int] , ) -> Optional[int]: super().__init__( lowerCAmelCase_ , tokenizer_file=lowerCAmelCase_ , do_lower_case=lowerCAmelCase_ , unk_token=lowerCAmelCase_ , sep_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , cls_token=lowerCAmelCase_ , mask_token=lowerCAmelCase_ , tokenize_chinese_chars=lowerCAmelCase_ , strip_accents=lowerCAmelCase_ , **lowerCAmelCase_ , ) __lowerCAmelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , lowerCAmelCase_ ) != do_lower_case or normalizer_state.get('strip_accents' , lowerCAmelCase_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , lowerCAmelCase_ ) != tokenize_chinese_chars ): __lowerCAmelCase = getattr(lowerCAmelCase_ , normalizer_state.pop('type' ) ) __lowerCAmelCase = do_lower_case __lowerCAmelCase = strip_accents __lowerCAmelCase = tokenize_chinese_chars __lowerCAmelCase = normalizer_class(**lowerCAmelCase_ ) __lowerCAmelCase = do_lower_case def lowercase ( self : int , lowerCAmelCase_ : Dict , lowerCAmelCase_ : List[Any]=None ) -> Dict: __lowerCAmelCase = [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 lowercase ( self : str , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None ) -> List[int]: __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 ) * [0] + len(token_ids_a + sep ) * [1] def lowercase ( self : List[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ) -> Tuple[str]: __lowerCAmelCase = self._tokenizer.model.save(lowerCAmelCase_ , name=lowerCAmelCase_ ) return tuple(lowerCAmelCase_ )
284
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss _snake_case : Dict = pytest.mark.integration @require_faiss class _UpperCAmelCase ( _UpperCamelCase ): """simple docstring""" def lowercase ( self : List[Any] ) -> Optional[Any]: __lowerCAmelCase = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(lowerCAmelCase_ ) for x in np.arange(3_0 ).tolist()]} ) return dset def lowercase ( self : List[str] ) -> Tuple: import faiss __lowerCAmelCase = self._create_dummy_dataset() __lowerCAmelCase = dset.map( lambda lowerCAmelCase_ , lowerCAmelCase_ : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=lowerCAmelCase_ , keep_in_memory=lowerCAmelCase_ ) __lowerCAmelCase = dset.add_faiss_index('vecs' , batch_size=1_0_0 , metric_type=faiss.METRIC_INNER_PRODUCT ) __lowerCAmelCase , __lowerCAmelCase = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def lowercase ( self : Optional[Any] ) -> str: import faiss __lowerCAmelCase = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((3_0, 5) ) * np.arange(3_0 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=1_0_0 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __lowerCAmelCase , __lowerCAmelCase = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def lowercase ( self : int ) -> Optional[Any]: import faiss __lowerCAmelCase = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((3_0, 5) ) * np.arange(3_0 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=lowerCAmelCase_ ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) __lowerCAmelCase , __lowerCAmelCase = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def lowercase ( self : Union[str, Any] ) -> List[Any]: __lowerCAmelCase = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((3_0, 5) ) * np.arange(3_0 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(lowerCAmelCase_ , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def lowercase ( self : Union[str, Any] ) -> Tuple: from elasticsearch import Elasticsearch __lowerCAmelCase = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __lowerCAmelCase = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 3_0 ) __lowerCAmelCase = {'hits': {'hits': [{'_score': 1, '_id': 2_9}]}} __lowerCAmelCase = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=lowerCAmelCase_ ) __lowerCAmelCase , __lowerCAmelCase = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class _UpperCAmelCase ( _UpperCamelCase ): """simple docstring""" def lowercase ( self : str ) -> int: import faiss __lowerCAmelCase = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 1_0 ) # single query __lowerCAmelCase = np.zeros(5 , dtype=np.floataa ) __lowerCAmelCase = 1 __lowerCAmelCase , __lowerCAmelCase = index.search(lowerCAmelCase_ ) self.assertRaises(lowerCAmelCase_ , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __lowerCAmelCase = np.eye(5 , dtype=np.floataa )[::-1] __lowerCAmelCase , __lowerCAmelCase = index.search_batch(lowerCAmelCase_ ) self.assertRaises(lowerCAmelCase_ , index.search_batch , queries[0] ) __lowerCAmelCase = [scores[0] for scores in total_scores] __lowerCAmelCase = [indices[0] for indices in total_indices] self.assertGreater(np.min(lowerCAmelCase_ ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , lowerCAmelCase_ ) def lowercase ( self : List[Any] ) -> List[str]: import faiss __lowerCAmelCase = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __lowerCAmelCase = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(lowerCAmelCase_ ): __lowerCAmelCase = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def lowercase ( self : Union[str, Any] ) -> Dict: import faiss __lowerCAmelCase = faiss.IndexFlat(5 ) __lowerCAmelCase = FaissIndex(custom_index=lowerCAmelCase_ ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def lowercase ( self : str ) -> Any: import faiss __lowerCAmelCase = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=lowerCAmelCase_ ) as tmp_file: index.save(tmp_file.name ) __lowerCAmelCase = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __lowerCAmelCase = np.zeros(5 , dtype=np.floataa ) __lowerCAmelCase = 1 __lowerCAmelCase , __lowerCAmelCase = index.search(lowerCAmelCase_ ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a_ ( lowerCAmelCase_ : Union[str, Any] ): import faiss __lowerCAmelCase = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5, dtype=np.floataa ) ) __lowerCAmelCase = 'index.faiss' __lowerCAmelCase = F"""mock://{index_name}""" index.save(lowerCAmelCase_, storage_options=mockfs.storage_options ) __lowerCAmelCase = FaissIndex.load(lowerCAmelCase_, storage_options=mockfs.storage_options ) __lowerCAmelCase = np.zeros(5, dtype=np.floataa ) __lowerCAmelCase = 1 __lowerCAmelCase , __lowerCAmelCase = index.search(lowerCAmelCase_ ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class _UpperCAmelCase ( _UpperCamelCase ): """simple docstring""" def lowercase ( self : Any ) -> int: from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __lowerCAmelCase = Elasticsearch() __lowerCAmelCase = {'acknowledged': True} __lowerCAmelCase = ElasticSearchIndex(es_client=lowerCAmelCase_ ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query __lowerCAmelCase = 'foo' __lowerCAmelCase = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __lowerCAmelCase , __lowerCAmelCase = index.search(lowerCAmelCase_ ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __lowerCAmelCase = 'foo' __lowerCAmelCase = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __lowerCAmelCase , __lowerCAmelCase = index.search(lowerCAmelCase_ , request_timeout=3_0 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __lowerCAmelCase = ['foo', 'bar', 'foobar'] __lowerCAmelCase = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __lowerCAmelCase , __lowerCAmelCase = index.search_batch(lowerCAmelCase_ ) __lowerCAmelCase = [scores[0] for scores in total_scores] __lowerCAmelCase = [indices[0] for indices in total_indices] self.assertGreater(np.min(lowerCAmelCase_ ) , 0 ) self.assertListEqual([1, 1, 1] , lowerCAmelCase_ ) # batched queries with timeout __lowerCAmelCase = ['foo', 'bar', 'foobar'] __lowerCAmelCase = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __lowerCAmelCase , __lowerCAmelCase = index.search_batch(lowerCAmelCase_ , request_timeout=3_0 ) __lowerCAmelCase = [scores[0] for scores in total_scores] __lowerCAmelCase = [indices[0] for indices in total_indices] self.assertGreater(np.min(lowerCAmelCase_ ) , 0 ) self.assertListEqual([1, 1, 1] , lowerCAmelCase_ )
284
1
"""simple docstring""" 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_ (lowercase__ ): '''simple docstring''' def __init__( self , lowercase_ , lowercase_=False , lowercase_=True , lowercase_=False , lowercase_="<s>" , lowercase_="</s>" , lowercase_="<unk>" , lowercase_="<sep>" , lowercase_="<pad>" , lowercase_="<cls>" , lowercase_="<mask>" , lowercase_=["<eop>", "<eod>"] , lowercase_ = None , **lowercase_ , ): """simple docstring""" UpperCAmelCase_ : Union[str, Any] = AddedToken(lowercase_ , lstrip=lowercase_ , rstrip=lowercase_ ) if isinstance(lowercase_ , lowercase_ ) else mask_token UpperCAmelCase_ : Any = {} 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_ , ) UpperCAmelCase_ : Union[str, Any] = 3 UpperCAmelCase_ : Any = do_lower_case UpperCAmelCase_ : List[Any] = remove_space UpperCAmelCase_ : Optional[int] = keep_accents UpperCAmelCase_ : List[str] = vocab_file UpperCAmelCase_ : 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." ) UpperCAmelCase_ : int = jieba UpperCAmelCase_ : List[Any] = str.maketrans(" \n" , "\u2582\u2583" ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def UpperCamelCase__ ( self ): """simple docstring""" return len(self.sp_model ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Dict = {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 ): """simple docstring""" UpperCAmelCase_ : List[str] = self.__dict__.copy() UpperCAmelCase_ : List[Any] = None return state def __setstate__( self , lowercase_ ): """simple docstring""" UpperCAmelCase_ : str = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCAmelCase_ : Any = {} UpperCAmelCase_ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" if self.remove_space: UpperCAmelCase_ : Any = " ".join(inputs.strip().split() ) else: UpperCAmelCase_ : Union[str, Any] = inputs UpperCAmelCase_ : str = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: UpperCAmelCase_ : int = unicodedata.normalize("NFKD" , lowercase_ ) UpperCAmelCase_ : int = "".join([c for c in outputs if not unicodedata.combining(lowercase_ )] ) if self.do_lower_case: UpperCAmelCase_ : List[Any] = outputs.lower() return outputs def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.preprocess_text(lowercase_ ) UpperCAmelCase_ : List[str] = self.sp_model.encode(lowercase_ , out_type=lowercase_ ) UpperCAmelCase_ : Optional[Any] = [] for piece in pieces: if len(lowercase_ ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): UpperCAmelCase_ : Dict = 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: UpperCAmelCase_ : List[str] = cur_pieces[1:] else: UpperCAmelCase_ : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(lowercase_ ) else: new_pieces.append(lowercase_ ) return new_pieces def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" return self.sp_model.PieceToId(lowercase_ ) def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" return self.sp_model.IdToPiece(lowercase_ ) def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Dict = "".join(lowercase_ ).replace(lowercase_ , " " ).strip() return out_string def UpperCamelCase__ ( self , lowercase_ , lowercase_ = None ): """simple docstring""" UpperCAmelCase_ : Union[str, Any] = [self.sep_token_id] UpperCAmelCase_ : Optional[int] = [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 UpperCamelCase__ ( self , lowercase_ , lowercase_ = None , lowercase_ = False ): """simple docstring""" 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 UpperCamelCase__ ( self , lowercase_ , lowercase_ = None ): """simple docstring""" UpperCAmelCase_ : Optional[int] = [self.sep_token_id] UpperCAmelCase_ : Union[str, 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 UpperCamelCase__ ( self , lowercase_ , lowercase_ = None ): """simple docstring""" if not os.path.isdir(lowercase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCAmelCase_ : List[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: UpperCAmelCase_ : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(lowercase_ ) return (out_vocab_file,) def UpperCamelCase__ ( self , *lowercase_ , **lowercase_ ): """simple docstring""" UpperCAmelCase_ : Optional[int] = super()._decode(*lowercase_ , **lowercase_ ) UpperCAmelCase_ : Dict = text.replace(" " , "" ).replace("\u2582" , " " ).replace("\u2583" , "\n" ) return text
23
"""simple docstring""" from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean _a = 0 _a = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] _a = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right _a = tuple[int, int] class A_ : '''simple docstring''' def __init__( self , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ): """simple docstring""" UpperCAmelCase_ : int = pos_x UpperCAmelCase_ : List[Any] = pos_y UpperCAmelCase_ : Union[str, Any] = (pos_y, pos_x) UpperCAmelCase_ : Any = goal_x UpperCAmelCase_ : Dict = goal_y UpperCAmelCase_ : Any = g_cost UpperCAmelCase_ : List[str] = parent UpperCAmelCase_ : int = self.calculate_heuristic() UpperCAmelCase_ : Any = self.g_cost + self.h_cost def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Tuple = self.pos_x - self.goal_x UpperCAmelCase_ : Union[str, Any] = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(lowercase_ ) + abs(lowercase_ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self , lowercase_ ): """simple docstring""" return self.f_cost < other.f_cost class A_ : '''simple docstring''' def __init__( self , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Tuple = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , lowercase_ ) UpperCAmelCase_ : List[Any] = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9999 , lowercase_ ) UpperCAmelCase_ : str = [self.start] UpperCAmelCase_ : list[Node] = [] UpperCAmelCase_ : int = False def UpperCamelCase__ ( self ): """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() UpperCAmelCase_ : List[str] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(lowercase_ ) self.closed_nodes.append(lowercase_ ) UpperCAmelCase_ : str = self.get_successors(lowercase_ ) 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(lowercase_ ) else: # retrieve the best current path UpperCAmelCase_ : Union[str, Any] = self.open_nodes.pop(self.open_nodes.index(lowercase_ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(lowercase_ ) else: self.open_nodes.append(lowercase_ ) return [self.start.pos] def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Any = [] for action in delta: UpperCAmelCase_ : str = parent.pos_x + action[1] UpperCAmelCase_ : int = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(lowercase_ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( lowercase_ , lowercase_ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , lowercase_ , ) ) return successors def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Optional[int] = node UpperCAmelCase_ : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) UpperCAmelCase_ : Optional[int] = current_node.parent path.reverse() return path class A_ : '''simple docstring''' def __init__( self , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Dict = AStar(lowercase_ , lowercase_ ) UpperCAmelCase_ : Optional[Any] = AStar(lowercase_ , lowercase_ ) UpperCAmelCase_ : Tuple = False def UpperCamelCase__ ( self ): """simple docstring""" while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() UpperCAmelCase_ : List[str] = self.fwd_astar.open_nodes.pop(0 ) UpperCAmelCase_ : List[Any] = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( lowercase_ , lowercase_ ) self.fwd_astar.closed_nodes.append(lowercase_ ) self.bwd_astar.closed_nodes.append(lowercase_ ) UpperCAmelCase_ : Tuple = current_bwd_node UpperCAmelCase_ : str = current_fwd_node UpperCAmelCase_ : Dict = { self.fwd_astar: self.fwd_astar.get_successors(lowercase_ ), self.bwd_astar: self.bwd_astar.get_successors(lowercase_ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(lowercase_ ) else: # retrieve the best current path UpperCAmelCase_ : List[Any] = astar.open_nodes.pop( astar.open_nodes.index(lowercase_ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(lowercase_ ) else: astar.open_nodes.append(lowercase_ ) return [self.fwd_astar.start.pos] def UpperCamelCase__ ( self , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : List[Any] = self.fwd_astar.retrace_path(lowercase_ ) UpperCAmelCase_ : int = self.bwd_astar.retrace_path(lowercase_ ) bwd_path.pop() bwd_path.reverse() UpperCAmelCase_ : Any = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] _a = (0, 0) _a = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) _a = time.time() _a = AStar(init, goal) _a = a_star.search() _a = time.time() - start_time print(f"""AStar execution time = {end_time:f} seconds""") _a = time.time() _a = BidirectionalAStar(init, goal) _a = time.time() - bd_start_time print(f"""BidirectionalAStar execution time = {bd_end_time:f} seconds""")
23
1
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" SCREAMING_SNAKE_CASE__ : int = "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n" SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def __A ( self : Dict ) -> 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='''https://github.com/mjpost/sacreBLEU#chrf--chrf''' , 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#chrf--chrf'''] , reference_urls=[ '''https://github.com/m-popovic/chrF''', ] , ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int = CHRF.CHAR_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.WORD_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.BETA , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Optional[Any]: __lowerCamelCase = len(references[0] ) if any(len(SCREAMING_SNAKE_CASE__ ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) __lowerCamelCase = [[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase = CHRF(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sb_chrf.corpus_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
270
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_wavlm": ["WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "WavLMConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST", "WavLMForAudioFrameClassification", "WavLMForCTC", "WavLMForSequenceClassification", "WavLMForXVector", "WavLMModel", "WavLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
1
import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType __a , __a , __a :Union[str, Any] = False, False, False @dataclass class _a : """simple docstring""" _lowerCamelCase : Optional[int] = None _lowerCamelCase : bool = True _lowerCamelCase : bool = True _lowerCamelCase : Optional[str] = None # Automatically constructed _lowerCamelCase : ClassVar[str] = "dict" _lowerCamelCase : ClassVar[Any] = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) _lowerCamelCase : str = field(default='Audio' , init=snake_case_ , repr=snake_case_ ) def __call__( self : List[str] ): return self.pa_type def __A ( self : Optional[Any] , UpperCAmelCase : Union[str, bytes, dict] ): try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("To support encoding audio data, please install 'soundfile'." ) from err if isinstance(UpperCAmelCase , UpperCAmelCase ): return {"bytes": None, "path": value} elif isinstance(UpperCAmelCase , UpperCAmelCase ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes A_ = BytesIO() sf.write(UpperCAmelCase , value["array"] , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} 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 if value["path"].endswith("pcm" ): # "PCM" only has raw audio bytes if value.get("sampling_rate" ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("To use PCM files, please specify a 'sampling_rate' in Audio object" ) if value.get("bytes" ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) A_ = np.frombuffer(value["bytes"] , dtype=np.intaa ).astype(np.floataa ) / 32767 else: A_ = np.memmap(value["path"] , dtype="h" , mode="r" ).astype(np.floataa ) / 32767 A_ = BytesIO(bytes() ) sf.write(UpperCAmelCase , UpperCAmelCase , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f'''An audio sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def __A ( self : Optional[int] , UpperCAmelCase : dict , UpperCAmelCase : Optional[Dict[str, Union[str, bool, None]]] = None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Audio(decode=True) instead." ) A_ , A_ = (value["path"], BytesIO(value["bytes"] )) if value["bytes"] is not None else (value["path"], None) if path is None and file is None: raise ValueError(f'''An audio sample should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError("To support decoding audio files, please install 'librosa' and 'soundfile'." ) from err A_ = xsplitext(UpperCAmelCase )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( "Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( "Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) if file is None: A_ = token_per_repo_id or {} A_ = path.split("::" )[-1] try: A_ = string_to_dict(UpperCAmelCase , config.HUB_DATASETS_URL )["repo_id"] A_ = token_per_repo_id[repo_id] except (ValueError, KeyError): A_ = None with xopen(UpperCAmelCase , "rb" , use_auth_token=UpperCAmelCase ) as f: A_ , A_ = sf.read(UpperCAmelCase ) else: A_ , A_ = sf.read(UpperCAmelCase ) A_ = array.T if self.mono: A_ = librosa.to_mono(UpperCAmelCase ) if self.sampling_rate and self.sampling_rate != sampling_rate: A_ = librosa.resample(UpperCAmelCase , orig_sr=UpperCAmelCase , target_sr=self.sampling_rate ) A_ = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def __A ( self : Optional[int] ): from .features import Value if self.decode: raise ValueError("Cannot flatten a decoded Audio feature." ) return { "bytes": Value("binary" ), "path": Value("string" ), } def __A ( self : Optional[Any] , UpperCAmelCase : Union[pa.StringArray, pa.StructArray] ): if pa.types.is_string(storage.type ): A_ = pa.array([None] * len(UpperCAmelCase ) , type=pa.binary() ) A_ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): A_ = pa.array([None] * len(UpperCAmelCase ) , type=pa.string() ) A_ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices("array" ): A_ = pa.array([Audio().encode_example(UpperCAmelCase ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: A_ = storage.field("bytes" ) else: A_ = pa.array([None] * len(UpperCAmelCase ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: A_ = storage.field("path" ) else: A_ = pa.array([None] * len(UpperCAmelCase ) , type=pa.string() ) A_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) return array_cast(UpperCAmelCase , self.pa_type ) def __A ( self : Tuple , UpperCAmelCase : pa.StructArray ): @no_op_if_value_is_null def path_to_bytes(UpperCAmelCase : str ): with xopen(UpperCAmelCase , "rb" ) as f: A_ = f.read() return bytes_ A_ = 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() , ) A_ = pa.array( [os.path.basename(UpperCAmelCase ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) A_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(UpperCAmelCase , self.pa_type )
329
import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def __snake_case ( __UpperCamelCase : List[Any] ): """simple docstring""" if ( (cp >= 0X4_E_0_0 and cp <= 0X9_F_F_F) or (cp >= 0X3_4_0_0 and cp <= 0X4_D_B_F) # or (cp >= 0X2_0_0_0_0 and cp <= 0X2_A_6_D_F) # or (cp >= 0X2_A_7_0_0 and cp <= 0X2_B_7_3_F) # or (cp >= 0X2_B_7_4_0 and cp <= 0X2_B_8_1_F) # or (cp >= 0X2_B_8_2_0 and cp <= 0X2_C_E_A_F) # or (cp >= 0XF_9_0_0 and cp <= 0XF_A_F_F) or (cp >= 0X2_F_8_0_0 and cp <= 0X2_F_A_1_F) # ): # return True return False def __snake_case ( __UpperCamelCase : str ): """simple docstring""" for char in word: A_ = ord(__UpperCamelCase ) if not _is_chinese_char(__UpperCamelCase ): return 0 return 1 def __snake_case ( __UpperCamelCase : List[str] ): """simple docstring""" A_ = set() for token in tokens: A_ = len(__UpperCamelCase ) > 1 and is_chinese(__UpperCamelCase ) if chinese_word: word_set.add(__UpperCamelCase ) A_ = list(__UpperCamelCase ) return word_list def __snake_case ( __UpperCamelCase : List[str] ,__UpperCamelCase : set() ): """simple docstring""" if not chinese_word_set: return bert_tokens A_ = max([len(__UpperCamelCase ) for w in chinese_word_set] ) A_ = bert_tokens A_ , A_ = 0, len(__UpperCamelCase ) while start < end: A_ = True if is_chinese(bert_word[start] ): A_ = min(end - start ,__UpperCamelCase ) for i in range(__UpperCamelCase ,1 ,-1 ): A_ = "".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 ,start + i ): A_ = "##" + bert_word[j] A_ = start + i A_ = False break if single_word: start += 1 return bert_word def __snake_case ( __UpperCamelCase : List[str] ,__UpperCamelCase : LTP ,__UpperCamelCase : BertTokenizer ): """simple docstring""" A_ = [] for i in range(0 ,len(__UpperCamelCase ) ,100 ): A_ = ltp_tokenizer.seg(lines[i : i + 100] )[0] A_ = [get_chinese_word(__UpperCamelCase ) for r in res] ltp_res.extend(__UpperCamelCase ) assert len(__UpperCamelCase ) == len(__UpperCamelCase ) A_ = [] for i in range(0 ,len(__UpperCamelCase ) ,100 ): A_ = bert_tokenizer(lines[i : i + 100] ,add_special_tokens=__UpperCamelCase ,truncation=__UpperCamelCase ,max_length=512 ) bert_res.extend(res["input_ids"] ) assert len(__UpperCamelCase ) == len(__UpperCamelCase ) A_ = [] for input_ids, chinese_word in zip(__UpperCamelCase ,__UpperCamelCase ): A_ = [] for id in input_ids: A_ = bert_tokenizer._convert_id_to_token(__UpperCamelCase ) input_tokens.append(__UpperCamelCase ) A_ = add_sub_symbol(__UpperCamelCase ,__UpperCamelCase ) A_ = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(__UpperCamelCase ): if token[:2] == "##": A_ = token[2:] # save chinese tokens' pos if len(__UpperCamelCase ) == 1 and _is_chinese_char(ord(__UpperCamelCase ) ): ref_id.append(__UpperCamelCase ) ref_ids.append(__UpperCamelCase ) assert len(__UpperCamelCase ) == len(__UpperCamelCase ) return ref_ids def __snake_case ( __UpperCamelCase : Dict ): """simple docstring""" with open(args.file_name ,"r" ,encoding="utf-8" ) as f: A_ = f.readlines() A_ = [line.strip() for line in data if len(__UpperCamelCase ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' A_ = LTP(args.ltp ) # faster in GPU device A_ = BertTokenizer.from_pretrained(args.bert ) A_ = prepare_ref(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) with open(args.save_path ,"w" ,encoding="utf-8" ) as f: A_ = [json.dumps(__UpperCamelCase ) + "\n" for ref in ref_ids] f.writelines(__UpperCamelCase ) if __name__ == "__main__": __a :List[Any] = argparse.ArgumentParser(description='prepare_chinese_ref') parser.add_argument( '--file_name', type=str, default='./resources/chinese-demo.txt', help='file need process, same as training data in lm', ) parser.add_argument( '--ltp', type=str, default='./resources/ltp', help='resources for LTP tokenizer, usually a path' ) parser.add_argument('--bert', type=str, default='./resources/robert', help='resources for Bert tokenizer') parser.add_argument('--save_path', type=str, default='./resources/ref.txt', help='path to save res') __a :Dict = parser.parse_args() main(args)
329
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_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = 1 UpperCAmelCase__ : Dict = 2 UpperCAmelCase__ : Optional[int] = 3 UpperCAmelCase__ : Dict = 4 UpperCAmelCase__ : List[str] = 5 @dataclass class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = 42 class UpperCAmelCase_ : """simple docstring""" UpperCAmelCase__ : Dict = SCHEDULER_CONFIG_NAME UpperCAmelCase__ : Tuple = ["dtype"] UpperCAmelCase__ : Optional[int] = [] UpperCAmelCase__ : Optional[Any] = True @classmethod def __lowercase ( cls , _a = None , _a = None , _a=False , **_a , ) -> Any: _a : List[Any] = cls.load_config( pretrained_model_name_or_path=_SCREAMING_SNAKE_CASE , subfolder=_SCREAMING_SNAKE_CASE , return_unused_kwargs=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) _a : str = cls.from_config(_SCREAMING_SNAKE_CASE , return_unused_kwargs=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if hasattr(_SCREAMING_SNAKE_CASE , '''create_state''' ) and getattr(_SCREAMING_SNAKE_CASE , '''has_state''' , _SCREAMING_SNAKE_CASE ): _a : str = scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def __lowercase ( self , _a , _a = False , **_a ) -> List[str]: self.save_config(save_directory=_SCREAMING_SNAKE_CASE , push_to_hub=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def __lowercase ( self ) -> Any: return self._get_compatibles() @classmethod def __lowercase ( cls ) -> Tuple: _a : Tuple = list(set([cls.__name__] + cls._compatibles ) ) _a : Union[str, Any] = importlib.import_module(__name__.split('''.''' )[0] ) _a : Any = [ getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for c in compatible_classes_str if hasattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ] return compatible_classes def __UpperCAmelCase ( __a : Union[str, Any] ,__a : Optional[int] ) -> List[str]: """simple docstring""" assert len(__a ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(__a ) - x.ndim) ) ,__a ) def __UpperCAmelCase ( __a : Optional[Any] ,__a : Tuple=0.9_99 ,__a : Optional[Any]=jnp.floataa ) -> Any: """simple docstring""" def alpha_bar(__a : List[Any] ): return math.cos((time_step + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 _a : Optional[Any] = [] for i in range(__a ): _a : Optional[Any] = i / num_diffusion_timesteps _a : Union[str, Any] = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(__a ) / alpha_bar(__a ) ,__a ) ) return jnp.array(__a ,dtype=__a ) @flax.struct.dataclass class UpperCAmelCase_ : """simple docstring""" UpperCAmelCase__ : Union[str, Any] = 42 UpperCAmelCase__ : List[Any] = 42 UpperCAmelCase__ : Any = 42 @classmethod def __lowercase ( cls , _a ) -> Tuple: _a : Tuple = scheduler.config if config.trained_betas is not None: _a : List[Any] = jnp.asarray(config.trained_betas , dtype=scheduler.dtype ) elif config.beta_schedule == "linear": _a : List[Any] = jnp.linspace(config.beta_start , config.beta_end , config.num_train_timesteps , dtype=scheduler.dtype ) elif config.beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _a : Tuple = ( jnp.linspace( config.beta_start**0.5 , config.beta_end**0.5 , config.num_train_timesteps , dtype=scheduler.dtype ) ** 2 ) elif config.beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _a : Tuple = betas_for_alpha_bar(config.num_train_timesteps , dtype=scheduler.dtype ) else: raise NotImplementedError( F"""beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}""" ) _a : int = 1.0 - betas _a : List[Any] = jnp.cumprod(_SCREAMING_SNAKE_CASE , axis=0 ) return cls( alphas=_SCREAMING_SNAKE_CASE , betas=_SCREAMING_SNAKE_CASE , alphas_cumprod=_SCREAMING_SNAKE_CASE , ) def __UpperCAmelCase ( __a : List[Any] ,__a : int ,__a : Tuple ,__a : List[str] ) -> Union[str, Any]: """simple docstring""" _a : List[Any] = state.alphas_cumprod _a : Tuple = alphas_cumprod[timesteps] ** 0.5 _a : Optional[int] = sqrt_alpha_prod.flatten() _a : Union[str, Any] = broadcast_to_shape_from_left(__a ,original_samples.shape ) _a : Any = (1 - alphas_cumprod[timesteps]) ** 0.5 _a : Dict = sqrt_one_minus_alpha_prod.flatten() _a : List[str] = broadcast_to_shape_from_left(__a ,original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def __UpperCAmelCase ( __a : Tuple ,__a : Dict ,__a : Union[str, Any] ,__a : Tuple ) -> Union[str, Any]: """simple docstring""" _a : Union[str, Any] = get_sqrt_alpha_prod(__a ,__a ,__a ,__a ) _a : Union[str, Any] = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def __UpperCAmelCase ( __a : Dict ,__a : str ,__a : Union[str, Any] ,__a : int ) -> Tuple: """simple docstring""" _a : Dict = get_sqrt_alpha_prod(__a ,__a ,__a ,__a ) _a : Union[str, Any] = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
235
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase = { """configuration_roberta""": ["""ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """RobertaConfig""", """RobertaOnnxConfig"""], """tokenization_roberta""": ["""RobertaTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ["""RobertaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ """ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""", """RobertaForCausalLM""", """RobertaForMaskedLM""", """RobertaForMultipleChoice""", """RobertaForQuestionAnswering""", """RobertaForSequenceClassification""", """RobertaForTokenClassification""", """RobertaModel""", """RobertaPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ """TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFRobertaForCausalLM""", """TFRobertaForMaskedLM""", """TFRobertaForMultipleChoice""", """TFRobertaForQuestionAnswering""", """TFRobertaForSequenceClassification""", """TFRobertaForTokenClassification""", """TFRobertaMainLayer""", """TFRobertaModel""", """TFRobertaPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ """FlaxRobertaForCausalLM""", """FlaxRobertaForMaskedLM""", """FlaxRobertaForMultipleChoice""", """FlaxRobertaForQuestionAnswering""", """FlaxRobertaForSequenceClassification""", """FlaxRobertaForTokenClassification""", """FlaxRobertaModel""", """FlaxRobertaPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
186
0
import unittest from transformers import GPTNeoXJapaneseConfig, is_torch_available from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel class __A: """simple docstring""" 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_=4 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=5_12 , 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 , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_multiple_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout UpperCamelCase__ = attention_dropout UpperCamelCase__ = weight_tying UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = scope def UpperCAmelCase_ (self ): UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = self.get_config() return config, input_ids, input_mask, token_labels def UpperCAmelCase_ (self ): return GPTNeoXJapaneseConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_multiple_size=self.intermediate_multiple_size , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , weight_tying=self.weight_tying , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self.prepare_config_and_inputs() UpperCamelCase__ = True return config, input_ids, input_mask, token_labels def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = GPTNeoXJapaneseModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 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_ ): UpperCamelCase__ = True UpperCamelCase__ = GPTNeoXJapaneseModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=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_ ): UpperCamelCase__ = GPTNeoXJapaneseForCausalLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=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_ ): UpperCamelCase__ = True UpperCamelCase__ = GPTNeoXJapaneseForCausalLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() # first forward pass UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase__ = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat([input_mask, next_mask] , dim=-1 ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = output_from_no_past["""hidden_states"""][0] UpperCamelCase__ = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ , )["""hidden_states"""][0] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase__ = 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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = config_and_inputs UpperCamelCase__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else () SCREAMING_SNAKE_CASE__ = (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE__ = ( {"""feature-extraction""": GPTNeoXJapaneseModel, """text-generation""": GPTNeoXJapaneseForCausalLM} if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = GPTNeoXJapaneseModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): # This regression test was failing with PyTorch < 1.3 UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_decoder() UpperCamelCase__ = None self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = """abeja/gpt-neox-japanese-2.7b""" UpperCamelCase__ = ["""データサイエンティストとは、""", """100年後に必要とされる会社は、""", """フルリモートの環境で働くために必要なことは、""", """国境の長いトンネルを抜けると""", """美味しい日本食といえば、"""] UpperCamelCase__ = [ """データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。""", """100年後に必要とされる会社は、「人」が中心の会社です。""", """フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。""", """国境の長いトンネルを抜けると、そこは雪国だった。""", """美味しい日本食といえば、やっぱりお寿司ですよね。""", ] UpperCamelCase__ = GPTNeoXJapaneseTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = GPTNeoXJapaneseForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [] for prompt in prompts: UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).input_ids UpperCamelCase__ = model.generate(SCREAMING_SNAKE_CASE_ , max_length=50 ) UpperCamelCase__ = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) predicted_outputs += generated_string self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
361
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class __A: """simple docstring""" @staticmethod def UpperCAmelCase_ (*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): pass def __magic_name__ ( __a : Image ): '''simple docstring''' UpperCamelCase__ = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def __magic_name__ ( __a : Image ): '''simple docstring''' UpperCamelCase__ = np.array(__a ) UpperCamelCase__ = npimg.shape return {"hash": hashimage(__a ), "shape": shape} @is_pipeline_test @require_vision @require_torch class __A( unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) SCREAMING_SNAKE_CASE__ = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = MaskGenerationPipeline(model=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): pass @require_tf @unittest.skip("""Image segmentation not implemented in TF""" ) def UpperCAmelCase_ (self ): pass @slow @require_torch def UpperCAmelCase_ (self ): UpperCamelCase__ = pipeline("""mask-generation""" , model="""facebook/sam-vit-huge""" ) UpperCamelCase__ = image_segmenter("""http://images.cocodataset.org/val2017/000000039769.jpg""" , points_per_batch=2_56 ) # Shortening by hashing UpperCamelCase__ = [] for i, o in enumerate(outputs["""masks"""] ): new_outupt += [{"mask": mask_to_test_readable(SCREAMING_SNAKE_CASE_ ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [ {"""mask""": {"""hash""": """115ad19f5f""", """shape""": (4_80, 6_40)}, """scores""": 1.0444}, {"""mask""": {"""hash""": """6affa964c6""", """shape""": (4_80, 6_40)}, """scores""": 1.021}, {"""mask""": {"""hash""": """dfe28a0388""", """shape""": (4_80, 6_40)}, """scores""": 1.0167}, {"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (4_80, 6_40)}, """scores""": 1.0132}, {"""mask""": {"""hash""": """fe8065c197""", """shape""": (4_80, 6_40)}, """scores""": 1.0053}, {"""mask""": {"""hash""": """e2d0b7a0b7""", """shape""": (4_80, 6_40)}, """scores""": 0.9967}, {"""mask""": {"""hash""": """453c7844bd""", """shape""": (4_80, 6_40)}, """scores""": 0.993}, {"""mask""": {"""hash""": """3d44f2926d""", """shape""": (4_80, 6_40)}, """scores""": 0.9909}, {"""mask""": {"""hash""": """64033ddc3f""", """shape""": (4_80, 6_40)}, """scores""": 0.9879}, {"""mask""": {"""hash""": """801064ff79""", """shape""": (4_80, 6_40)}, """scores""": 0.9834}, {"""mask""": {"""hash""": """6172f276ef""", """shape""": (4_80, 6_40)}, """scores""": 0.9716}, {"""mask""": {"""hash""": """b49e60e084""", """shape""": (4_80, 6_40)}, """scores""": 0.9612}, {"""mask""": {"""hash""": """a811e775fd""", """shape""": (4_80, 6_40)}, """scores""": 0.9599}, {"""mask""": {"""hash""": """a6a8ebcf4b""", """shape""": (4_80, 6_40)}, """scores""": 0.9552}, {"""mask""": {"""hash""": """9d8257e080""", """shape""": (4_80, 6_40)}, """scores""": 0.9532}, {"""mask""": {"""hash""": """32de6454a8""", """shape""": (4_80, 6_40)}, """scores""": 0.9516}, {"""mask""": {"""hash""": """af3d4af2c8""", """shape""": (4_80, 6_40)}, """scores""": 0.9499}, {"""mask""": {"""hash""": """3c6db475fb""", """shape""": (4_80, 6_40)}, """scores""": 0.9483}, {"""mask""": {"""hash""": """c290813fb9""", """shape""": (4_80, 6_40)}, """scores""": 0.9464}, {"""mask""": {"""hash""": """b6f0b8f606""", """shape""": (4_80, 6_40)}, """scores""": 0.943}, {"""mask""": {"""hash""": """92ce16bfdf""", """shape""": (4_80, 6_40)}, """scores""": 0.943}, {"""mask""": {"""hash""": """c749b25868""", """shape""": (4_80, 6_40)}, """scores""": 0.9408}, {"""mask""": {"""hash""": """efb6cab859""", """shape""": (4_80, 6_40)}, """scores""": 0.9335}, {"""mask""": {"""hash""": """1ff2eafb30""", """shape""": (4_80, 6_40)}, """scores""": 0.9326}, {"""mask""": {"""hash""": """788b798e24""", """shape""": (4_80, 6_40)}, """scores""": 0.9262}, {"""mask""": {"""hash""": """abea804f0e""", """shape""": (4_80, 6_40)}, """scores""": 0.8999}, {"""mask""": {"""hash""": """7b9e8ddb73""", """shape""": (4_80, 6_40)}, """scores""": 0.8986}, {"""mask""": {"""hash""": """cd24047c8a""", """shape""": (4_80, 6_40)}, """scores""": 0.8984}, {"""mask""": {"""hash""": """6943e6bcbd""", """shape""": (4_80, 6_40)}, """scores""": 0.8873}, {"""mask""": {"""hash""": """b5f47c9191""", """shape""": (4_80, 6_40)}, """scores""": 0.8871} ] , ) # fmt: on @require_torch @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = """facebook/sam-vit-huge""" UpperCamelCase__ = pipeline("""mask-generation""" , model=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = image_segmenter( """http://images.cocodataset.org/val2017/000000039769.jpg""" , pred_iou_thresh=1 , points_per_batch=2_56 ) # Shortening by hashing UpperCamelCase__ = [] for i, o in enumerate(outputs["""masks"""] ): new_outupt += [{"mask": mask_to_test_readable(SCREAMING_SNAKE_CASE_ ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [ {"""mask""": {"""hash""": """115ad19f5f""", """shape""": (4_80, 6_40)}, """scores""": 1.0444}, {"""mask""": {"""hash""": """6affa964c6""", """shape""": (4_80, 6_40)}, """scores""": 1.0210}, {"""mask""": {"""hash""": """dfe28a0388""", """shape""": (4_80, 6_40)}, """scores""": 1.0167}, {"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (4_80, 6_40)}, """scores""": 1.0132}, {"""mask""": {"""hash""": """fe8065c197""", """shape""": (4_80, 6_40)}, """scores""": 1.0053}, ] , )
178
0
'''simple docstring''' from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(imports) UpperCAmelCase : Any = _symbol_database.Default() UpperCAmelCase : List[str] = _descriptor_pool.Default().AddSerializedFile( b'\n\x19sentencepiece_model.proto\x12\rsentencepiece"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03' ) UpperCAmelCase : Any = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sentencepiece_model_pb2', _globals) if _descriptor._USE_C_DESCRIPTORS is False: UpperCAmelCase : str = None UpperCAmelCase : Optional[Any] = b'H\003' # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined) # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001" # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001" UpperCAmelCase : Tuple = 4_5 UpperCAmelCase : Dict = 1_5_8_1 UpperCAmelCase : int = 1_5_1_7 UpperCAmelCase : int = 1_5_7_0 UpperCAmelCase : List[Any] = 1_5_8_4 UpperCAmelCase : Union[str, Any] = 1_7_9_3 UpperCAmelCase : Tuple = 1_7_9_5 UpperCAmelCase : Optional[Any] = 1_9_1_6 UpperCAmelCase : str = 1_8_6_4 UpperCAmelCase : Dict = 1_9_0_5 UpperCAmelCase : Dict = 1_9_1_9 UpperCAmelCase : Dict = 2_4_2_9 UpperCAmelCase : List[Any] = 2_2_0_8 UpperCAmelCase : Union[str, Any] = 2_4_1_8 UpperCAmelCase : List[str] = 2_3_2_3 UpperCAmelCase : List[str] = 2_4_0_7 # @@protoc_insertion_point(module_scope)
267
"""simple docstring""" import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() A = logging.get_logger() def __A ( a_ :int , a_ :str , a_ :LevitConfig , a_ :Path , a_ :bool = True) -> Union[str, Any]: print(F"""Converting {name}...""") with torch.no_grad(): if hidden_sizes == 1_28: if name[-1] == "S": __a : Optional[int] = timm.create_model('''levit_128s''' , pretrained=a_) else: __a : List[Any] = timm.create_model('''levit_128''' , pretrained=a_) if hidden_sizes == 1_92: __a : List[Any] = timm.create_model('''levit_192''' , pretrained=a_) if hidden_sizes == 2_56: __a : Any = timm.create_model('''levit_256''' , pretrained=a_) if hidden_sizes == 3_84: __a : Optional[int] = timm.create_model('''levit_384''' , pretrained=a_) from_model.eval() __a : Dict = LevitForImageClassificationWithTeacher(a_).eval() __a : Optional[int] = OrderedDict() __a : Tuple = from_model.state_dict() __a : Dict = list(from_model.state_dict().keys()) __a : str = list(our_model.state_dict().keys()) print(len(a_) , len(a_)) for i in range(len(a_)): __a : int = weights[og_keys[i]] our_model.load_state_dict(a_) __a : Union[str, Any] = torch.randn((2, 3, 2_24, 2_24)) __a : Union[str, Any] = from_model(a_) __a : Optional[int] = our_model(a_).logits assert torch.allclose(a_ , a_), "The model logits don't match the original one." __a : List[Any] = name print(a_) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name) __a : Tuple = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name) print(F"""Pushed {checkpoint_name}""") def __A ( a_ :Path , a_ :str = None , a_ :bool = True) -> Optional[Any]: __a : List[Any] = '''imagenet-1k-id2label.json''' __a : Tuple = 10_00 __a : List[str] = (1, num_labels) __a : Union[str, Any] = '''huggingface/label-files''' __a : Dict = num_labels __a : List[Any] = json.load(open(hf_hub_download(a_ , a_ , repo_type='''dataset''') , '''r''')) __a : str = {int(a_): v for k, v in idalabel.items()} __a : int = idalabel __a : List[str] = {v: k for k, v in idalabel.items()} __a : Optional[int] = partial(a_ , num_labels=a_ , idalabel=a_ , labelaid=a_) __a : Optional[int] = { '''levit-128S''': 1_28, '''levit-128''': 1_28, '''levit-192''': 1_92, '''levit-256''': 2_56, '''levit-384''': 3_84, } __a : int = { '''levit-128S''': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), '''levit-128''': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), '''levit-192''': ImageNetPreTrainedConfig( hidden_sizes=[1_92, 2_88, 3_84] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), '''levit-256''': ImageNetPreTrainedConfig( hidden_sizes=[2_56, 3_84, 5_12] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), '''levit-384''': ImageNetPreTrainedConfig( hidden_sizes=[3_84, 5_12, 7_68] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] , a_ , names_to_config[model_name] , a_ , a_) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , a_ , a_ , a_ , a_) return config, expected_shape if __name__ == "__main__": A = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help='''The name of the model you wish to convert, it must be one of the supported Levit* architecture,''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''levit-dump-folder/''', type=Path, required=False, help='''Path to the output PyTorch model directory.''', ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Push model and image processor to the hub''') parser.add_argument( '''--no-push_to_hub''', dest='''push_to_hub''', action='''store_false''', help='''Do not push model and image processor to the hub''', ) A = parser.parse_args() A = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
160
0
from collections.abc import Callable import numpy as np def UpperCamelCase (lowercase_: Callable , lowercase_: float , lowercase_: float , lowercase_: float , lowercase_: float ) -> np.array: A__ : List[str] = int(np.ceil((x_end - xa) / step_size ) ) A__ : Union[str, Any] = np.zeros((n + 1,) ) A__ : Dict = ya A__ : Optional[int] = xa for k in range(lowercase_ ): A__ : Tuple = y[k] + step_size * ode_func(lowercase_ , y[k] ) A__ : Tuple = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
359
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES A_ : Union[str, Any] = logging.get_logger(__name__) A_ : int = OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) A_ : Tuple = OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) A_ : Tuple = OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) A_ : Any = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) A_ : Union[str, Any] = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) A_ : Union[str, Any] = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) A_ : Tuple = OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) A_ : Optional[int] = OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) A_ : Any = OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) A_ : Dict = OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) A_ : List[str] = OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) A_ : List[str] = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) A_ : Optional[Any] = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) A_ : Optional[Any] = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) A_ : List[str] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) A_ : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) A_ : Tuple = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) A_ : Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) A_ : Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) A_ : Optional[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) A_ : Optional[int] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) A_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) A_ : Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) A_ : Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) A_ : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) A_ : Union[str, Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) A_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) A_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class _a (_BaseAutoModelClass ): '''simple docstring''' UpperCAmelCase__: str = FLAX_MODEL_MAPPING A_ : Any = auto_class_update(FlaxAutoModel) class _a (_BaseAutoModelClass ): '''simple docstring''' UpperCAmelCase__: List[Any] = FLAX_MODEL_FOR_PRETRAINING_MAPPING A_ : Union[str, Any] = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class _a (_BaseAutoModelClass ): '''simple docstring''' UpperCAmelCase__: Any = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING A_ : Union[str, Any] = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class _a (_BaseAutoModelClass ): '''simple docstring''' UpperCAmelCase__: Optional[Any] = FLAX_MODEL_FOR_MASKED_LM_MAPPING A_ : Tuple = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class _a (_BaseAutoModelClass ): '''simple docstring''' UpperCAmelCase__: Dict = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING A_ : Dict = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class _a (_BaseAutoModelClass ): '''simple docstring''' UpperCAmelCase__: Dict = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING A_ : Tuple = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class _a (_BaseAutoModelClass ): '''simple docstring''' UpperCAmelCase__: Any = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING A_ : int = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class _a (_BaseAutoModelClass ): '''simple docstring''' UpperCAmelCase__: Tuple = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING A_ : Dict = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class _a (_BaseAutoModelClass ): '''simple docstring''' UpperCAmelCase__: List[Any] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING A_ : Union[str, Any] = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class _a (_BaseAutoModelClass ): '''simple docstring''' UpperCAmelCase__: str = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING A_ : Optional[Any] = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class _a (_BaseAutoModelClass ): '''simple docstring''' UpperCAmelCase__: str = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING A_ : List[Any] = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class _a (_BaseAutoModelClass ): '''simple docstring''' UpperCAmelCase__: Dict = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING A_ : Union[str, Any] = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class _a (_BaseAutoModelClass ): '''simple docstring''' UpperCAmelCase__: int = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING A_ : List[str] = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
141
0
"""simple docstring""" import argparse import torch from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = LxmertConfig.from_json_file(_UpperCamelCase ) print(f"Building PyTorch model from configuration: {config}" ) __lowerCAmelCase = LxmertForPreTraining(_UpperCamelCase ) # Load weights from tf checkpoint load_tf_weights_in_lxmert(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _UpperCamelCase ) if __name__ == "__main__": A : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) A : int = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
57
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = False while is_sorted is False: # Until all the indices are traversed keep looping __lowerCAmelCase = True for i in range(0 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase = False for i in range(1 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase = False return input_list if __name__ == "__main__": print("Enter list to be sorted") A : Union[str, Any] = [int(x) for x in input().split()] # inputing elements of the list in one line A : str = odd_even_sort(input_list) print("The sorted list is") print(sorted_list)
57
1
from collections import Counter from timeit import timeit def __A ( __lowerCamelCase = "" , ) -> bool: return sum(c % 2 for c in Counter(input_str.replace(""" """ , """""" ).lower() ).values() ) < 2 def __A ( __lowerCamelCase = "" ) -> bool: if len(__lowerCamelCase ) == 0: return True a = input_str.replace(""" """ , """""" ).lower() # character_freq_dict: Stores the frequency of every character in the input string a = {} for character in lower_case_input_str: a = character_freq_dict.get(__lowerCamelCase , 0 ) + 1 a = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def __A ( __lowerCamelCase = "" ) -> None: print("""\nFor string = """ , __lowerCamelCase , """:""" ) print( """> can_string_be_rearranged_as_palindrome_counter()""" , """\tans =""" , can_string_be_rearranged_as_palindrome_counter(__lowerCamelCase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome_counter(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) print( """> can_string_be_rearranged_as_palindrome()""" , """\tans =""" , can_string_be_rearranged_as_palindrome(__lowerCamelCase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) if __name__ == "__main__": __UpperCamelCase : Tuple = input( "Enter string to determine if it can be rearranged as a palindrome or not: " ).strip() benchmark(check_str) __UpperCamelCase : str = can_string_be_rearranged_as_palindrome_counter(check_str) print(F'{check_str} can {"" if status else "not "}be rearranged as a palindrome')
367
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __lowerCAmelCase ( unittest.TestCase ): def __init__( self :List[str] , __magic_name__ :List[str] , __magic_name__ :List[Any]=13 , __magic_name__ :Any=7 , __magic_name__ :Optional[int]=True , __magic_name__ :List[Any]=True , __magic_name__ :Optional[int]=True , __magic_name__ :Union[str, Any]=True , __magic_name__ :Any=99 , __magic_name__ :List[str]=32 , __magic_name__ :List[str]=5 , __magic_name__ :str=4 , __magic_name__ :str=37 , __magic_name__ :Optional[int]="gelu" , __magic_name__ :int=0.1 , __magic_name__ :Dict=0.1 , __magic_name__ :List[str]=512 , __magic_name__ :Tuple=16 , __magic_name__ :Tuple=2 , __magic_name__ :List[str]=0.02 , __magic_name__ :Any=4 , ): '''simple docstring''' a = parent a = batch_size a = seq_length a = is_training a = use_attention_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_choices def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_attention_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a = RoFormerConfig( 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=__magic_name__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): UpperCamelCase__ = True UpperCamelCase__ = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = FlaxRoFormerModelTester(self ) @slow def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=__magic_name__ ) a = model(np.ones((1, 1) ) ) self.assertIsNotNone(__magic_name__ ) @require_flax class __lowerCAmelCase ( unittest.TestCase ): @slow def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) a = jnp.array([[0, 1, 2, 3, 4, 5]] ) a = model(__magic_name__ )[0] a = 5_0000 a = (1, 6, vocab_size) self.assertEqual(output.shape , __magic_name__ ) a = jnp.array( [[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , __magic_name__ , atol=1E-4 ) )
347
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class __snake_case : def __init__( self , lowercase , lowercase=13 , lowercase=7 , lowercase=True , lowercase=True , lowercase=True , lowercase=True , lowercase=99 , lowercase=32 , lowercase=2 , lowercase=4 , lowercase=37 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=5_12 , lowercase=16 , lowercase=2 , lowercase=0.02 , lowercase=False , lowercase=True , lowercase="None" , lowercase=3 , lowercase=4 , lowercase=None , ) -> Union[str, Any]: '''simple docstring''' a__: Union[str, Any] = parent a__: str = batch_size a__: List[str] = seq_length a__: int = is_training a__: Union[str, Any] = use_input_mask a__: str = use_token_type_ids a__: Union[str, Any] = use_labels a__: Any = vocab_size a__: str = hidden_size a__: Tuple = num_hidden_layers a__: Optional[Any] = num_attention_heads a__: Dict = intermediate_size a__: Tuple = hidden_act a__: List[Any] = hidden_dropout_prob a__: Tuple = attention_probs_dropout_prob a__: int = max_position_embeddings a__: int = type_vocab_size a__: Any = type_sequence_label_size a__: Optional[int] = initializer_range a__: List[Any] = num_labels a__: Optional[Any] = num_choices a__: Union[str, Any] = relative_attention a__: Optional[int] = position_biased_input a__: Tuple = pos_att_type a__: Union[str, Any] = scope def lowerCamelCase_ ( self) -> Any: '''simple docstring''' a__: Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) a__: str = None if self.use_input_mask: a__: List[str] = random_attention_mask([self.batch_size, self.seq_length]) a__: List[Any] = None if self.use_token_type_ids: a__: Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) a__: str = None a__: List[str] = None a__: List[Any] = None if self.use_labels: a__: List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size) a__: Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) a__: List[Any] = DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=lowercase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> Dict: '''simple docstring''' a__: Union[str, Any] = TFDebertaVaModel(config=lowercase) a__: Dict = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} a__: Optional[Any] = [input_ids, input_mask] a__: Optional[Any] = model(lowercase) a__: int = model(lowercase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def lowerCamelCase_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> List[Any]: '''simple docstring''' a__: Optional[Any] = TFDebertaVaForMaskedLM(config=lowercase) a__: Optional[int] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } a__: Any = model(lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def lowerCamelCase_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> Optional[int]: '''simple docstring''' a__: Dict = self.num_labels a__: Union[str, Any] = TFDebertaVaForSequenceClassification(config=lowercase) a__: Optional[int] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } a__: List[Any] = model(lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def lowerCamelCase_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> List[Any]: '''simple docstring''' a__: int = self.num_labels a__: int = TFDebertaVaForTokenClassification(config=lowercase) a__: Optional[int] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } a__: Any = model(lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def lowerCamelCase_ ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> List[str]: '''simple docstring''' a__: Dict = TFDebertaVaForQuestionAnswering(config=lowercase) a__: str = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } a__: List[str] = model(lowercase) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def lowerCamelCase_ ( self) -> int: '''simple docstring''' a__: List[Any] = self.prepare_config_and_inputs() ( ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ): Tuple = 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_tf class __snake_case ( __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase ): a__ = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) a__ = ( { """feature-extraction""": TFDebertaVaModel, """fill-mask""": TFDebertaVaForMaskedLM, """question-answering""": TFDebertaVaForQuestionAnswering, """text-classification""": TFDebertaVaForSequenceClassification, """token-classification""": TFDebertaVaForTokenClassification, """zero-shot""": TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) a__ = False a__ = False def lowerCamelCase_ ( self) -> Union[str, Any]: '''simple docstring''' a__: str = TFDebertaVaModelTester(self) a__: Any = ConfigTester(self , config_class=lowercase , hidden_size=37) def lowerCamelCase_ ( self) -> Tuple: '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase_ ( self) -> Any: '''simple docstring''' a__: str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase) def lowerCamelCase_ ( self) -> Any: '''simple docstring''' a__: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowercase) def lowerCamelCase_ ( self) -> Optional[Any]: '''simple docstring''' a__: Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase) def lowerCamelCase_ ( self) -> str: '''simple docstring''' a__: List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowercase) def lowerCamelCase_ ( self) -> Optional[Any]: '''simple docstring''' a__: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase) @slow def lowerCamelCase_ ( self) -> Optional[Any]: '''simple docstring''' a__: Optional[int] = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge') self.assertIsNotNone(lowercase) @require_tf class __snake_case ( unittest.TestCase ): @unittest.skip(reason='Model not available yet') def lowerCamelCase_ ( self) -> Tuple: '''simple docstring''' pass @slow def lowerCamelCase_ ( self) -> int: '''simple docstring''' a__: Tuple = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge') a__: Optional[int] = tf.constant([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]]) a__: Any = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) a__: Tuple = model(lowercase , attention_mask=lowercase)[0] a__: Optional[int] = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]]) tf.debugging.assert_near(output[:, 1:4, 1:4] , lowercase , atol=1e-4)
290
"""simple docstring""" import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() lowercase__ = logging.get_logger('transformers.models.encodec') lowercase__ = { 'quantizer.vq.layers.*._codebook.inited': 'quantizer.layers.*.codebook.inited', 'quantizer.vq.layers.*._codebook.cluster_size': 'quantizer.layers.*.codebook.cluster_size', 'quantizer.vq.layers.*._codebook.embed': 'quantizer.layers.*.codebook.embed', 'quantizer.vq.layers.*._codebook.embed_avg': 'quantizer.layers.*.codebook.embed_avg', } lowercase__ = { 'encoder.model.0.conv.conv': 'encoder.layers.0.conv', 'encoder.model.1.block.1.conv.conv': 'encoder.layers.1.block.1.conv', 'encoder.model.1.block.3.conv.conv': 'encoder.layers.1.block.3.conv', 'encoder.model.1.shortcut.conv.conv': 'encoder.layers.1.shortcut.conv', 'encoder.model.3.conv.conv': 'encoder.layers.3.conv', 'encoder.model.4.block.1.conv.conv': 'encoder.layers.4.block.1.conv', 'encoder.model.4.block.3.conv.conv': 'encoder.layers.4.block.3.conv', 'encoder.model.4.shortcut.conv.conv': 'encoder.layers.4.shortcut.conv', 'encoder.model.6.conv.conv': 'encoder.layers.6.conv', 'encoder.model.7.block.1.conv.conv': 'encoder.layers.7.block.1.conv', 'encoder.model.7.block.3.conv.conv': 'encoder.layers.7.block.3.conv', 'encoder.model.7.shortcut.conv.conv': 'encoder.layers.7.shortcut.conv', 'encoder.model.9.conv.conv': 'encoder.layers.9.conv', 'encoder.model.10.block.1.conv.conv': 'encoder.layers.10.block.1.conv', 'encoder.model.10.block.3.conv.conv': 'encoder.layers.10.block.3.conv', 'encoder.model.10.shortcut.conv.conv': 'encoder.layers.10.shortcut.conv', 'encoder.model.12.conv.conv': 'encoder.layers.12.conv', 'encoder.model.13.lstm': 'encoder.layers.13.lstm', 'encoder.model.15.conv.conv': 'encoder.layers.15.conv', } lowercase__ = { 'encoder.model.0.conv.norm': 'encoder.layers.0.norm', 'encoder.model.1.block.1.conv.norm': 'encoder.layers.1.block.1.norm', 'encoder.model.1.block.3.conv.norm': 'encoder.layers.1.block.3.norm', 'encoder.model.1.shortcut.conv.norm': 'encoder.layers.1.shortcut.norm', 'encoder.model.3.conv.norm': 'encoder.layers.3.norm', 'encoder.model.4.block.1.conv.norm': 'encoder.layers.4.block.1.norm', 'encoder.model.4.block.3.conv.norm': 'encoder.layers.4.block.3.norm', 'encoder.model.4.shortcut.conv.norm': 'encoder.layers.4.shortcut.norm', 'encoder.model.6.conv.norm': 'encoder.layers.6.norm', 'encoder.model.7.block.1.conv.norm': 'encoder.layers.7.block.1.norm', 'encoder.model.7.block.3.conv.norm': 'encoder.layers.7.block.3.norm', 'encoder.model.7.shortcut.conv.norm': 'encoder.layers.7.shortcut.norm', 'encoder.model.9.conv.norm': 'encoder.layers.9.norm', 'encoder.model.10.block.1.conv.norm': 'encoder.layers.10.block.1.norm', 'encoder.model.10.block.3.conv.norm': 'encoder.layers.10.block.3.norm', 'encoder.model.10.shortcut.conv.norm': 'encoder.layers.10.shortcut.norm', 'encoder.model.12.conv.norm': 'encoder.layers.12.norm', 'encoder.model.15.conv.norm': 'encoder.layers.15.norm', } lowercase__ = { 'decoder.model.0.conv.conv': 'decoder.layers.0.conv', 'decoder.model.1.lstm': 'decoder.layers.1.lstm', 'decoder.model.3.convtr.convtr': 'decoder.layers.3.conv', 'decoder.model.4.block.1.conv.conv': 'decoder.layers.4.block.1.conv', 'decoder.model.4.block.3.conv.conv': 'decoder.layers.4.block.3.conv', 'decoder.model.4.shortcut.conv.conv': 'decoder.layers.4.shortcut.conv', 'decoder.model.6.convtr.convtr': 'decoder.layers.6.conv', 'decoder.model.7.block.1.conv.conv': 'decoder.layers.7.block.1.conv', 'decoder.model.7.block.3.conv.conv': 'decoder.layers.7.block.3.conv', 'decoder.model.7.shortcut.conv.conv': 'decoder.layers.7.shortcut.conv', 'decoder.model.9.convtr.convtr': 'decoder.layers.9.conv', 'decoder.model.10.block.1.conv.conv': 'decoder.layers.10.block.1.conv', 'decoder.model.10.block.3.conv.conv': 'decoder.layers.10.block.3.conv', 'decoder.model.10.shortcut.conv.conv': 'decoder.layers.10.shortcut.conv', 'decoder.model.12.convtr.convtr': 'decoder.layers.12.conv', 'decoder.model.13.block.1.conv.conv': 'decoder.layers.13.block.1.conv', 'decoder.model.13.block.3.conv.conv': 'decoder.layers.13.block.3.conv', 'decoder.model.13.shortcut.conv.conv': 'decoder.layers.13.shortcut.conv', 'decoder.model.15.conv.conv': 'decoder.layers.15.conv', } lowercase__ = { 'decoder.model.0.conv.norm': 'decoder.layers.0.norm', 'decoder.model.3.convtr.norm': 'decoder.layers.3.norm', 'decoder.model.4.block.1.conv.norm': 'decoder.layers.4.block.1.norm', 'decoder.model.4.block.3.conv.norm': 'decoder.layers.4.block.3.norm', 'decoder.model.4.shortcut.conv.norm': 'decoder.layers.4.shortcut.norm', 'decoder.model.6.convtr.norm': 'decoder.layers.6.norm', 'decoder.model.7.block.1.conv.norm': 'decoder.layers.7.block.1.norm', 'decoder.model.7.block.3.conv.norm': 'decoder.layers.7.block.3.norm', 'decoder.model.7.shortcut.conv.norm': 'decoder.layers.7.shortcut.norm', 'decoder.model.9.convtr.norm': 'decoder.layers.9.norm', 'decoder.model.10.block.1.conv.norm': 'decoder.layers.10.block.1.norm', 'decoder.model.10.block.3.conv.norm': 'decoder.layers.10.block.3.norm', 'decoder.model.10.shortcut.conv.norm': 'decoder.layers.10.shortcut.norm', 'decoder.model.12.convtr.norm': 'decoder.layers.12.norm', 'decoder.model.13.block.1.conv.norm': 'decoder.layers.13.block.1.norm', 'decoder.model.13.block.3.conv.norm': 'decoder.layers.13.block.3.norm', 'decoder.model.13.shortcut.conv.norm': 'decoder.layers.13.shortcut.norm', 'decoder.model.15.conv.norm': 'decoder.layers.15.norm', } lowercase__ = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } lowercase__ = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } lowercase__ = [] lowercase__ = [] def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->int: for attribute in key.split('.' ): a__: str = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if weight_type is not None: a__: List[str] = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape else: a__: Optional[Any] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": a__: str = value elif weight_type == "weight_g": a__: int = value elif weight_type == "weight_v": a__: Tuple = value elif weight_type == "bias": a__: Dict = value elif weight_type == "running_mean": a__: Any = value elif weight_type == "running_var": a__: Tuple = value elif weight_type == "num_batches_tracked": a__: List[str] = value elif weight_type == "weight_ih_l0": a__: List[Any] = value elif weight_type == "weight_hh_l0": a__: List[Any] = value elif weight_type == "bias_ih_l0": a__: List[Any] = value elif weight_type == "bias_hh_l0": a__: List[Any] = value elif weight_type == "weight_ih_l1": a__: int = value elif weight_type == "weight_hh_l1": a__: str = value elif weight_type == "bias_ih_l1": a__: Union[str, Any] = value elif weight_type == "bias_hh_l1": a__: Any = value else: a__: Union[str, Any] = value logger.info(F'{key + ("." + weight_type if weight_type is not None else "")} was initialized from {full_name}.' ) def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Dict: for key in ignore_keys: if key.endswith('.*' ): if name.startswith(key[:-1] ): return True elif ".*." in key: a__ , a__: Optional[Any] = key.split('.*.' ) if prefix in name and suffix in name: return True elif key in name: return True return False def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[str]: a__: List[Any] = [] if model_name == "encodec_24khz" or "encodec_32khz": a__: Optional[int] = MAPPING_24K elif model_name == "encodec_48khz": a__: List[Any] = MAPPING_48K else: raise ValueError(F'Unsupported model: {model_name}' ) for name, value in orig_dict.items(): if should_ignore(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): logger.info(F'{name} was ignored' ) continue a__: int = False for key, mapped_key in MAPPING.items(): if "*" in key: a__ , a__: str = key.split('.*.' ) if prefix in name and suffix in name: a__: List[str] = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('embed' ) and name.endswith('embed_avg' ): continue a__: List[str] = True if "*" in mapped_key: a__: List[str] = name.split(_SCREAMING_SNAKE_CASE )[0].split('.' )[-2] a__: str = mapped_key.replace('*' , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: a__: int = 'weight_g' elif "weight_v" in name: a__: Dict = 'weight_v' elif "weight_ih_l0" in name: a__: int = 'weight_ih_l0' elif "weight_hh_l0" in name: a__: Union[str, Any] = 'weight_hh_l0' elif "bias_ih_l0" in name: a__: Optional[Any] = 'bias_ih_l0' elif "bias_hh_l0" in name: a__: Optional[int] = 'bias_hh_l0' elif "weight_ih_l1" in name: a__: Dict = 'weight_ih_l1' elif "weight_hh_l1" in name: a__: Optional[Any] = 'weight_hh_l1' elif "bias_ih_l1" in name: a__: List[str] = 'bias_ih_l1' elif "bias_hh_l1" in name: a__: Optional[Any] = 'bias_hh_l1' elif "bias" in name: a__: List[str] = 'bias' elif "weight" in name: a__: Any = 'weight' elif "running_mean" in name: a__: Dict = 'running_mean' elif "running_var" in name: a__: Dict = 'running_var' elif "num_batches_tracked" in name: a__: Dict = 'num_batches_tracked' else: a__: List[str] = None set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(F'Unused weights: {unused_weights}' ) @torch.no_grad() def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , ) ->int: if config_path is not None: a__: Dict = EncodecConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: a__: Tuple = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": a__: Any = [8, 5, 4, 4] a__: List[str] = [2.2] a__: List[Any] = 64 a__: Dict = 32000 a__: Union[str, Any] = 2048 a__: Union[str, Any] = False a__: Any = False a__: Optional[Any] = False elif model_name == "encodec_48khz": a__: Optional[int] = [8, 5, 4, 2] a__: Union[str, Any] = [3.0, 6.0, 12.0, 24.0] a__: List[str] = 48000 a__: Tuple = 2 a__: Optional[Any] = False a__: Optional[int] = 'time_group_norm' a__: Union[str, Any] = True a__: Dict = 1.0 a__: str = 0.01 else: raise ValueError(F'Unknown model name: {model_name}' ) a__: Optional[int] = EncodecModel(_SCREAMING_SNAKE_CASE ) a__: List[str] = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) a__: int = torch.load(_SCREAMING_SNAKE_CASE ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights a__: str = original_checkpoint['best_state'] recursively_load_weights(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) if repo_id: print('Pushing to the hub...' ) feature_extractor.push_to_hub(_SCREAMING_SNAKE_CASE ) model.push_to_hub(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowercase__ = argparse.ArgumentParser() parser.add_argument( '--model', default='encodec_24khz', type=str, help='The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.', ) parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.' ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) lowercase__ = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
290
1
from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { '''deepmind/language-perceiver''': '''https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json''', # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class lowerCamelCase__ ( _a ): _lowerCAmelCase = '''perceiver''' def __init__( self : Optional[Any] , _a : int=2_5_6 , _a : Dict=1_2_8_0 , _a : Dict=7_6_8 , _a : Union[str, Any]=1 , _a : Tuple=2_6 , _a : List[Any]=8 , _a : Optional[int]=8 , _a : Any=None , _a : List[str]=None , _a : Dict="kv" , _a : int=1 , _a : Tuple=1 , _a : int="gelu" , _a : int=0.1 , _a : Tuple=0.0_2 , _a : int=1e-12 , _a : List[Any]=True , _a : Optional[Any]=2_6_2 , _a : str=2_0_4_8 , _a : Tuple=5_6 , _a : int=[3_6_8, 4_9_6] , _a : Optional[int]=1_6 , _a : str=1_9_2_0 , _a : Union[str, Any]=1_6 , _a : Optional[Any]=[1, 1_6, 2_2_4, 2_2_4] , **_a : str , ): super().__init__(**_a ) a__: List[str] =num_latents a__: Any =d_latents a__: int =d_model a__: int =num_blocks a__: Any =num_self_attends_per_block a__: int =num_self_attention_heads a__: List[str] =num_cross_attention_heads a__: Optional[Any] =qk_channels a__: Tuple =v_channels a__: Union[str, Any] =cross_attention_shape_for_attention a__: Dict =self_attention_widening_factor a__: Tuple =cross_attention_widening_factor a__: Tuple =hidden_act a__: Union[str, Any] =attention_probs_dropout_prob a__: Union[str, Any] =initializer_range a__: Dict =layer_norm_eps a__: Optional[int] =use_query_residual # masked language modeling attributes a__: Optional[int] =vocab_size a__: List[str] =max_position_embeddings # image classification attributes a__: str =image_size # flow attributes a__: Optional[Any] =train_size # multimodal autoencoding attributes a__: Optional[Any] =num_frames a__: Dict =audio_samples_per_frame a__: Union[str, Any] =samples_per_patch a__: int =output_shape class lowerCamelCase__ ( _a ): @property def _lowerCamelCase ( self : List[Any] ): if self.task == "multiple-choice": a__: Dict ={0: "batch", 1: "choice", 2: "sequence"} else: a__: Optional[Any] ={0: "batch", 1: "sequence"} return OrderedDict( [ ("inputs", dynamic_axis), ("attention_mask", dynamic_axis), ] ) @property def _lowerCamelCase ( self : Any ): return 1e-4 def _lowerCamelCase ( self : List[Any] , _a : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , _a : int = -1 , _a : int = -1 , _a : int = -1 , _a : bool = False , _a : Optional[TensorType] = None , _a : int = 3 , _a : int = 4_0 , _a : int = 4_0 , ): # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(_a , _a ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX a__: Tuple =compute_effective_axis_dimension( _a , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX a__: Union[str, Any] =preprocessor.num_special_tokens_to_add(_a ) a__: Any =compute_effective_axis_dimension( _a , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=_a ) # Generate dummy inputs according to compute batch and sequence a__: Dict =[" ".join(["a"] ) * seq_length] * batch_size a__: int =dict(preprocessor(_a , return_tensors=_a ) ) a__: Optional[int] =inputs.pop("input_ids" ) return inputs elif isinstance(_a , _a ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX a__: str =compute_effective_axis_dimension(_a , fixed_dimension=OnnxConfig.default_fixed_batch ) a__: int =self._generate_dummy_images(_a , _a , _a , _a ) a__: Optional[Any] =dict(preprocessor(images=_a , return_tensors=_a ) ) a__: List[str] =inputs.pop("pixel_values" ) return inputs else: raise ValueError( "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor." )
42
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class lowerCamelCase__ ( _a , _a ): @register_to_config def __init__( self : str , _a : int = 7_6_8 , ): super().__init__() a__: Optional[Any] =nn.Parameter(torch.zeros(1 , _a ) ) a__: List[str] =nn.Parameter(torch.ones(1 , _a ) ) def _lowerCamelCase ( self : Tuple , _a : Optional[Union[str, torch.device]] = None , _a : Optional[torch.dtype] = None , ): a__: str =nn.Parameter(self.mean.to(_a ).to(_a ) ) a__: List[Any] =nn.Parameter(self.std.to(_a ).to(_a ) ) return self def _lowerCamelCase ( self : List[Any] , _a : Dict ): a__: str =(embeds - self.mean) * 1.0 / self.std return embeds def _lowerCamelCase ( self : List[Any] , _a : str ): a__: Optional[Any] =(embeds * self.std) + self.mean return embeds
42
1
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, BertTokenizerFast, BlipImageProcessor, GPTaTokenizer, InstructBlipProcessor, PreTrainedTokenizerFast, ) @require_vision class UpperCAmelCase_ ( unittest.TestCase): def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Any = tempfile.mkdtemp() _lowerCAmelCase : int = BlipImageProcessor() _lowerCAmelCase : Dict = GPTaTokenizer.from_pretrained("hf-internal-testing/tiny-random-GPT2Model") _lowerCAmelCase : Tuple = BertTokenizerFast.from_pretrained("hf-internal-testing/tiny-random-bert") _lowerCAmelCase : Optional[Any] = InstructBlipProcessor(__a, __a, __a) processor.save_pretrained(self.tmpdirname) def snake_case__ ( self, **__a): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname, **__a).tokenizer def snake_case__ ( self, **__a): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname, **__a).image_processor def snake_case__ ( self, **__a): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname, **__a).qformer_tokenizer def snake_case__ ( self): '''simple docstring''' shutil.rmtree(self.tmpdirname) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Dict = [np.random.randint(255, size=(3, 30, 400), dtype=np.uinta)] _lowerCAmelCase : Any = [Image.fromarray(np.moveaxis(__a, 0, -1)) for x in image_inputs] return image_inputs def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : List[Any] = InstructBlipProcessor( tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor(), qformer_tokenizer=self.get_qformer_tokenizer(), ) processor.save_pretrained(self.tmpdirname) _lowerCAmelCase : str = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)") _lowerCAmelCase : int = self.get_image_processor(do_normalize=__a, padding_value=1.0) _lowerCAmelCase : str = InstructBlipProcessor.from_pretrained( self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=__a, padding_value=1.0) self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer, __a) self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor, __a) self.assertIsInstance(processor.qformer_tokenizer, __a) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Tuple = self.get_image_processor() _lowerCAmelCase : int = self.get_tokenizer() _lowerCAmelCase : int = self.get_qformer_tokenizer() _lowerCAmelCase : Dict = InstructBlipProcessor( tokenizer=__a, image_processor=__a, qformer_tokenizer=__a) _lowerCAmelCase : int = self.prepare_image_inputs() _lowerCAmelCase : Union[str, Any] = image_processor(__a, return_tensors="np") _lowerCAmelCase : Any = processor(images=__a, return_tensors="np") for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1E-2) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[int] = self.get_image_processor() _lowerCAmelCase : Optional[Any] = self.get_tokenizer() _lowerCAmelCase : List[str] = self.get_qformer_tokenizer() _lowerCAmelCase : Union[str, Any] = InstructBlipProcessor( tokenizer=__a, image_processor=__a, qformer_tokenizer=__a) _lowerCAmelCase : List[str] = "lower newer" _lowerCAmelCase : str = processor(text=__a) _lowerCAmelCase : Dict = tokenizer(__a, return_token_type_ids=__a) _lowerCAmelCase : Union[str, Any] = qformer_tokenizer(__a, return_token_type_ids=__a) for key in encoded_tokens.keys(): self.assertListEqual(encoded_tokens[key], encoded_processor[key]) for key in encoded_tokens_qformer.keys(): self.assertListEqual(encoded_tokens_qformer[key], encoded_processor["qformer_" + key]) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : List[str] = self.get_image_processor() _lowerCAmelCase : List[str] = self.get_tokenizer() _lowerCAmelCase : Optional[int] = self.get_qformer_tokenizer() _lowerCAmelCase : List[str] = InstructBlipProcessor( tokenizer=__a, image_processor=__a, qformer_tokenizer=__a) _lowerCAmelCase : int = "lower newer" _lowerCAmelCase : Optional[Any] = self.prepare_image_inputs() _lowerCAmelCase : str = processor(text=__a, images=__a) self.assertListEqual( list(inputs.keys()), ["input_ids", "attention_mask", "qformer_input_ids", "qformer_attention_mask", "pixel_values"], ) # test if it raises when no input is passed with pytest.raises(__a): processor() def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Tuple = self.get_image_processor() _lowerCAmelCase : Union[str, Any] = self.get_tokenizer() _lowerCAmelCase : Dict = self.get_qformer_tokenizer() _lowerCAmelCase : Dict = InstructBlipProcessor( tokenizer=__a, image_processor=__a, qformer_tokenizer=__a) _lowerCAmelCase : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _lowerCAmelCase : str = processor.batch_decode(__a) _lowerCAmelCase : List[str] = tokenizer.batch_decode(__a) self.assertListEqual(__a, __a) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = self.get_image_processor() _lowerCAmelCase : List[str] = self.get_tokenizer() _lowerCAmelCase : Optional[int] = self.get_qformer_tokenizer() _lowerCAmelCase : Dict = InstructBlipProcessor( tokenizer=__a, image_processor=__a, qformer_tokenizer=__a) _lowerCAmelCase : Optional[Any] = "lower newer" _lowerCAmelCase : Tuple = self.prepare_image_inputs() _lowerCAmelCase : List[str] = processor(text=__a, images=__a) self.assertListEqual( list(inputs.keys()), ["input_ids", "attention_mask", "qformer_input_ids", "qformer_attention_mask", "pixel_values"], )
36
from PIL import Image def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase : int = image.size _lowerCAmelCase : Any = 0 _lowerCAmelCase : Tuple = image.load() for i in range(_lowerCamelCase ): for j in range(_lowerCamelCase ): _lowerCAmelCase : Union[str, Any] = pixels[j, i] mean += pixel mean //= width * height for j in range(_lowerCamelCase ): for i in range(_lowerCamelCase ): _lowerCAmelCase : Optional[Any] = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": _snake_case = mean_threshold(Image.open("path_to_image").convert("L")) image.save("output_image_path")
36
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} lowerCAmelCase_ = [ "small", "small-base", "medium", "medium-base", "intermediate", "intermediate-base", "large", "large-base", "xlarge", "xlarge-base", ] lowerCAmelCase_ = { "vocab_file": { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt", "funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt", "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt", "funnel-transformer/medium-base": ( "https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt" ), "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt", "funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt", "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt", "funnel-transformer/xlarge-base": ( "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json", "funnel-transformer/small-base": ( "https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json" ), "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json", "funnel-transformer/medium-base": ( "https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json" ), "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json", "funnel-transformer/large-base": ( "https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json" ), "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json", "funnel-transformer/xlarge-base": ( "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json" ), }, } lowerCAmelCase_ = {f"funnel-transformer/{name}": 5_1_2 for name in _model_names} lowerCAmelCase_ = {f"funnel-transformer/{name}": {"do_lower_case": True} for name in _model_names} class lowerCamelCase ( __lowerCAmelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_INIT_CONFIGURATION snake_case_ = FunnelTokenizer snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = 2 def __init__( self, lowercase_=None, lowercase_=None, lowercase_=True, lowercase_="<unk>", lowercase_="<sep>", lowercase_="<pad>", lowercase_="<cls>", lowercase_="<mask>", lowercase_="<s>", lowercase_="</s>", lowercase_=True, lowercase_=True, lowercase_=None, lowercase_="##", **lowercase_, ) -> Dict: 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_, bos_token=lowercase_, eos_token=lowercase_, clean_text=lowercase_, tokenize_chinese_chars=lowercase_, strip_accents=lowercase_, wordpieces_prefix=lowercase_, **lowercase_, ) snake_case = 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 ): snake_case = getattr(lowercase_, normalizer_state.pop('type' ) ) snake_case = do_lower_case snake_case = strip_accents snake_case = tokenize_chinese_chars snake_case = normalizer_class(**lowercase_ ) snake_case = do_lower_case def _lowerCamelCase ( self, lowercase_, lowercase_=None ) -> Optional[int]: snake_case = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _lowerCamelCase ( self, lowercase_, lowercase_ = None ) -> List[int]: snake_case = [self.sep_token_id] snake_case = [self.cls_token_id] if token_ids_a is None: return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowerCamelCase ( self, lowercase_, lowercase_ = None ) -> Tuple[str]: snake_case = self._tokenizer.model.save(lowercase_, name=lowercase_ ) return tuple(lowercase_ )
332
'''simple docstring''' from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time lowerCAmelCase_ = Lock() def __magic_name__ ( A , A , A , A , A , A , A ) -> Any: global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 1_0 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(A ) process_lock.release() # receive your right neighbor's value process_lock.acquire() snake_case = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left snake_case = min(A , A ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(A ) process_lock.release() # receive your left neighbor's value process_lock.acquire() snake_case = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right snake_case = max(A , A ) # after all swaps are performed, send the values back to main result_pipe[1].send(A ) def __magic_name__ ( A ) -> str: snake_case = [] snake_case = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop snake_case = Pipe() snake_case = Pipe() process_array_.append( Process( target=A , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) snake_case = temp_rs snake_case = temp_rr for i in range(1 , len(A ) - 1 ): snake_case = Pipe() snake_case = Pipe() process_array_.append( Process( target=A , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) snake_case = temp_rs snake_case = temp_rr process_array_.append( Process( target=A , args=( len(A ) - 1, arr[len(A ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(A ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(A ) ): snake_case = result_pipe[p][0].recv() process_array_[p].join() return arr def __magic_name__ ( ) -> Tuple: snake_case = list(range(1_0 , 0 , -1 ) ) print('Initial List' ) print(*A ) snake_case = odd_even_transposition(A ) print('Sorted List\n' ) print(*A ) if __name__ == "__main__": main()
332
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class _UpperCAmelCase ( metaclass=lowercase_ ): UpperCamelCase = ['''torch''', '''torchsde'''] def __init__( self :Optional[Any] , *__UpperCamelCase :Optional[int] , **__UpperCamelCase :Optional[Any] ): requires_backends(self , ["torch", "torchsde"] ) @classmethod def lowerCamelCase ( cls :Union[str, Any] , *__UpperCamelCase :List[str] , **__UpperCamelCase :Dict ): requires_backends(cls , ["torch", "torchsde"] ) @classmethod def lowerCamelCase ( cls :Union[str, Any] , *__UpperCamelCase :Union[str, Any] , **__UpperCamelCase :Dict ): requires_backends(cls , ["torch", "torchsde"] )
292
"""simple docstring""" from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) _snake_case : int = logging.get_logger(__name__) # pylint: disable=invalid-name _snake_case : List[Any] = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase=8 ): A = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 A = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class _UpperCAmelCase ( lowercase_ ): def __init__( self :Any , __UpperCamelCase :UNetaDConditionModel , __UpperCamelCase :DDPMScheduler , __UpperCamelCase :VQModel , ): super().__init__() self.register_modules( unet=__UpperCamelCase , scheduler=__UpperCamelCase , movq=__UpperCamelCase , ) A = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCamelCase ( self :Union[str, Any] , __UpperCamelCase :Tuple , __UpperCamelCase :Dict , __UpperCamelCase :Dict , __UpperCamelCase :List[str] , __UpperCamelCase :Optional[int] , __UpperCamelCase :List[str] ): if latents is None: A = randn_tensor(__UpperCamelCase , generator=__UpperCamelCase , device=__UpperCamelCase , dtype=__UpperCamelCase ) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}" ) A = latents.to(__UpperCamelCase ) A = latents * scheduler.init_noise_sigma return latents def lowerCamelCase ( self :Tuple , __UpperCamelCase :Any=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) A = torch.device(f"cuda:{gpu_id}" ) A = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__UpperCamelCase , __UpperCamelCase ) def lowerCamelCase ( self :Dict , __UpperCamelCase :int=0 ): if is_accelerate_available() and is_accelerate_version(">=" , "0.17.0.dev0" ): from accelerate import cpu_offload_with_hook else: raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher." ) A = torch.device(f"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to("cpu" , silence_dtype_warnings=__UpperCamelCase ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) A = None for cpu_offloaded_model in [self.unet, self.movq]: A, A = cpu_offload_with_hook(__UpperCamelCase , __UpperCamelCase , prev_module_hook=__UpperCamelCase ) # We'll offload the last model manually. A = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCamelCase ( self :str ): if not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(__UpperCamelCase , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(__UpperCamelCase ) def __call__( self :List[Any] , __UpperCamelCase :Union[torch.FloatTensor, List[torch.FloatTensor]] , __UpperCamelCase :Union[torch.FloatTensor, List[torch.FloatTensor]] , __UpperCamelCase :torch.FloatTensor , __UpperCamelCase :int = 5_12 , __UpperCamelCase :int = 5_12 , __UpperCamelCase :int = 1_00 , __UpperCamelCase :float = 4.0 , __UpperCamelCase :int = 1 , __UpperCamelCase :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __UpperCamelCase :Optional[torch.FloatTensor] = None , __UpperCamelCase :Optional[str] = "pil" , __UpperCamelCase :bool = True , ): A = self._execution_device A = guidance_scale > 1.0 if isinstance(__UpperCamelCase , __UpperCamelCase ): A = torch.cat(__UpperCamelCase , dim=0 ) if isinstance(__UpperCamelCase , __UpperCamelCase ): A = torch.cat(__UpperCamelCase , dim=0 ) if isinstance(__UpperCamelCase , __UpperCamelCase ): A = torch.cat(__UpperCamelCase , dim=0 ) A = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: A = image_embeds.repeat_interleave(__UpperCamelCase , dim=0 ) A = negative_image_embeds.repeat_interleave(__UpperCamelCase , dim=0 ) A = hint.repeat_interleave(__UpperCamelCase , dim=0 ) A = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=__UpperCamelCase ) A = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=__UpperCamelCase ) self.scheduler.set_timesteps(__UpperCamelCase , device=__UpperCamelCase ) A = self.scheduler.timesteps A = self.movq.config.latent_channels A, A = downscale_height_and_width(__UpperCamelCase , __UpperCamelCase , self.movq_scale_factor ) # create initial latent A = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , self.scheduler , ) for i, t in enumerate(self.progress_bar(__UpperCamelCase ) ): # expand the latents if we are doing classifier free guidance A = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents A = {"image_embeds": image_embeds, "hint": hint} A = self.unet( sample=__UpperCamelCase , timestep=__UpperCamelCase , encoder_hidden_states=__UpperCamelCase , added_cond_kwargs=__UpperCamelCase , return_dict=__UpperCamelCase , )[0] if do_classifier_free_guidance: A, A = noise_pred.split(latents.shape[1] , dim=1 ) A, A = noise_pred.chunk(2 ) A, A = variance_pred.chunk(2 ) A = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) A = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , "variance_type" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): A, A = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 A = self.scheduler.step( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , generator=__UpperCamelCase , )[0] # post-processing A = self.movq.decode(__UpperCamelCase , force_not_quantize=__UpperCamelCase )["sample"] if output_type not in ["pt", "np", "pil"]: raise ValueError(f"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}" ) if output_type in ["np", "pil"]: A = image * 0.5 + 0.5 A = image.clamp(0 , 1 ) A = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": A = self.numpy_to_pil(__UpperCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__UpperCamelCase )
292
1
"""simple docstring""" from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. __UpperCamelCase : int = 10 def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : list[int] , _UpperCAmelCase : int ): for i in range(_UpperCAmelCase , _UpperCAmelCase ): if array[i] == target: return i return -1 def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : list[int] , _UpperCAmelCase : int ): lowerCAmelCase = 0 lowerCAmelCase = len(_UpperCAmelCase ) while left <= right: if right - left < precision: return lin_search(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) lowerCAmelCase = (left + right) // 3 + 1 lowerCAmelCase = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: lowerCAmelCase = one_third - 1 elif array[two_third] < target: lowerCAmelCase = two_third + 1 else: lowerCAmelCase = one_third + 1 lowerCAmelCase = two_third - 1 else: return -1 def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : list[int] , _UpperCAmelCase : int ): if left < right: if right - left < precision: return lin_search(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) lowerCAmelCase = (left + right) // 3 + 1 lowerCAmelCase = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(_UpperCAmelCase , one_third - 1 , _UpperCAmelCase , _UpperCAmelCase ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , _UpperCAmelCase , _UpperCAmelCase ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() __UpperCamelCase : Optional[Any] = input('''Enter numbers separated by comma:\n''').strip() __UpperCamelCase : Any = [int(item.strip()) for item in user_input.split(''',''')] assert collection == sorted(collection), f"List must be ordered.\n{collection}." __UpperCamelCase : List[Any] = int(input('''Enter the number to be found in the list:\n''').strip()) __UpperCamelCase : Any = ite_ternary_search(collection, target) __UpperCamelCase : List[Any] = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f'''Iterative search: {target} found at positions: {resulta}''') print(f'''Recursive search: {target} found at positions: {resulta}''') else: print('''Not found''')
309
"""simple docstring""" from __future__ import annotations from decimal import Decimal from numpy import array def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : list[list[float]] ): lowerCAmelCase = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(_UpperCAmelCase ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix lowerCAmelCase = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError('This matrix has no inverse.' ) # Creates a copy of the matrix with swapped positions of the elements lowerCAmelCase = [[0.0, 0.0], [0.0, 0.0]] lowerCAmelCase ,lowerCAmelCase = matrix[1][1], matrix[0][0] lowerCAmelCase ,lowerCAmelCase = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(_UpperCAmelCase ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(_UpperCAmelCase ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule lowerCAmelCase = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError('This matrix has no inverse.' ) # Creating cofactor matrix lowerCAmelCase = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] lowerCAmelCase = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) lowerCAmelCase = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) lowerCAmelCase = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) lowerCAmelCase = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) lowerCAmelCase = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) lowerCAmelCase = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) lowerCAmelCase = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) lowerCAmelCase = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) lowerCAmelCase = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) lowerCAmelCase = array(_UpperCAmelCase ) for i in range(3 ): for j in range(3 ): lowerCAmelCase = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix lowerCAmelCase = array(_UpperCAmelCase ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(_UpperCAmelCase ) # Calculate the inverse of the matrix return [[float(d(_UpperCAmelCase ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError('Please provide a matrix of size 2x2 or 3x3.' )
309
1
'''simple docstring''' from pathlib import Path import numpy as np from PIL import Image def snake_case_ ( _lowerCAmelCase : np.ndarray ) -> np.ndarray: UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : Any = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2_9_8_9 * r + 0.5_8_7_0 * g + 0.1_1_4_0 * b def snake_case_ ( _lowerCAmelCase : np.ndarray ) -> np.ndarray: return (gray > 127) & (gray <= 255) def snake_case_ ( _lowerCAmelCase : np.ndarray , _lowerCAmelCase : np.ndarray ) -> np.ndarray: UpperCAmelCase : int = np.zeros_like(_lowerCAmelCase ) UpperCAmelCase : Dict = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image UpperCAmelCase : Dict = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): UpperCAmelCase : List[str] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() UpperCAmelCase : Any = int(summation > 0 ) return output if __name__ == "__main__": # read original image UpperCamelCase__: int = Path(__file__).resolve().parent / "image_data" / "lena.jpg" UpperCamelCase__: Optional[Any] = np.array(Image.open(lena_path)) # kernel to be applied UpperCamelCase__: Union[str, Any] = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) UpperCamelCase__: Optional[Any] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image UpperCamelCase__: Union[str, Any] = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
23
'''simple docstring''' from __future__ import annotations def snake_case_ ( _lowerCAmelCase : str , _lowerCAmelCase : str ) -> bool: UpperCAmelCase : str = get_failure_array(_lowerCAmelCase ) # 2) Step through text searching for pattern UpperCAmelCase , UpperCAmelCase : Optional[Any] = 0, 0 # index into text, pattern while i < len(_lowerCAmelCase ): if pattern[j] == text[i]: if j == (len(_lowerCAmelCase ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: UpperCAmelCase : Optional[Any] = failure[j - 1] continue i += 1 return False def snake_case_ ( _lowerCAmelCase : str ) -> list[int]: UpperCAmelCase : Optional[Any] = [0] UpperCAmelCase : str = 0 UpperCAmelCase : List[str] = 1 while j < len(_lowerCAmelCase ): if pattern[i] == pattern[j]: i += 1 elif i > 0: UpperCAmelCase : Union[str, Any] = failure[i - 1] continue j += 1 failure.append(_lowerCAmelCase ) return failure if __name__ == "__main__": # Test 1) UpperCamelCase__: str = "abc1abc12" UpperCamelCase__: str = "alskfjaldsabc1abc1abc12k23adsfabcabc" UpperCamelCase__: Any = "alskfjaldsk23adsfabcabc" assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) UpperCamelCase__: Tuple = "ABABX" UpperCamelCase__: Union[str, Any] = "ABABZABABYABABX" assert kmp(pattern, text) # Test 3) UpperCamelCase__: Any = "AAAB" UpperCamelCase__: str = "ABAAAAAB" assert kmp(pattern, text) # Test 4) UpperCamelCase__: int = "abcdabcy" UpperCamelCase__: Any = "abcxabcdabxabcdabcdabcy" assert kmp(pattern, text) # Test 5) UpperCamelCase__: List[str] = "aabaabaaa" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
23
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCAmelCase : List[Any] = { '''configuration_funnel''': ['''FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FunnelConfig'''], '''convert_funnel_original_tf_checkpoint_to_pytorch''': [], '''tokenization_funnel''': ['''FunnelTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Any = ['''FunnelTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Tuple = [ '''FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FunnelBaseModel''', '''FunnelForMaskedLM''', '''FunnelForMultipleChoice''', '''FunnelForPreTraining''', '''FunnelForQuestionAnswering''', '''FunnelForSequenceClassification''', '''FunnelForTokenClassification''', '''FunnelModel''', '''FunnelPreTrainedModel''', '''load_tf_weights_in_funnel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : int = [ '''TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFFunnelBaseModel''', '''TFFunnelForMaskedLM''', '''TFFunnelForMultipleChoice''', '''TFFunnelForPreTraining''', '''TFFunnelForQuestionAnswering''', '''TFFunnelForSequenceClassification''', '''TFFunnelForTokenClassification''', '''TFFunnelModel''', '''TFFunnelPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys _lowerCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
359
# 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. import copy import importlib.metadata import json import os from dataclasses import dataclass from typing import Any, Dict, Union from packaging import version from ..utils import is_torch_available, logging if is_torch_available(): import torch _lowerCAmelCase : str = logging.get_logger(__name__) @dataclass class __magic_name__ : """simple docstring""" def __init__( self :Dict , snake_case :List[str]=False , snake_case :Optional[Any]=False , snake_case :Union[str, Any]=6.0 , snake_case :Union[str, Any]=None , snake_case :Union[str, Any]=False , snake_case :str=False , snake_case :Optional[Any]=None , snake_case :int="fp4" , snake_case :int=False , **snake_case :Optional[Any] , ): '''simple docstring''' A_ : int = load_in_abit A_ : Union[str, Any] = load_in_abit A_ : str = llm_inta_threshold A_ : str = llm_inta_skip_modules A_ : List[Any] = llm_inta_enable_fpaa_cpu_offload A_ : Optional[int] = llm_inta_has_fpaa_weight A_ : Optional[int] = bnb_abit_quant_type A_ : Dict = bnb_abit_use_double_quant if bnb_abit_compute_dtype is None: A_ : List[Any] = torch.floataa elif isinstance(snake_case , snake_case ): A_ : Any = getattr(snake_case , snake_case ) elif isinstance(snake_case , torch.dtype ): A_ : Union[str, Any] = bnb_abit_compute_dtype else: raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype" ) self.post_init() def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' if not isinstance(self.llm_inta_threshold , snake_case ): raise ValueError("llm_int8_threshold must be a float" ) if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules , snake_case ): raise ValueError("llm_int8_skip_modules must be a list of strings" ) if not isinstance(self.llm_inta_enable_fpaa_cpu_offload , snake_case ): raise ValueError("llm_int8_enable_fp32_cpu_offload must be a boolean" ) if not isinstance(self.llm_inta_has_fpaa_weight , snake_case ): raise ValueError("llm_int8_has_fp16_weight must be a boolean" ) if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype , torch.dtype ): raise ValueError("bnb_4bit_compute_dtype must be torch.dtype" ) if not isinstance(self.bnb_abit_quant_type , snake_case ): raise ValueError("bnb_4bit_quant_type must be a string" ) if not isinstance(self.bnb_abit_use_double_quant , snake_case ): raise ValueError("bnb_4bit_use_double_quant must be a boolean" ) if self.load_in_abit and not version.parse(importlib.metadata.version("bitsandbytes" ) ) >= version.parse( "0.39.0" ): raise ValueError( "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version" ) def SCREAMING_SNAKE_CASE ( self :Union[str, Any] ): '''simple docstring''' return self.load_in_abit or self.load_in_abit def SCREAMING_SNAKE_CASE ( self :List[Any] ): '''simple docstring''' if self.load_in_abit: return "llm_int8" elif self.load_in_abit and self.bnb_abit_quant_type == "fp4": return "fp4" elif self.load_in_abit and self.bnb_abit_quant_type == "nf4": return "nf4" else: return None @classmethod def SCREAMING_SNAKE_CASE ( cls :List[str] , snake_case :Dict , snake_case :str , **snake_case :Dict ): '''simple docstring''' A_ : str = cls(**snake_case ) A_ : Any = [] for key, value in kwargs.items(): if hasattr(snake_case , snake_case ): setattr(snake_case , snake_case , snake_case ) to_remove.append(snake_case ) for key in to_remove: kwargs.pop(snake_case , snake_case ) if return_unused_kwargs: return config, kwargs else: return config def SCREAMING_SNAKE_CASE ( self :Tuple , snake_case :Union[str, os.PathLike] ): '''simple docstring''' with open(snake_case , "w" , encoding="utf-8" ) as writer: A_ : List[Any] = self.to_dict() A_ : int = json.dumps(snake_case , indent=2 , sort_keys=snake_case ) + "\n" writer.write(snake_case ) def SCREAMING_SNAKE_CASE ( self :List[str] ): '''simple docstring''' A_ : List[str] = copy.deepcopy(self.__dict__ ) A_ : Optional[int] = str(output["bnb_4bit_compute_dtype"] ).split("." )[1] return output def __repr__( self :List[str] ): '''simple docstring''' return f"{self.__class__.__name__} {self.to_json_string()}" def SCREAMING_SNAKE_CASE ( self :List[str] , snake_case :bool = True ): '''simple docstring''' if use_diff is True: A_ : List[str] = self.to_diff_dict() else: A_ : int = self.to_dict() return json.dumps(snake_case , indent=2 , sort_keys=snake_case ) + "\n" def SCREAMING_SNAKE_CASE ( self :Dict ): '''simple docstring''' A_ : List[Any] = self.to_dict() # get the default config dict A_ : Optional[Any] = BitsAndBytesConfig().to_dict() A_ : List[Any] = {} # only serialize values that differ from the default config for key, value in config_dict.items(): if value != default_config_dict[key]: A_ : int = value return serializable_config_dict
70
0
from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class __a : _a : Any = XGLMConfig _a : Optional[int] = {} _a : List[str] = 'gelu' def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=14 , _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=0.02 , ) -> Dict: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = seq_length _UpperCAmelCase = is_training _UpperCAmelCase = use_input_mask _UpperCAmelCase = use_labels _UpperCAmelCase = vocab_size _UpperCAmelCase = d_model _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = ffn_dim _UpperCAmelCase = activation_function _UpperCAmelCase = activation_dropout _UpperCAmelCase = attention_dropout _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = initializer_range _UpperCAmelCase = None _UpperCAmelCase = 0 _UpperCAmelCase = 2 _UpperCAmelCase = 1 def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" return XGLMConfig.from_pretrained('facebook/xglm-564M' ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 ) _UpperCAmelCase = None if self.use_input_mask: _UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCAmelCase = self.get_config() _UpperCAmelCase = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=_SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=_SCREAMING_SNAKE_CASE , ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = self.prepare_config_and_inputs() ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = config_and_inputs _UpperCAmelCase = { 'input_ids': input_ids, 'head_mask': head_mask, } return config, inputs_dict @require_tf class __a ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): _a : int = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () _a : int = (TFXGLMForCausalLM,) if is_tf_available() else () _a : int = ( {'feature-extraction': TFXGLMModel, 'text-generation': TFXGLMForCausalLM} if is_tf_available() else {} ) _a : Dict = False _a : int = False _a : Union[str, Any] = False def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = TFXGLMModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , n_embd=37 ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() @slow def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = TFXGLMModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.' ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" super().test_resize_token_embeddings() @require_tf class __a ( unittest.TestCase ): @slow def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE=True ) -> Dict: """simple docstring""" _UpperCAmelCase = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) _UpperCAmelCase = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa ) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off _UpperCAmelCase = [2, 268, 9865, 67, 11, 1988, 57252, 9865, 5, 984, 67, 1988, 213838, 1658, 53, 70446, 33, 6657, 278, 1581] # fmt: on _UpperCAmelCase = model.generate(_SCREAMING_SNAKE_CASE , do_sample=_SCREAMING_SNAKE_CASE , num_beams=1 ) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , _SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) _UpperCAmelCase = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) tf.random.set_seed(0 ) _UpperCAmelCase = tokenizer('Today is a nice day and' , return_tensors='tf' ) _UpperCAmelCase = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(':/CPU:0' ): _UpperCAmelCase = model.generate(_SCREAMING_SNAKE_CASE , do_sample=_SCREAMING_SNAKE_CASE , seed=[7, 0] ) _UpperCAmelCase = tokenizer.decode(output_ids[0] , skip_special_tokens=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due' ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) _UpperCAmelCase = XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) _UpperCAmelCase = 'left' # use different length sentences to test batching _UpperCAmelCase = [ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When', 'Hello, my dog is a little', ] _UpperCAmelCase = tokenizer(_SCREAMING_SNAKE_CASE , return_tensors='tf' , padding=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = inputs['input_ids'] _UpperCAmelCase = model.generate(input_ids=_SCREAMING_SNAKE_CASE , attention_mask=inputs['attention_mask'] , max_new_tokens=12 ) _UpperCAmelCase = tokenizer(sentences[0] , return_tensors='tf' ).input_ids _UpperCAmelCase = model.generate(input_ids=_SCREAMING_SNAKE_CASE , max_new_tokens=12 ) _UpperCAmelCase = tokenizer(sentences[1] , return_tensors='tf' ).input_ids _UpperCAmelCase = model.generate(input_ids=_SCREAMING_SNAKE_CASE , max_new_tokens=12 ) _UpperCAmelCase = tokenizer.batch_decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = tokenizer.decode(output_non_padded[0] , skip_special_tokens=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = tokenizer.decode(output_padded[0] , skip_special_tokens=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ' 'a single', 'Hello, my dog is a little bit of a shy one, but he is very friendly', ] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , [non_padded_sentence, padded_sentence] )
329
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ :int = logging.get_logger(__name__) lowerCAmelCase__ :Optional[Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class __a ( UpperCAmelCase ): _a : str = 'data2vec-text' def __init__( self , _SCREAMING_SNAKE_CASE=30522 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-1_2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = hidden_act _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = initializer_range _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = position_embedding_type _UpperCAmelCase = use_cache _UpperCAmelCase = classifier_dropout class __a ( UpperCAmelCase ): @property def UpperCAmelCase__ ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": _UpperCAmelCase = {0: 'batch', 1: 'choice', 2: 'sequence'} else: _UpperCAmelCase = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
329
1
def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _enforce_args(_a, _a ) if n == 0: return 0 _SCREAMING_SNAKE_CASE : int = float("-inf" ) for i in range(1, n + 1 ): _SCREAMING_SNAKE_CASE : str = max( _a, prices[i - 1] + naive_cut_rod_recursive(n - i, _a ) ) return max_revue def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _enforce_args(_a, _a ) _SCREAMING_SNAKE_CASE : Tuple = [float("-inf" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(_a, _a, _a ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: _SCREAMING_SNAKE_CASE : Dict = float("-inf" ) for i in range(1, n + 1 ): _SCREAMING_SNAKE_CASE : Optional[int] = max( _a, prices[i - 1] + _top_down_cut_rod_recursive(n - i, _a, _a ), ) _SCREAMING_SNAKE_CASE : str = max_revenue return max_rev[n] def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _enforce_args(_a, _a ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. _SCREAMING_SNAKE_CASE : Tuple = [float("-inf" ) for _ in range(n + 1 )] _SCREAMING_SNAKE_CASE : Optional[Any] = 0 for i in range(1, n + 1 ): _SCREAMING_SNAKE_CASE : Union[str, Any] = max_rev[i] for j in range(1, i + 1 ): _SCREAMING_SNAKE_CASE : Optional[int] = max(_a, prices[j - 1] + max_rev[i - j] ) _SCREAMING_SNAKE_CASE : str = max_revenue_i return max_rev[n] def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): if n < 0: _SCREAMING_SNAKE_CASE : int = f"""n must be greater than or equal to 0. Got n = {n}""" raise ValueError(_a ) if n > len(_a ): _SCREAMING_SNAKE_CASE : List[str] = ( """Each integral piece of rod must have a corresponding price. """ f"""Got n = {n} but length of prices = {len(_a )}""" ) raise ValueError(_a ) def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Dict = [6, 10, 12, 15, 20, 23] _SCREAMING_SNAKE_CASE : str = len(_a ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. _SCREAMING_SNAKE_CASE : Any = 36 _SCREAMING_SNAKE_CASE : Optional[Any] = top_down_cut_rod(_a, _a ) _SCREAMING_SNAKE_CASE : str = bottom_up_cut_rod(_a, _a ) _SCREAMING_SNAKE_CASE : Dict = naive_cut_rod_recursive(_a, _a ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
365
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ['image_processor', 'tokenizer'] __snake_case = 'BlipImageProcessor' __snake_case = 'AutoTokenizer' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: super().__init__(__lowerCamelCase , __lowerCamelCase ) # add QFormer tokenizer _SCREAMING_SNAKE_CASE : List[str] = qformer_tokenizer def __call__( self , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = True , __lowerCamelCase = False , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = False , __lowerCamelCase = True , __lowerCamelCase = None , **__lowerCamelCase , ) -> BatchFeature: if images is None and text is None: raise ValueError("You have to specify at least images or text." ) _SCREAMING_SNAKE_CASE : Any = BatchFeature() if text is not None: _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) encoding.update(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = self.qformer_tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : str = qformer_text_encoding.pop("input_ids" ) _SCREAMING_SNAKE_CASE : List[Any] = qformer_text_encoding.pop("attention_mask" ) if images is not None: _SCREAMING_SNAKE_CASE : Optional[int] = self.image_processor(__lowerCamelCase , return_tensors=__lowerCamelCase ) encoding.update(__lowerCamelCase ) return encoding def UpperCamelCase_ ( self , *__lowerCamelCase , **__lowerCamelCase ) -> Union[str, Any]: return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase_ ( self , *__lowerCamelCase , **__lowerCamelCase ) -> str: return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def UpperCamelCase_ ( self ) -> str: _SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer.model_input_names _SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def UpperCamelCase_ ( self , __lowerCamelCase , **__lowerCamelCase ) -> Any: if os.path.isfile(__lowerCamelCase ): raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = os.path.join(__lowerCamelCase , "qformer_tokenizer" ) self.qformer_tokenizer.save_pretrained(__lowerCamelCase ) return super().save_pretrained(__lowerCamelCase , **__lowerCamelCase ) @classmethod def UpperCamelCase_ ( cls , __lowerCamelCase , **__lowerCamelCase ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained(__lowerCamelCase , subfolder="qformer_tokenizer" ) _SCREAMING_SNAKE_CASE : Optional[Any] = cls._get_arguments_from_pretrained(__lowerCamelCase , **__lowerCamelCase ) args.append(__lowerCamelCase ) return cls(*__lowerCamelCase )
325
0
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.utils import logging lowercase__ = logging.get_logger(__name__) # pylint: disable=invalid-name class __lowerCamelCase ( snake_case_ ): '''simple docstring''' def __init__( self : Any , a_ : List[Any] , a_ : Union[str, Any] , a_ : int , a_ : Union[str, Any] , a_ : List[Any] , a_ : Tuple , a_ : int , a_ : int , a_ : Tuple , ): super().__init__() if safety_checker is None: logger.warning( f'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure''' " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( speech_model=a_ , speech_processor=a_ , vae=a_ , text_encoder=a_ , tokenizer=a_ , unet=a_ , scheduler=a_ , feature_extractor=a_ , ) def lowerCamelCase ( self : Union[str, Any] , a_ : Union[str, Any] = "auto" ): if slice_size == "auto": lowerCAmelCase_ : int = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(a_ ) def lowerCamelCase ( self : int ): self.enable_attention_slicing(a_ ) @torch.no_grad() def __call__( self : str , a_ : Union[str, Any] , a_ : Optional[int]=1_60_00 , a_ : Tuple = 5_12 , a_ : int = 5_12 , a_ : Optional[Any] = 50 , a_ : int = 7.5 , a_ : Tuple = None , a_ : Any = 1 , a_ : Optional[int] = 0.0 , a_ : Any = None , a_ : int = None , a_ : str = "pil" , a_ : Union[str, Any] = True , a_ : Tuple = None , a_ : List[Any] = 1 , **a_ : Optional[int] , ): lowerCAmelCase_ : List[Any] = self.speech_processor.feature_extractor( a_ , return_tensors="pt" , sampling_rate=a_ ).input_features.to(self.device ) lowerCAmelCase_ : Optional[Any] = self.speech_model.generate(a_ , max_length=48_00_00 ) lowerCAmelCase_ : Any = self.speech_processor.tokenizer.batch_decode(a_ , skip_special_tokens=a_ , normalize=a_ )[ 0 ] if isinstance(a_ , a_ ): lowerCAmelCase_ : List[str] = 1 elif isinstance(a_ , a_ ): lowerCAmelCase_ : List[str] = len(a_ ) else: raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(a_ )}''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(a_ , a_ ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(a_ )}.''' ) # get prompt text embeddings lowerCAmelCase_ : List[str] = self.tokenizer( a_ , padding="max_length" , max_length=self.tokenizer.model_max_length , return_tensors="pt" , ) lowerCAmelCase_ : Tuple = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: lowerCAmelCase_ : Optional[int] = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" f''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) lowerCAmelCase_ : List[Any] = text_input_ids[:, : self.tokenizer.model_max_length] lowerCAmelCase_ : Optional[Any] = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Optional[Any] = text_embeddings.shape lowerCAmelCase_ : Tuple = text_embeddings.repeat(1 , a_ , 1 ) lowerCAmelCase_ : Optional[Any] = text_embeddings.view(bs_embed * num_images_per_prompt , a_ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. lowerCAmelCase_ : Optional[int] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: lowerCAmelCase_ : int = 42 if negative_prompt is None: lowerCAmelCase_ : Optional[int] = [""] * batch_size elif type(a_ ) is not type(a_ ): raise TypeError( f'''`negative_prompt` should be the same type to `prompt`, but got {type(a_ )} !=''' f''' {type(a_ )}.''' ) elif isinstance(a_ , a_ ): lowerCAmelCase_ : Union[str, Any] = [negative_prompt] elif batch_size != len(a_ ): raise ValueError( f'''`negative_prompt`: {negative_prompt} has batch size {len(a_ )}, but `prompt`:''' f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches''' " the batch size of `prompt`." ) else: lowerCAmelCase_ : str = negative_prompt lowerCAmelCase_ : Optional[Any] = text_input_ids.shape[-1] lowerCAmelCase_ : Dict = self.tokenizer( a_ , padding="max_length" , max_length=a_ , truncation=a_ , return_tensors="pt" , ) lowerCAmelCase_ : Dict = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method lowerCAmelCase_ : List[str] = uncond_embeddings.shape[1] lowerCAmelCase_ : Tuple = uncond_embeddings.repeat(1 , a_ , 1 ) lowerCAmelCase_ : Optional[Any] = uncond_embeddings.view(batch_size * num_images_per_prompt , a_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowerCAmelCase_ : 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`. lowerCAmelCase_ : List[str] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) lowerCAmelCase_ : List[str] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps lowerCAmelCase_ : Dict = torch.randn(a_ , generator=a_ , device="cpu" , dtype=a_ ).to( self.device ) else: lowerCAmelCase_ : 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}''' ) lowerCAmelCase_ : Tuple = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(a_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand lowerCAmelCase_ : Optional[Any] = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler lowerCAmelCase_ : 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] lowerCAmelCase_ : Any = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowerCAmelCase_ : Optional[Any] = {} if accepts_eta: lowerCAmelCase_ : Optional[int] = eta for i, t in enumerate(self.progress_bar(a_ ) ): # expand the latents if we are doing classifier free guidance lowerCAmelCase_ : str = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowerCAmelCase_ : Union[str, Any] = self.scheduler.scale_model_input(a_ , a_ ) # predict the noise residual lowerCAmelCase_ : List[Any] = self.unet(a_ , a_ , encoder_hidden_states=a_ ).sample # perform guidance if do_classifier_free_guidance: lowerCAmelCase_ , lowerCAmelCase_ : Any = noise_pred.chunk(2 ) lowerCAmelCase_ : Optional[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 lowerCAmelCase_ : List[str] = self.scheduler.step(a_ , a_ , a_ , **a_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(a_ , a_ , a_ ) lowerCAmelCase_ : int = 1 / 0.18215 * latents lowerCAmelCase_ : Tuple = self.vae.decode(a_ ).sample lowerCAmelCase_ : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 lowerCAmelCase_ : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": lowerCAmelCase_ : Optional[int] = self.numpy_to_pil(a_ ) if not return_dict: return image return StableDiffusionPipelineOutput(images=a_ , nsfw_content_detected=a_ )
241
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SegformerConfig, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() lowercase = logging.get_logger(__name__) def __UpperCAmelCase ( a_ , a_=False): snake_case_ = OrderedDict() for key, value in state_dict.items(): if encoder_only and not key.startswith('head'): snake_case_ = 'segformer.encoder.' + key if key.startswith('backbone'): snake_case_ = key.replace('backbone' , 'segformer.encoder') if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 snake_case_ = key[key.find('patch_embed') + len('patch_embed')] snake_case_ = key.replace(f'''patch_embed{idx}''' , f'''patch_embeddings.{int(a_)-1}''') if "norm" in key: snake_case_ = key.replace('norm' , 'layer_norm') if "segformer.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 snake_case_ = key[key.find('segformer.encoder.layer_norm') + len('segformer.encoder.layer_norm')] snake_case_ = key.replace(f'''layer_norm{idx}''' , f'''layer_norm.{int(a_)-1}''') if "layer_norm1" in key: snake_case_ = key.replace('layer_norm1' , 'layer_norm_1') if "layer_norm2" in key: snake_case_ = key.replace('layer_norm2' , 'layer_norm_2') if "block" in key: # replace for example block1 by block.0 snake_case_ = key[key.find('block') + len('block')] snake_case_ = key.replace(f'''block{idx}''' , f'''block.{int(a_)-1}''') if "attn.q" in key: snake_case_ = key.replace('attn.q' , 'attention.self.query') if "attn.proj" in key: snake_case_ = key.replace('attn.proj' , 'attention.output.dense') if "attn" in key: snake_case_ = key.replace('attn' , 'attention.self') if "fc1" in key: snake_case_ = key.replace('fc1' , 'dense1') if "fc2" in key: snake_case_ = key.replace('fc2' , 'dense2') if "linear_pred" in key: snake_case_ = key.replace('linear_pred' , 'classifier') if "linear_fuse" in key: snake_case_ = key.replace('linear_fuse.conv' , 'linear_fuse') snake_case_ = key.replace('linear_fuse.bn' , 'batch_norm') if "linear_c" in key: # replace for example linear_c4 by linear_c.3 snake_case_ = key[key.find('linear_c') + len('linear_c')] snake_case_ = key.replace(f'''linear_c{idx}''' , f'''linear_c.{int(a_)-1}''') if key.startswith('head'): snake_case_ = key.replace('head' , 'classifier') snake_case_ = value return new_state_dict def __UpperCAmelCase ( a_ , a_): # for each of the encoder blocks: for i in range(config.num_encoder_blocks): for j in range(config.depths[i]): # read in weights + bias of keys and values (which is a single matrix in the original implementation) snake_case_ = state_dict.pop(f'''segformer.encoder.block.{i}.{j}.attention.self.kv.weight''') snake_case_ = state_dict.pop(f'''segformer.encoder.block.{i}.{j}.attention.self.kv.bias''') # next, add keys and values (in that order) to the state dict snake_case_ = kv_weight[ : config.hidden_sizes[i], : ] snake_case_ = kv_bias[: config.hidden_sizes[i]] snake_case_ = kv_weight[ config.hidden_sizes[i] :, : ] snake_case_ = kv_bias[ config.hidden_sizes[i] : ] def __UpperCAmelCase ( ): snake_case_ = 'http://images.cocodataset.org/val2017/000000039769.jpg' snake_case_ = Image.open(requests.get(a_ , stream=a_).raw) return image @torch.no_grad() def __UpperCAmelCase ( a_ , a_ , a_): snake_case_ = SegformerConfig() snake_case_ = False # set attributes based on model_name snake_case_ = 'huggingface/label-files' if "segformer" in model_name: snake_case_ = model_name[len('segformer.') : len('segformer.') + 2] if "ade" in model_name: snake_case_ = 1_50 snake_case_ = 'ade20k-id2label.json' snake_case_ = (1, 1_50, 1_28, 1_28) elif "city" in model_name: snake_case_ = 19 snake_case_ = 'cityscapes-id2label.json' snake_case_ = (1, 19, 1_28, 1_28) else: raise ValueError(f'''Model {model_name} not supported''') elif "mit" in model_name: snake_case_ = True snake_case_ = model_name[4:6] snake_case_ = 10_00 snake_case_ = 'imagenet-1k-id2label.json' snake_case_ = (1, 10_00) else: raise ValueError(f'''Model {model_name} not supported''') # set config attributes snake_case_ = json.load(open(hf_hub_download(a_ , a_ , repo_type='dataset') , 'r')) snake_case_ = {int(a_): v for k, v in idalabel.items()} snake_case_ = idalabel snake_case_ = {v: k for k, v in idalabel.items()} if size == "b0": pass elif size == "b1": snake_case_ = [64, 1_28, 3_20, 5_12] snake_case_ = 2_56 elif size == "b2": snake_case_ = [64, 1_28, 3_20, 5_12] snake_case_ = 7_68 snake_case_ = [3, 4, 6, 3] elif size == "b3": snake_case_ = [64, 1_28, 3_20, 5_12] snake_case_ = 7_68 snake_case_ = [3, 4, 18, 3] elif size == "b4": snake_case_ = [64, 1_28, 3_20, 5_12] snake_case_ = 7_68 snake_case_ = [3, 8, 27, 3] elif size == "b5": snake_case_ = [64, 1_28, 3_20, 5_12] snake_case_ = 7_68 snake_case_ = [3, 6, 40, 3] else: raise ValueError(f'''Size {size} not supported''') # load image processor (only resize + normalize) snake_case_ = SegformerImageProcessor( image_scale=(5_12, 5_12) , keep_ratio=a_ , align=a_ , do_random_crop=a_) # prepare image snake_case_ = prepare_img() snake_case_ = image_processor(images=a_ , return_tensors='pt').pixel_values logger.info(f'''Converting model {model_name}...''') # load original state dict if encoder_only: snake_case_ = torch.load(a_ , map_location=torch.device('cpu')) else: snake_case_ = torch.load(a_ , map_location=torch.device('cpu'))['state_dict'] # rename keys snake_case_ = rename_keys(a_ , encoder_only=a_) if not encoder_only: del state_dict["decode_head.conv_seg.weight"] del state_dict["decode_head.conv_seg.bias"] # key and value matrices need special treatment read_in_k_v(a_ , a_) # create HuggingFace model and load state dict if encoder_only: snake_case_ = False snake_case_ = SegformerForImageClassification(a_) else: snake_case_ = SegformerForSemanticSegmentation(a_) model.load_state_dict(a_) model.eval() # forward pass snake_case_ = model(a_) snake_case_ = outputs.logits # set expected_slice based on model name # ADE20k checkpoints if model_name == "segformer.b0.512x512.ade.160k": snake_case_ = torch.tensor( [ [[-4.63_10, -5.52_32, -6.23_56], [-5.19_21, -6.14_44, -6.59_96], [-5.44_24, -6.27_90, -6.75_74]], [[-12.13_91, -13.31_22, -13.95_54], [-12.87_32, -13.93_52, -14.35_63], [-12.94_38, -13.82_26, -14.25_13]], [[-12.51_34, -13.46_86, -14.49_15], [-12.86_69, -14.43_43, -14.77_58], [-13.25_23, -14.58_19, -15.06_94]], ]) elif model_name == "segformer.b1.512x512.ade.160k": snake_case_ = torch.tensor( [ [[-7.58_20, -8.72_31, -8.32_15], [-8.06_00, -10.35_29, -10.03_04], [-7.52_08, -9.41_03, -9.62_39]], [[-12.69_18, -13.89_94, -13.71_37], [-13.31_96, -15.75_23, -15.47_89], [-12.93_43, -14.87_57, -14.96_89]], [[-11.19_11, -11.94_21, -11.32_43], [-11.33_42, -13.68_39, -13.35_81], [-10.39_09, -12.18_32, -12.48_58]], ]) elif model_name == "segformer.b2.512x512.ade.160k": snake_case_ = torch.tensor( [ [[-11.81_73, -14.38_50, -16.31_28], [-14.56_48, -16.58_04, -18.65_68], [-14.72_23, -15.73_87, -18.42_18]], [[-15.72_90, -17.91_71, -19.44_23], [-18.31_05, -19.94_48, -21.46_61], [-17.92_96, -18.64_97, -20.79_10]], [[-15.07_83, -17.03_36, -18.27_89], [-16.87_71, -18.68_70, -20.16_12], [-16.24_54, -17.14_26, -19.50_55]], ]) elif model_name == "segformer.b3.512x512.ade.160k": snake_case_ = torch.tensor( [ [[-9.08_78, -10.20_81, -10.18_91], [-9.31_44, -10.79_41, -10.98_43], [-9.22_94, -10.38_55, -10.57_04]], [[-12.23_16, -13.90_68, -13.61_02], [-12.91_61, -14.37_02, -14.32_35], [-12.52_33, -13.71_74, -13.79_32]], [[-14.62_75, -15.24_90, -14.97_27], [-14.34_00, -15.96_87, -16.28_27], [-14.14_84, -15.40_33, -15.89_37]], ]) elif model_name == "segformer.b4.512x512.ade.160k": snake_case_ = torch.tensor( [ [[-12.31_44, -13.24_47, -14.08_02], [-13.36_14, -14.58_16, -15.61_17], [-13.33_40, -14.44_33, -16.22_19]], [[-19.27_81, -20.41_28, -20.75_06], [-20.61_53, -21.65_66, -22.09_98], [-19.98_00, -21.04_30, -22.14_94]], [[-18.87_39, -19.78_04, -21.18_34], [-20.12_33, -21.67_65, -23.29_44], [-20.03_15, -21.26_41, -23.69_44]], ]) elif model_name == "segformer.b5.640x640.ade.160k": snake_case_ = torch.tensor( [ [[-9.55_24, -12.08_35, -11.73_48], [-10.52_29, -13.64_46, -14.56_62], [-9.58_42, -12.88_51, -13.94_14]], [[-15.34_32, -17.53_23, -17.08_18], [-16.33_30, -18.92_55, -19.21_01], [-15.13_40, -17.78_48, -18.39_71]], [[-12.60_72, -14.94_86, -14.66_31], [-13.76_29, -17.09_07, -17.77_45], [-12.78_99, -16.16_95, -17.16_71]], ]) # Cityscapes checkpoints elif model_name == "segformer.b0.1024x1024.city.160k": snake_case_ = torch.tensor( [ [[-11.92_95, -13.40_57, -14.81_06], [-13.34_31, -14.81_79, -15.37_81], [-14.28_36, -15.59_42, -16.15_88]], [[-11.49_06, -12.80_67, -13.65_64], [-13.11_89, -14.05_00, -14.15_43], [-13.87_48, -14.51_36, -14.87_89]], [[0.53_74, 0.10_67, -0.47_42], [0.11_41, -0.22_55, -0.70_99], [-0.30_00, -0.59_24, -1.31_05]], ]) elif model_name == "segformer.b0.512x1024.city.160k": snake_case_ = torch.tensor( [ [[-7.82_17, -9.87_67, -10.17_17], [-9.44_38, -10.90_58, -11.40_47], [-9.79_39, -12.34_95, -12.10_79]], [[-7.15_14, -9.53_36, -10.08_60], [-9.77_76, -11.68_22, -11.84_39], [-10.14_11, -12.76_55, -12.89_72]], [[0.30_21, 0.08_05, -0.23_10], [-0.03_28, -0.16_05, -0.27_14], [-0.14_08, -0.54_77, -0.69_76]], ]) elif model_name == "segformer.b0.640x1280.city.160k": snake_case_ = torch.tensor( [ [ [-1.1_372E01, -1.2_787E01, -1.3_477E01], [-1.2_536E01, -1.4_194E01, -1.4_409E01], [-1.3_217E01, -1.4_888E01, -1.5_327E01], ], [ [-1.4_791E01, -1.7_122E01, -1.8_277E01], [-1.7_163E01, -1.9_192E01, -1.9_533E01], [-1.7_897E01, -1.9_991E01, -2.0_315E01], ], [ [7.6_723E-01, 4.1_921E-01, -7.7_878E-02], [4.7_772E-01, 9.5_557E-03, -2.8_082E-01], [3.6_032E-01, -2.4_826E-01, -5.1_168E-01], ], ]) elif model_name == "segformer.b0.768x768.city.160k": snake_case_ = torch.tensor( [ [[-9.49_59, -11.30_87, -11.74_79], [-11.00_25, -12.65_40, -12.33_19], [-11.40_64, -13.04_87, -12.99_05]], [[-9.89_05, -11.30_84, -12.08_54], [-11.17_26, -12.76_98, -12.95_83], [-11.59_85, -13.32_78, -14.17_74]], [[0.22_13, 0.01_92, -0.24_66], [-0.17_31, -0.42_13, -0.48_74], [-0.31_26, -0.65_41, -1.13_89]], ]) elif model_name == "segformer.b1.1024x1024.city.160k": snake_case_ = torch.tensor( [ [[-13.57_48, -13.91_11, -12.65_00], [-14.35_00, -15.36_83, -14.23_28], [-14.75_32, -16.04_24, -15.60_87]], [[-17.16_51, -15.87_25, -12.96_53], [-17.25_80, -17.37_18, -14.82_23], [-16.60_58, -16.87_83, -16.74_52]], [[-3.64_56, -3.02_09, -1.42_03], [-3.07_97, -3.19_59, -2.00_00], [-1.87_57, -1.92_17, -1.69_97]], ]) elif model_name == "segformer.b2.1024x1024.city.160k": snake_case_ = torch.tensor( [ [[-16.09_76, -16.48_56, -17.39_62], [-16.62_34, -19.03_42, -19.76_85], [-16.09_00, -18.06_61, -19.11_80]], [[-18.47_50, -18.84_88, -19.50_74], [-19.40_30, -22.15_70, -22.59_77], [-19.11_91, -20.84_86, -22.37_83]], [[-4.51_78, -5.50_37, -6.51_09], [-5.08_84, -7.21_74, -8.03_34], [-4.41_56, -5.81_17, -7.29_70]], ]) elif model_name == "segformer.b3.1024x1024.city.160k": snake_case_ = torch.tensor( [ [[-14.20_81, -14.47_32, -14.19_77], [-14.58_67, -16.44_23, -16.63_56], [-13.44_41, -14.96_85, -16.86_96]], [[-14.45_76, -14.70_73, -15.04_51], [-15.08_16, -17.62_37, -17.98_73], [-14.42_13, -16.01_99, -18.59_92]], [[-4.73_49, -4.95_88, -5.09_66], [-4.32_10, -6.93_25, -7.25_91], [-3.43_12, -4.74_84, -7.19_17]], ]) elif model_name == "segformer.b4.1024x1024.city.160k": snake_case_ = torch.tensor( [ [[-11.77_37, -11.95_26, -11.32_73], [-13.66_92, -14.45_74, -13.88_78], [-13.89_37, -14.69_24, -15.93_45]], [[-14.67_06, -14.53_30, -14.13_06], [-16.15_02, -16.81_80, -16.42_69], [-16.83_38, -17.89_39, -20.17_46]], [[1.04_91, 0.82_89, 1.03_10], [1.10_44, 0.52_19, 0.80_55], [1.08_99, 0.69_26, 0.55_90]], ]) elif model_name == "segformer.b5.1024x1024.city.160k": snake_case_ = torch.tensor( [ [[-12.56_41, -13.47_77, -13.06_84], [-13.95_87, -15.89_83, -16.65_57], [-13.31_09, -15.73_50, -16.31_41]], [[-14.70_74, -15.43_52, -14.59_44], [-16.63_53, -18.16_63, -18.61_20], [-15.17_02, -18.03_29, -18.15_47]], [[-1.79_90, -2.09_51, -1.77_84], [-2.63_97, -3.82_45, -3.96_86], [-1.52_64, -2.81_26, -2.93_16]], ]) else: snake_case_ = logits.argmax(-1).item() print('Predicted class:' , model.config.idalabel[predicted_class_idx]) # verify logits if not encoder_only: assert logits.shape == expected_shape assert torch.allclose(logits[0, :3, :3, :3] , a_ , atol=1E-2) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''') Path(a_).mkdir(exist_ok=a_) model.save_pretrained(a_) image_processor.save_pretrained(a_) if __name__ == "__main__": lowercase = argparse.ArgumentParser() parser.add_argument( "--model_name", default="segformer.b0.512x512.ade.160k", type=str, help="Name of the model you'd like to convert.", ) parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original PyTorch checkpoint (.pth file)." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) lowercase = parser.parse_args() convert_segformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
178
0
import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Tuple: """simple docstring""" A__ = AutoConfig.from_pretrained(lowercase_ ) A__ = FlaxAutoModelForSeqaSeqLM.from_config(config=lowercase_ ) A__ = checkpoints.load_tax_checkpoint(lowercase_ ) A__ = '''wi_0''' in tax_model['''target''']['''encoder''']['''layers_0''']['''mlp'''] if config.model_type == "t5": A__ = '''SelfAttention''' if config.model_type == "longt5" and config.encoder_attention_type == "local": A__ = '''LocalSelfAttention''' elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": A__ = '''TransientGlobalSelfAttention''' else: raise ValueError( '''Given config is expected to have `model_type=\'t5\'`, or `model_type=\'longt5` with `encoder_attention_type`''' ''' attribute with a value from [\'local\', \'transient-global].''' ) # Encoder for layer_index in range(config.num_layers ): A__ = f"""layers_{str(lowercase_ )}""" # Self-Attention A__ = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''key''']['''kernel'''] A__ = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''out''']['''kernel'''] A__ = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''query''']['''kernel'''] A__ = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''value''']['''kernel'''] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": A__ = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''T5LayerNorm_0''']['''scale'''] # Layer Normalization A__ = tax_model['''target''']['''encoder'''][layer_name]['''pre_attention_layer_norm''']['''scale'''] if split_mlp_wi: A__ = tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wi_0''']['''kernel'''] A__ = tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wi_1''']['''kernel'''] else: A__ = tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wi''']['''kernel'''] A__ = tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wo''']['''kernel'''] # Layer Normalization A__ = tax_model['''target''']['''encoder'''][layer_name]['''pre_mlp_layer_norm''']['''scale'''] # Assigning A__ = flax_model.params['''encoder''']['''block'''][str(lowercase_ )]['''layer'''] A__ = tax_attention_key A__ = tax_attention_out A__ = tax_attention_query A__ = tax_attention_value A__ = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": A__ = tax_global_layer_norm if split_mlp_wi: A__ = tax_mlp_wi_a A__ = tax_mlp_wi_a else: A__ = tax_mlp_wi A__ = tax_mlp_wo A__ = tax_mlp_layer_norm A__ = flax_model_encoder_layer_block # Only for layer 0: A__ = tax_model['''target''']['''encoder''']['''relpos_bias''']['''rel_embedding'''].T A__ = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": A__ = tax_model['''target''']['''encoder''']['''side_relpos_bias''']['''rel_embedding'''].T A__ = tax_encoder_global_rel_embedding # Assigning A__ = tax_model['''target''']['''encoder''']['''encoder_norm''']['''scale'''] A__ = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): A__ = f"""layers_{str(lowercase_ )}""" # Self-Attention A__ = tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''key''']['''kernel'''] A__ = tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''out''']['''kernel'''] A__ = tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''query''']['''kernel'''] A__ = tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''value''']['''kernel'''] # Layer Normalization A__ = tax_model['''target''']['''decoder'''][layer_name]['''pre_self_attention_layer_norm'''][ '''scale''' ] # Encoder-Decoder-Attention A__ = tax_model['''target''']['''decoder'''][layer_name]['''encoder_decoder_attention'''] A__ = tax_enc_dec_attention_module['''key''']['''kernel'''] A__ = tax_enc_dec_attention_module['''out''']['''kernel'''] A__ = tax_enc_dec_attention_module['''query''']['''kernel'''] A__ = tax_enc_dec_attention_module['''value''']['''kernel'''] # Layer Normalization A__ = tax_model['''target''']['''decoder'''][layer_name]['''pre_cross_attention_layer_norm''']['''scale'''] # MLP if split_mlp_wi: A__ = tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wi_0''']['''kernel'''] A__ = tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wi_1''']['''kernel'''] else: A__ = tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wi''']['''kernel'''] A__ = tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wo''']['''kernel'''] # Layer Normalization A__ = tax_model['''target''']['''decoder'''][layer_name]['''pre_mlp_layer_norm''']['''scale'''] # Assigning A__ = flax_model.params['''decoder''']['''block'''][str(lowercase_ )]['''layer'''] A__ = tax_attention_key A__ = tax_attention_out A__ = tax_attention_query A__ = tax_attention_value A__ = tax_pre_attention_layer_norm A__ = tax_enc_dec_attention_key A__ = tax_enc_dec_attention_out A__ = tax_enc_dec_attention_query A__ = tax_enc_dec_attention_value A__ = tax_cross_layer_norm if split_mlp_wi: A__ = tax_mlp_wi_a A__ = tax_mlp_wi_a else: A__ = tax_mlp_wi A__ = tax_mlp_wo A__ = txa_mlp_layer_norm A__ = flax_model_decoder_layer_block # Decoder Normalization A__ = tax_model['''target''']['''decoder''']['''decoder_norm''']['''scale'''] A__ = txa_decoder_norm # Only for layer 0: A__ = tax_model['''target''']['''decoder''']['''relpos_bias''']['''rel_embedding'''].T A__ = tax_decoder_rel_embedding # Token Embeddings A__ = tax_model['''target''']['''token_embedder''']['''embedding'''] A__ = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: A__ = tax_model['''target''']['''decoder''']['''logits_dense''']['''kernel'''] flax_model.save_pretrained(lowercase_ ) print('''T5X Model was sucessfully converted!''' ) if __name__ == "__main__": _lowerCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( """--t5x_checkpoint_path""", default=None, type=str, required=True, help="""Path the T5X checkpoint.""" ) parser.add_argument("""--config_name""", default=None, type=str, required=True, help="""Config name of LongT5/T5 model.""") parser.add_argument( """--flax_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output FLAX model.""" ) _lowerCamelCase : Tuple = parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
231
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 UpperCamelCase_ : '''simple docstring''' def __init__( self : str , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any=14 , UpperCAmelCase__ : Any=7 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Tuple=False , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Tuple=99 , UpperCAmelCase__ : Optional[Any]=32 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : Any=4 , UpperCAmelCase__ : int=4 , UpperCAmelCase__ : Optional[Any]=37 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : Optional[Any]=512 , UpperCAmelCase__ : Union[str, Any]=0.02 , ) ->Any: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = use_token_type_ids A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = rotary_dim A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = initializer_range A__ = None A__ = vocab_size - 1 A__ = vocab_size - 1 A__ = vocab_size - 1 def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[str]: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length]) A__ = 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 SCREAMING_SNAKE_CASE ( self : Any) ->Optional[int]: '''simple docstring''' A__ = self.prepare_config_and_inputs() A__ , A__ , A__ = config_and_inputs A__ = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any]) ->Optional[int]: '''simple docstring''' A__ = 20 A__ = model_class_name(UpperCAmelCase__) A__ = model.init_cache(input_ids.shape[0] , UpperCAmelCase__) A__ = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='''i4''') A__ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1)[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1)) A__ = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , position_ids=UpperCAmelCase__ , ) A__ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='''i4''') A__ = model( input_ids[:, -1:] , attention_mask=UpperCAmelCase__ , past_key_values=outputs_cache.past_key_values , position_ids=UpperCAmelCase__ , ) A__ = model(UpperCAmelCase__) A__ = 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 SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int) ->Any: '''simple docstring''' A__ = 20 A__ = model_class_name(UpperCAmelCase__) A__ = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]))] , axis=-1 , ) A__ = model.init_cache(input_ids.shape[0] , UpperCAmelCase__) A__ = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1)[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1)) A__ = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , position_ids=UpperCAmelCase__ , ) A__ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='''i4''') A__ = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=UpperCAmelCase__ , position_ids=UpperCAmelCase__ , ) A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__) A__ = 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 UpperCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () UpperCAmelCase__ = (FlaxGPTJForCausalLM,) if is_flax_available() else () def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->List[Any]: '''simple docstring''' A__ = FlaxGPTJModelTester(self) def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Any: '''simple docstring''' for model_class_name in self.all_model_classes: A__ , A__ , A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Any: '''simple docstring''' for model_class_name in self.all_model_classes: A__ , A__ , A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) @tooslow def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Dict: '''simple docstring''' A__ = GPTaTokenizer.from_pretrained('''gpt2''' , pad_token='''<|endoftext|>''' , padding_side='''left''') A__ = tokenizer(['''Hello this is a long string''', '''Hey'''] , return_tensors='''np''' , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__) A__ = FlaxGPTJForCausalLM.from_pretrained('''EleutherAI/gpt-j-6B''') A__ = False A__ = model.config.eos_token_id A__ = jax.jit(model.generate) A__ = jit_generate( inputs['''input_ids'''] , attention_mask=inputs['''attention_mask'''] , pad_token_id=tokenizer.pad_token_id).sequences A__ = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__) A__ = [ '''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 SCREAMING_SNAKE_CASE ( self : Optional[int]) ->int: '''simple docstring''' A__ , A__ = 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 A__ = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__) A__ = {k: torch.tensor(v.tolist()) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class A__ = model_class.__name__[4:] # Skip the "Flax" at the beginning A__ = getattr(UpperCAmelCase__ , UpperCAmelCase__) A__ , A__ = pt_inputs['''input_ids'''].shape A__ = np.random.randint(0 , seq_length - 1 , size=(batch_size,)) for batch_idx, start_index in enumerate(UpperCAmelCase__): A__ = 0 A__ = 1 A__ = 0 A__ = 1 A__ = pt_model_class(UpperCAmelCase__).eval() A__ = model_class(UpperCAmelCase__ , dtype=jnp.floataa) A__ = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , UpperCAmelCase__) A__ = fx_state with torch.no_grad(): A__ = pt_model(**UpperCAmelCase__).to_tuple() A__ = 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__) A__ = model_class.from_pretrained(UpperCAmelCase__ , from_pt=UpperCAmelCase__) A__ = 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 SCREAMING_SNAKE_CASE ( self : Any) ->Optional[int]: '''simple docstring''' A__ , A__ = 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 A__ = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__) A__ = {k: torch.tensor(v.tolist()) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class A__ = model_class.__name__[4:] # Skip the "Flax" at the beginning A__ = getattr(UpperCAmelCase__ , UpperCAmelCase__) A__ = pt_model_class(UpperCAmelCase__).eval() A__ = model_class(UpperCAmelCase__ , dtype=jnp.floataa) A__ = load_flax_weights_in_pytorch_model(UpperCAmelCase__ , fx_model.params) A__ , A__ = pt_inputs['''input_ids'''].shape A__ = np.random.randint(0 , seq_length - 1 , size=(batch_size,)) for batch_idx, start_index in enumerate(UpperCAmelCase__): A__ = 0 A__ = 1 A__ = 0 A__ = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): A__ = pt_model(**UpperCAmelCase__).to_tuple() A__ = 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__) A__ = pt_model_class.from_pretrained(UpperCAmelCase__ , from_flax=UpperCAmelCase__) with torch.no_grad(): A__ = 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 SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[Any]: '''simple docstring''' for model_class_name in self.all_model_classes: A__ = model_class_name.from_pretrained('''EleutherAI/gpt-j-6B''') A__ = model(np.ones((1, 1))) self.assertIsNotNone(UpperCAmelCase__)
231
1
from __future__ import annotations from random import random class __magic_name__ : def __init__( self : List[str] , lowerCamelCase__ : int | None = None ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ : Union[str, Any] = value UpperCamelCase__ : Union[str, Any] = random() UpperCamelCase__ : List[str] = None UpperCamelCase__ : Optional[Any] = None def __repr__( self : Any ) -> str: '''simple docstring''' from pprint import pformat if self.left is None and self.right is None: return F"\'{self.value}: {self.prior:.5}\'" else: return pformat( {F"{self.value}: {self.prior:.5}": (self.left, self.right)} , indent=1 ) def __str__( self : Optional[Any] ) -> Tuple: '''simple docstring''' UpperCamelCase__ : int = str(self.value ) + ''' ''' UpperCamelCase__ : List[Any] = str(self.left or '''''' ) UpperCamelCase__ : Tuple = str(self.right or '''''' ) return value + left + right def _a ( SCREAMING_SNAKE_CASE : Node | None , SCREAMING_SNAKE_CASE : int ): """simple docstring""" if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: UpperCamelCase__ , UpperCamelCase__ : Union[str, Any] = split(root.left , lowercase__ ) return left, root else: UpperCamelCase__ , UpperCamelCase__ : str = split(root.right , lowercase__ ) return root, right def _a ( SCREAMING_SNAKE_CASE : Node | None , SCREAMING_SNAKE_CASE : Node | None ): """simple docstring""" if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: UpperCamelCase__ : List[str] = merge(left.right , lowercase__ ) return left else: UpperCamelCase__ : Tuple = merge(lowercase__ , right.left ) return right def _a ( SCREAMING_SNAKE_CASE : Node | None , SCREAMING_SNAKE_CASE : int ): """simple docstring""" UpperCamelCase__ : Any = Node(lowercase__ ) UpperCamelCase__ , UpperCamelCase__ : Tuple = split(lowercase__ , lowercase__ ) return merge(merge(lowercase__ , lowercase__ ) , lowercase__ ) def _a ( SCREAMING_SNAKE_CASE : Node | None , SCREAMING_SNAKE_CASE : int ): """simple docstring""" UpperCamelCase__ , UpperCamelCase__ : Union[str, Any] = split(lowercase__ , value - 1 ) UpperCamelCase__ , UpperCamelCase__ : Dict = split(lowercase__ , lowercase__ ) return merge(lowercase__ , lowercase__ ) def _a ( SCREAMING_SNAKE_CASE : Node | None ): """simple docstring""" if not root: # None return else: inorder(root.left ) print(root.value , end=''',''' ) inorder(root.right ) def _a ( SCREAMING_SNAKE_CASE : Node | None , SCREAMING_SNAKE_CASE : str ): """simple docstring""" for arg in args.split(): if arg[0] == "+": UpperCamelCase__ : List[str] = insert(lowercase__ , int(arg[1:] ) ) elif arg[0] == "-": UpperCamelCase__ : Union[str, Any] = erase(lowercase__ , int(arg[1:] ) ) else: print('''Unknown command''' ) return root def _a ( ): """simple docstring""" UpperCamelCase__ : List[str] = None print( '''enter numbers to create a tree, + value to add value into treap, ''' '''- value to erase all nodes with value. \'q\' to quit. ''' ) UpperCamelCase__ : List[str] = input() while args != "q": UpperCamelCase__ : str = interact_treap(lowercase__ , lowercase__ ) print(lowercase__ ) UpperCamelCase__ : Optional[Any] = input() print('''good by!''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
146
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, 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 lowerCAmelCase ( A , unittest.TestCase ): lowerCAmelCase_ = KandinskyVaaImgaImgPipeline lowerCAmelCase_ = ["image_embeds", "negative_image_embeds", "image"] lowerCAmelCase_ = [ "image_embeds", "negative_image_embeds", "image", ] lowerCAmelCase_ = [ "generator", "height", "width", "strength", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] lowerCAmelCase_ = False @property def snake_case ( self : List[str] ): """simple docstring""" return 32 @property def snake_case ( self : Any ): """simple docstring""" return 32 @property def snake_case ( self : List[str] ): """simple docstring""" return self.time_input_dim @property def snake_case ( self : str ): """simple docstring""" return self.time_input_dim * 4 @property def snake_case ( self : Union[str, Any] ): """simple docstring""" return 100 @property def snake_case ( self : str ): """simple docstring""" torch.manual_seed(0 ) __lowercase ={ 'in_channels': 4, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'image', '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, } __lowercase =UNetaDConditionModel(**__lowercase ) return model @property def snake_case ( self : Any ): """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["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", ], "vq_embed_dim": 4, } @property def snake_case ( self : str ): """simple docstring""" torch.manual_seed(0 ) __lowercase =VQModel(**self.dummy_movq_kwargs ) return model def snake_case ( self : Tuple ): """simple docstring""" __lowercase =self.dummy_unet __lowercase =self.dummy_movq __lowercase ={ 'num_train_timesteps': 1000, 'beta_schedule': 'linear', 'beta_start': 0.0_0_0_8_5, 'beta_end': 0.0_1_2, 'clip_sample': False, 'set_alpha_to_one': False, 'steps_offset': 0, 'prediction_type': 'epsilon', 'thresholding': False, } __lowercase =DDIMScheduler(**__lowercase ) __lowercase ={ 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def snake_case ( self : Optional[int] , __lowercase : Optional[int] , __lowercase : int=0 ): """simple docstring""" __lowercase =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__lowercase ) ).to(__lowercase ) __lowercase =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( __lowercase ) # create init_image __lowercase =floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowercase ) ).to(__lowercase ) __lowercase =image.cpu().permute(0 , 2 , 3 , 1 )[0] __lowercase =Image.fromarray(np.uinta(__lowercase ) ).convert('RGB' ).resize((256, 256) ) if str(__lowercase ).startswith('mps' ): __lowercase =torch.manual_seed(__lowercase ) else: __lowercase =torch.Generator(device=__lowercase ).manual_seed(__lowercase ) __lowercase ={ 'image': init_image, 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'generator': generator, 'height': 64, 'width': 64, 'num_inference_steps': 10, 'guidance_scale': 7.0, 'strength': 0.2, 'output_type': 'np', } return inputs def snake_case ( self : List[str] ): """simple docstring""" __lowercase ='cpu' __lowercase =self.get_dummy_components() __lowercase =self.pipeline_class(**__lowercase ) __lowercase =pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) __lowercase =pipe(**self.get_dummy_inputs(__lowercase ) ) __lowercase =output.images __lowercase =pipe( **self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0] __lowercase =image[0, -3:, -3:, -1] __lowercase =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowercase =np.array( [0.6_1_9_9_7_7_8, 0.6_3_9_8_4_4_0_6, 0.4_6_1_4_5_7_8_5, 0.6_2_9_4_4_9_8_4, 0.5_6_2_2_2_1_5, 0.4_7_3_0_6_1_3_2, 0.4_7_4_4_1_4_5_6, 0.4_6_0_7_6_0_6, 0.4_8_7_1_9_2_6_3] ) 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 lowerCAmelCase ( unittest.TestCase ): def snake_case ( self : Optional[int] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self : Any ): """simple docstring""" __lowercase =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_img2img_frog.npy' ) __lowercase =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) __lowercase ='A red cartoon frog, 4k' __lowercase =KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' , torch_dtype=torch.floataa ) pipe_prior.to(__lowercase ) __lowercase =KandinskyVaaImgaImgPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-decoder' , torch_dtype=torch.floataa ) __lowercase =pipeline.to(__lowercase ) pipeline.set_progress_bar_config(disable=__lowercase ) __lowercase =torch.Generator(device='cpu' ).manual_seed(0 ) __lowercase , __lowercase =pipe_prior( __lowercase , generator=__lowercase , num_inference_steps=5 , negative_prompt='' , ).to_tuple() __lowercase =pipeline( image=__lowercase , image_embeds=__lowercase , negative_image_embeds=__lowercase , generator=__lowercase , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type='np' , ) __lowercase =output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__lowercase , __lowercase )
141
0
"""simple docstring""" def lowercase_ ( _lowerCamelCase: str ) -> List[Any]: '''simple docstring''' __lowerCamelCase : Union[str, Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
358
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMForMultipleChoice''', '''XLMForQuestionAnswering''', '''XLMForQuestionAnsweringSimple''', '''XLMForSequenceClassification''', '''XLMForTokenClassification''', '''XLMModel''', '''XLMPreTrainedModel''', '''XLMWithLMHeadModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMForMultipleChoice''', '''TFXLMForQuestionAnsweringSimple''', '''TFXLMForSequenceClassification''', '''TFXLMForTokenClassification''', '''TFXLMMainLayer''', '''TFXLMModel''', '''TFXLMPreTrainedModel''', '''TFXLMWithLMHeadModel''', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
64
0
"""simple docstring""" import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse("0.12.2"): raise Exception("requires fairseq >= 0.12.2") if version.parse(fairseq.__version__) > version.parse("2"): raise Exception("requires fairseq < v2") logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = "Hello, World!" SCREAMING_SNAKE_CASE__ = "en_XX" def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : bool ): '''simple docstring''' lowerCAmelCase = Path("""data_bin""" ) lowerCAmelCase = FairseqXmodModel.from_pretrained( model_name_or_path=str(Path(SCREAMING_SNAKE_CASE ).parent ) , checkpoint_file=Path(SCREAMING_SNAKE_CASE ).name , _name="""xmod_base""" , arch="""xmod_base""" , task="""multilingual_masked_lm""" , data_name_or_path=str(SCREAMING_SNAKE_CASE ) , bpe="""sentencepiece""" , sentencepiece_model=str(Path(SCREAMING_SNAKE_CASE ).parent / """sentencepiece.bpe.model""" ) , src_dict=str(data_dir / """dict.txt""" ) , ) xmod.eval() # disable dropout print(SCREAMING_SNAKE_CASE ) lowerCAmelCase = xmod.model.encoder.sentence_encoder lowerCAmelCase = XmodConfig( vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_14 , type_vocab_size=1 , layer_norm_eps=1e-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , """bottleneck""" , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , ) if classification_head: lowerCAmelCase = xmod.model.classification_heads["""mnli"""].out_proj.weight.shape[0] print("""Our X-MOD config:""" , SCREAMING_SNAKE_CASE ) lowerCAmelCase = XmodForSequenceClassification(SCREAMING_SNAKE_CASE ) if classification_head else XmodForMaskedLM(SCREAMING_SNAKE_CASE ) model.eval() # Now let's copy all the weights. # Embeddings lowerCAmelCase = xmod_sent_encoder.embed_tokens.weight lowerCAmelCase = xmod_sent_encoder.embed_positions.weight lowerCAmelCase = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them. lowerCAmelCase = xmod_sent_encoder.layernorm_embedding.weight lowerCAmelCase = xmod_sent_encoder.layernorm_embedding.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer lowerCAmelCase = model.roberta.encoder.layer[i] lowerCAmelCase = xmod_sent_encoder.layers[i] # self attention lowerCAmelCase = layer.attention.self if not ( xmod_layer.self_attn.k_proj.weight.data.shape == xmod_layer.self_attn.q_proj.weight.data.shape == xmod_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ): raise AssertionError("""Dimensions of self-attention weights do not match.""" ) lowerCAmelCase = xmod_layer.self_attn.q_proj.weight lowerCAmelCase = xmod_layer.self_attn.q_proj.bias lowerCAmelCase = xmod_layer.self_attn.k_proj.weight lowerCAmelCase = xmod_layer.self_attn.k_proj.bias lowerCAmelCase = xmod_layer.self_attn.v_proj.weight lowerCAmelCase = xmod_layer.self_attn.v_proj.bias # self-attention output lowerCAmelCase = layer.attention.output if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape: raise AssertionError("""Dimensions of self-attention output weights do not match.""" ) lowerCAmelCase = xmod_layer.self_attn.out_proj.weight lowerCAmelCase = xmod_layer.self_attn.out_proj.bias lowerCAmelCase = xmod_layer.self_attn_layer_norm.weight lowerCAmelCase = xmod_layer.self_attn_layer_norm.bias # intermediate lowerCAmelCase = layer.intermediate if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError("""Dimensions of intermediate weights do not match.""" ) lowerCAmelCase = xmod_layer.fca.weight lowerCAmelCase = xmod_layer.fca.bias # output lowerCAmelCase = layer.output if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError("""Dimensions of feed-forward weights do not match.""" ) lowerCAmelCase = xmod_layer.fca.weight lowerCAmelCase = xmod_layer.fca.bias lowerCAmelCase = xmod_layer.final_layer_norm.weight lowerCAmelCase = xmod_layer.final_layer_norm.bias if bert_output.adapter_layer_norm is not None: lowerCAmelCase = xmod_layer.adapter_layer_norm.weight lowerCAmelCase = xmod_layer.adapter_layer_norm.bias if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ): raise AssertionError("""Lists of language adapters do not match.""" ) for lang_code, adapter in xmod_layer.adapter_modules.items(): lowerCAmelCase = bert_output.adapter_modules[lang_code] lowerCAmelCase = xmod_layer.adapter_modules[lang_code] lowerCAmelCase = from_adapter.fca.weight lowerCAmelCase = from_adapter.fca.bias lowerCAmelCase = from_adapter.fca.weight lowerCAmelCase = from_adapter.fca.bias # end of layer if xmod_sent_encoder.layer_norm is not None: lowerCAmelCase = xmod_sent_encoder.layer_norm.weight lowerCAmelCase = xmod_sent_encoder.layer_norm.bias if classification_head: lowerCAmelCase = xmod.model.classification_heads["""mnli"""].dense.weight lowerCAmelCase = xmod.model.classification_heads["""mnli"""].dense.bias lowerCAmelCase = xmod.model.classification_heads["""mnli"""].out_proj.weight lowerCAmelCase = xmod.model.classification_heads["""mnli"""].out_proj.bias else: # LM Head lowerCAmelCase = xmod.model.encoder.lm_head.dense.weight lowerCAmelCase = xmod.model.encoder.lm_head.dense.bias lowerCAmelCase = xmod.model.encoder.lm_head.layer_norm.weight lowerCAmelCase = xmod.model.encoder.lm_head.layer_norm.bias lowerCAmelCase = xmod.model.encoder.lm_head.weight lowerCAmelCase = xmod.model.encoder.lm_head.bias # Let's check that we get the same results. lowerCAmelCase = xmod.encode(SCREAMING_SNAKE_CASE ).unsqueeze(0 ) # batch of size 1 model.roberta.set_default_language(SCREAMING_SNAKE_CASE ) lowerCAmelCase = model(SCREAMING_SNAKE_CASE )[0] if classification_head: lowerCAmelCase = xmod.model.classification_heads["""mnli"""](xmod.extract_features(SCREAMING_SNAKE_CASE ) ) else: lowerCAmelCase = xmod.model(SCREAMING_SNAKE_CASE , lang_id=[SAMPLE_LANGUAGE] )[0] print(our_output.shape , their_output.shape ) lowerCAmelCase = torch.max(torch.abs(our_output - their_output ) ).item() print(F'max_absolute_diff = {max_absolute_diff}' ) # ~ 1e-7 lowerCAmelCase = torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) print("""Do both models output the same tensors?""" , """🔥""" if success else """💩""" ) if not success: raise Exception("""Something went wRoNg""" ) Path(SCREAMING_SNAKE_CASE ).mkdir(parents=SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) print(F'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xmod_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." ) parser.add_argument( "--classification_head", action="store_true", help="Whether to convert a final classification head." ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_xmod_checkpoint_to_pytorch( args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
46
from __future__ import annotations def lowerCAmelCase__ ( a__: dict , a__: str ) -> set[str]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = set(a__ ), [start] while stack: _UpperCAmelCase = stack.pop() explored.add(a__ ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(a__ ) return explored lowerCAmelCase__ :Tuple = { '''A''': ['''B''', '''C''', '''D'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F'''], '''D''': ['''B''', '''D'''], '''E''': ['''B''', '''F'''], '''F''': ['''C''', '''E''', '''G'''], '''G''': ['''F'''], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, '''A'''))
329
0
from typing import List import jiwer import jiwer.transforms as tr from packaging import version import datasets from datasets.config import PY_VERSION if PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata a_ = '' if version.parse(importlib_metadata.version('jiwer')) < version.parse('2.3.0'): class _lowercase ( tr.AbstractTransform ): def __init__( self : str , snake_case : str = " " ) -> List[str]: """simple docstring""" UpperCamelCase_ : Optional[Any] = sentence_delimiter def SCREAMING_SNAKE_CASE__ ( self : List[Any] , snake_case : str ) -> Optional[int]: """simple docstring""" return list(snake_case ) def SCREAMING_SNAKE_CASE__ ( self : List[str] , snake_case : List[str] ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ : Tuple = [] for sent_idx, sentence in enumerate(snake_case ): chars.extend(self.process_string(snake_case ) ) if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(snake_case ) - 1: chars.append(self.sentence_delimiter ) return chars a_ = tr.Compose( [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)] ) else: a_ = tr.Compose( [ tr.RemoveMultipleSpaces(), tr.Strip(), tr.ReduceToSingleSentence(SENTENCE_DELIMITER), tr.ReduceToListOfListOfChars(), ] ) a_ = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n' a_ = '\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the\nperformance of the ASR system with a CER of 0 being a perfect score.\n' a_ = '\nComputes CER score of transcribed segments against references.\nArgs:\n references: list of references for each speech input.\n predictions: list of transcribtions to score.\n concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n (float): the character error rate\n\nExamples:\n\n >>> predictions = ["this is the prediction", "there is an other sample"]\n >>> references = ["this is the reference", "there is another one"]\n >>> cer = datasets.load_metric("cer")\n >>> cer_score = cer.compute(predictions=predictions, references=references)\n >>> print(cer_score)\n 0.34146341463414637\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowercase ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/jitsi/jiwer/'] , reference_urls=[ 'https://en.wikipedia.org/wiki/Word_error_rate', 'https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates', ] , ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case : Tuple , snake_case : Tuple , snake_case : List[str]=False ) -> Any: """simple docstring""" if concatenate_texts: return jiwer.compute_measures( snake_case , snake_case , truth_transform=snake_case , hypothesis_transform=snake_case , )["wer"] UpperCamelCase_ : Dict = 0 UpperCamelCase_ : Union[str, Any] = 0 for prediction, reference in zip(snake_case , snake_case ): UpperCamelCase_ : str = jiwer.compute_measures( snake_case , snake_case , truth_transform=snake_case , hypothesis_transform=snake_case , ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
50
from manim import * class _lowercase ( snake_case_ ): def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Any: """simple docstring""" UpperCamelCase_ : str = Rectangle(height=0.5 , width=0.5 ) UpperCamelCase_ : Optional[Any] = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) UpperCamelCase_ : int = [mem.copy() for i in range(6 )] UpperCamelCase_ : List[Any] = [mem.copy() for i in range(6 )] UpperCamelCase_ : Dict = VGroup(*snake_case ).arrange(snake_case , buff=0 ) UpperCamelCase_ : List[str] = VGroup(*snake_case ).arrange(snake_case , buff=0 ) UpperCamelCase_ : int = VGroup(snake_case , snake_case ).arrange(snake_case , buff=0 ) UpperCamelCase_ : int = Text('CPU' , font_size=2_4 ) UpperCamelCase_ : List[str] = Group(snake_case , snake_case ).arrange(snake_case , buff=0.5 , aligned_edge=snake_case ) cpu.move_to([-2.5, -0.5, 0] ) self.add(snake_case ) UpperCamelCase_ : Union[str, Any] = [mem.copy() for i in range(1 )] UpperCamelCase_ : Dict = VGroup(*snake_case ).arrange(snake_case , buff=0 ) UpperCamelCase_ : Union[str, Any] = Text('GPU' , font_size=2_4 ) UpperCamelCase_ : Optional[Any] = Group(snake_case , snake_case ).arrange(snake_case , buff=0.5 , aligned_edge=snake_case ) gpu.align_to(snake_case , snake_case ) gpu.set_x(gpu.get_x() - 1 ) self.add(snake_case ) UpperCamelCase_ : int = [mem.copy() for i in range(6 )] UpperCamelCase_ : int = VGroup(*snake_case ).arrange(snake_case , buff=0 ) UpperCamelCase_ : Tuple = Text('Model' , font_size=2_4 ) UpperCamelCase_ : Dict = Group(snake_case , snake_case ).arrange(snake_case , buff=0.5 , aligned_edge=snake_case ) model.move_to([3, -1.0, 0] ) self.play( Create(snake_case , run_time=1 ) , Create(snake_case , run_time=1 ) , Create(snake_case , run_time=1 ) , ) UpperCamelCase_ : Union[str, Any] = MarkupText( f"First, an empty model skeleton is loaded\ninto <span fgcolor='{YELLOW}'>memory</span> without using much RAM." , font_size=2_4 , ) UpperCamelCase_ : Tuple = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) UpperCamelCase_ : Dict = MarkupText( f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model" , font_size=1_8 , ) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(snake_case , run_time=2.5 ) , Write(snake_case ) , Write(snake_case ) ) self.add(snake_case ) UpperCamelCase_ : Tuple = [] UpperCamelCase_ : List[str] = [] UpperCamelCase_ : Tuple = [] for i, rect in enumerate(snake_case ): UpperCamelCase_ : Any = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(snake_case , opacity=0.7 ) cpu_target.move_to(snake_case ) cpu_target.generate_target() UpperCamelCase_ : int = 0.46 / 4 UpperCamelCase_ : Tuple = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=snake_case ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=snake_case , buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=snake_case , buff=0.0 ) cpu_targs.append(snake_case ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(snake_case ) ) second_animations.append(MoveToTarget(snake_case , run_time=1.5 ) ) self.play(*snake_case ) self.play(*snake_case ) self.wait()
50
1
'''simple docstring''' from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. lowercase : Dict = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. lowercase : Optional[int] = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. lowercase : Optional[Any] = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> tuple[str, float]: _snake_case = len([g for position, g in enumerate(__A ) if g == main_target[position]] ) return (item, float(__A )) def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> tuple[str, str]: _snake_case = random.randint(0 , len(__A ) - 1 ) _snake_case = parent_a[:random_slice] + parent_a[random_slice:] _snake_case = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> str: _snake_case = list(__A ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: _snake_case = random.choice(__A ) return "".join(__A ) def SCREAMING_SNAKE_CASE__ ( __A , __A , __A , ) -> list[str]: _snake_case = [] # Generate more children proportionally to the fitness score. _snake_case = int(parent_a[1] * 100 ) + 1 _snake_case = 10 if child_n >= 10 else child_n for _ in range(__A ): _snake_case = population_score[random.randint(0 , __A )][0] _snake_case , _snake_case = crossover(parent_a[0] , __A ) # Append new string to the population list. pop.append(mutate(__A , __A ) ) pop.append(mutate(__A , __A ) ) return pop def SCREAMING_SNAKE_CASE__ ( __A , __A , __A = True ) -> tuple[int, int, str]: # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: _snake_case = F'{N_POPULATION} must be bigger than {N_SELECTED}' raise ValueError(__A ) # Verify that the target contains no genes besides the ones inside genes variable. _snake_case = sorted({c for c in target if c not in genes} ) if not_in_genes_list: _snake_case = F'{not_in_genes_list} is not in genes list, evolution cannot converge' raise ValueError(__A ) # Generate random starting population. _snake_case = [] for _ in range(__A ): population.append(''.join([random.choice(__A ) for i in range(len(__A ) )] ) ) # Just some logs to know what the algorithms is doing. _snake_case , _snake_case = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(__A ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. _snake_case = [evaluate(__A , __A ) for item in population] # Check if there is a matching evolution. _snake_case = sorted(__A , key=lambda __A : x[1] , reverse=__A ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'\nGeneration: {generation}' F'\nTotal Population:{total_population}' F'\nBest score: {population_score[0][1]}' F'\nBest string: {population_score[0][0]}' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. _snake_case = population[: int(N_POPULATION / 3 )] population.clear() population.extend(__A ) # Normalize population score to be between 0 and 1. _snake_case = [ (item, score / len(__A )) for item, score in population_score ] # This is selection for i in range(__A ): population.extend(select(population_score[int(__A )] , __A , __A ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(__A ) > N_POPULATION: break if __name__ == "__main__": lowercase : str = ( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) lowercase : str = list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) lowercase , lowercase , lowercase : Tuple = basic(target_str, genes_list) print( F'''\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}''' )
42
'''simple docstring''' from __future__ import annotations import string from itertools import cycle, product from pathlib import Path lowercase : str = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) lowercase : list[int] = [ord(letter) for letter in string.ascii_lowercase] lowercase : set[int] = {ord(char) for char in VALID_CHARS} lowercase : list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"] def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> str | None: _snake_case = "" _snake_case = 42 _snake_case = 42 _snake_case = 42 for keychar, cipherchar in zip(cycle(__A ) , __A ): _snake_case = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(__A ) return decoded def SCREAMING_SNAKE_CASE__ ( __A ) -> list[str]: _snake_case = [] for key in product(__A , repeat=3 ): _snake_case = try_key(__A , __A ) if encoded is not None: possibles.append(__A ) return possibles def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> list[str]: return [possible for possible in possibles if common_word in possible.lower()] def SCREAMING_SNAKE_CASE__ ( __A = "p059_cipher.txt" ) -> int: _snake_case = 42 _snake_case = 42 _snake_case = 42 _snake_case = 42 _snake_case = Path(__A ).parent.joinpath(__A ).read_text(encoding='utf-8' ) _snake_case = [int(__A ) for number in data.strip().split(',' )] _snake_case = filter_valid_chars(__A ) for common_word in COMMON_WORDS: _snake_case = filter_common_word(__A , __A ) if len(__A ) == 1: break _snake_case = possibles[0] return sum(ord(__A ) for char in decoded_text ) if __name__ == "__main__": print(F'''{solution() = }''')
42
1
'''simple docstring''' def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : int ): '''simple docstring''' if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError('iterations must be defined as integers' ) if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not number >= 1: raise ValueError( 'starting number must be\n and integer and be more than 0' ) if not iterations >= 1: raise ValueError('Iterations must be done more than 0 times to play FizzBuzz' ) _UpperCAmelCase : int ='' while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(__lowerCamelCase ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
242
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase =logging.get_logger(__name__) lowercase ={ 'vinvino02/glpn-kitti': 'https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json', # See all GLPN models at https://huggingface.co/models?filter=glpn } class __magic_name__ ( lowerCAmelCase ): UpperCAmelCase ="glpn" def __init__( self , snake_case=3 , snake_case=4 , snake_case=[2, 2, 2, 2] , snake_case=[8, 4, 2, 1] , snake_case=[3_2, 6_4, 1_6_0, 2_5_6] , snake_case=[7, 3, 3, 3] , snake_case=[4, 2, 2, 2] , snake_case=[1, 2, 5, 8] , snake_case=[4, 4, 4, 4] , snake_case="gelu" , snake_case=0.0 , snake_case=0.0 , snake_case=0.02 , snake_case=0.1 , snake_case=1E-6 , snake_case=6_4 , snake_case=1_0 , snake_case=-1 , **snake_case , ) -> Tuple: '''simple docstring''' super().__init__(**snake_case) _UpperCAmelCase : Any =num_channels _UpperCAmelCase : List[str] =num_encoder_blocks _UpperCAmelCase : Optional[Any] =depths _UpperCAmelCase : str =sr_ratios _UpperCAmelCase : Dict =hidden_sizes _UpperCAmelCase : List[str] =patch_sizes _UpperCAmelCase : Any =strides _UpperCAmelCase : List[str] =mlp_ratios _UpperCAmelCase : Dict =num_attention_heads _UpperCAmelCase : List[str] =hidden_act _UpperCAmelCase : int =hidden_dropout_prob _UpperCAmelCase : List[Any] =attention_probs_dropout_prob _UpperCAmelCase : Union[str, Any] =initializer_range _UpperCAmelCase : Tuple =drop_path_rate _UpperCAmelCase : str =layer_norm_eps _UpperCAmelCase : Optional[int] =decoder_hidden_size _UpperCAmelCase : List[str] =max_depth _UpperCAmelCase : Dict =head_in_index
242
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer _lowercase : Tuple = logging.get_logger(__name__) _lowercase : Tuple = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _lowercase : Dict = [ 'small', 'small-base', 'medium', 'medium-base', 'intermediate', 'intermediate-base', 'large', 'large-base', 'xlarge', 'xlarge-base', ] _lowercase : str = { 'vocab_file': { 'funnel-transformer/small': 'https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt', 'funnel-transformer/small-base': 'https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt', 'funnel-transformer/medium': 'https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt', 'funnel-transformer/medium-base': ( 'https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt' ), 'funnel-transformer/intermediate': ( 'https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt' ), 'funnel-transformer/intermediate-base': ( 'https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt' ), 'funnel-transformer/large': 'https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt', 'funnel-transformer/large-base': 'https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt', 'funnel-transformer/xlarge': 'https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt', 'funnel-transformer/xlarge-base': ( 'https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'funnel-transformer/small': 'https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json', 'funnel-transformer/small-base': ( 'https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json' ), 'funnel-transformer/medium': 'https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json', 'funnel-transformer/medium-base': ( 'https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json' ), 'funnel-transformer/intermediate': ( 'https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json' ), 'funnel-transformer/intermediate-base': ( 'https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json' ), 'funnel-transformer/large': 'https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json', 'funnel-transformer/large-base': ( 'https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json' ), 'funnel-transformer/xlarge': 'https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json', 'funnel-transformer/xlarge-base': ( 'https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json' ), }, } _lowercase : Optional[Any] = {f"""funnel-transformer/{name}""": 5_12 for name in _model_names} _lowercase : Optional[Any] = {f"""funnel-transformer/{name}""": {'do_lower_case': True} for name in _model_names} class _UpperCAmelCase ( _lowerCAmelCase ): a__ : Dict = VOCAB_FILES_NAMES a__ : int = PRETRAINED_VOCAB_FILES_MAP a__ : Optional[int] = PRETRAINED_INIT_CONFIGURATION a__ : List[str] = FunnelTokenizer a__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : int = 2 def __init__( self : List[str] , _lowercase : Any=None , _lowercase : Tuple=None , _lowercase : int=True , _lowercase : int="<unk>" , _lowercase : List[str]="<sep>" , _lowercase : Dict="<pad>" , _lowercase : Any="<cls>" , _lowercase : int="<mask>" , _lowercase : Optional[int]="<s>" , _lowercase : Optional[int]="</s>" , _lowercase : Tuple=True , _lowercase : List[Any]=True , _lowercase : Any=None , _lowercase : int="##" , **_lowercase : Optional[int] , ): 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 , bos_token=_lowercase , eos_token=_lowercase , clean_text=_lowercase , tokenize_chinese_chars=_lowercase , strip_accents=_lowercase , wordpieces_prefix=_lowercase , **_lowercase , ) __UpperCAmelCase = 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 = getattr(_lowercase , normalizer_state.pop('''type''' ) ) __UpperCAmelCase = do_lower_case __UpperCAmelCase = strip_accents __UpperCAmelCase = tokenize_chinese_chars __UpperCAmelCase = normalizer_class(**_lowercase ) __UpperCAmelCase = do_lower_case def a ( self : Union[str, Any] , _lowercase : str , _lowercase : Union[str, Any]=None ): __UpperCAmelCase = [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 a ( self : Optional[int] , _lowercase : List[int] , _lowercase : Optional[List[int]] = None ): __UpperCAmelCase = [self.sep_token_id] __UpperCAmelCase = [self.cls_token_id] if token_ids_a is None: return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a ( self : str , _lowercase : str , _lowercase : Optional[str] = None ): __UpperCAmelCase = self._tokenizer.model.save(_lowercase , name=_lowercase ) return tuple(_lowercase )
332
"""simple docstring""" import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def lowercase__ ( snake_case_ :Optional[int] ): return EnvironmentCommand() def lowercase__ ( snake_case_ :List[str] ): return EnvironmentCommand(args.accelerate_config_file ) class _UpperCAmelCase ( _lowerCAmelCase ): @staticmethod def a ( _lowercase : ArgumentParser ): __UpperCAmelCase = parser.add_parser('''env''' ) download_parser.set_defaults(func=_lowercase ) download_parser.add_argument( '''--accelerate-config_file''' , default=_lowercase , help='''The accelerate config file to use for the default values in the launching script.''' , ) download_parser.set_defaults(func=_lowercase ) def __init__( self : Optional[int] , _lowercase : str , *_lowercase : Tuple ): __UpperCAmelCase = accelerate_config_file def a ( self : Dict ): __UpperCAmelCase = '''not installed''' if is_safetensors_available(): import safetensors __UpperCAmelCase = safetensors.__version__ elif importlib.util.find_spec('''safetensors''' ) is not None: import safetensors __UpperCAmelCase = F'''{safetensors.__version__} but is ignored because of PyTorch version too old.''' __UpperCAmelCase = '''not installed''' __UpperCAmelCase = __UpperCAmelCase = '''not found''' if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file __UpperCAmelCase = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(_lowercase ): __UpperCAmelCase = load_config_from_file(self._accelerate_config_file ).to_dict() __UpperCAmelCase = ( '''\n'''.join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()] ) if isinstance(_lowercase , _lowercase ) else F'''\t{accelerate_config}''' ) __UpperCAmelCase = '''not installed''' __UpperCAmelCase = '''NA''' if is_torch_available(): import torch __UpperCAmelCase = torch.__version__ __UpperCAmelCase = torch.cuda.is_available() __UpperCAmelCase = '''not installed''' __UpperCAmelCase = '''NA''' if is_tf_available(): import tensorflow as tf __UpperCAmelCase = tf.__version__ try: # deprecated in v2.1 __UpperCAmelCase = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool __UpperCAmelCase = bool(tf.config.list_physical_devices('''GPU''' ) ) __UpperCAmelCase = '''not installed''' __UpperCAmelCase = '''not installed''' __UpperCAmelCase = '''not installed''' __UpperCAmelCase = '''NA''' if is_flax_available(): import flax import jax import jaxlib __UpperCAmelCase = flax.__version__ __UpperCAmelCase = jax.__version__ __UpperCAmelCase = jaxlib.__version__ __UpperCAmelCase = jax.lib.xla_bridge.get_backend().platform __UpperCAmelCase = { '''`transformers` version''': version, '''Platform''': platform.platform(), '''Python version''': platform.python_version(), '''Huggingface_hub version''': huggingface_hub.__version__, '''Safetensors version''': F'''{safetensors_version}''', '''Accelerate version''': F'''{accelerate_version}''', '''Accelerate config''': F'''{accelerate_config_str}''', '''PyTorch version (GPU?)''': F'''{pt_version} ({pt_cuda_available})''', '''Tensorflow version (GPU?)''': F'''{tf_version} ({tf_cuda_available})''', '''Flax version (CPU?/GPU?/TPU?)''': F'''{flax_version} ({jax_backend})''', '''Jax version''': F'''{jax_version}''', '''JaxLib version''': F'''{jaxlib_version}''', '''Using GPU in script?''': '''<fill in>''', '''Using distributed or parallel set-up in script?''': '''<fill in>''', } print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n''' ) print(self.format_dict(_lowercase ) ) return info @staticmethod def a ( _lowercase : str ): return "\n".join([F'''- {prop}: {val}''' for prop, val in d.items()] ) + "\n"
332
1
import inspect import unittest class _a ( unittest.TestCase): def UpperCAmelCase__( self : Union[str, Any] )-> Optional[int]: try: import diffusers # noqa: F401 except ImportError: assert False def UpperCAmelCase__( self : Any )-> Any: import diffusers from diffusers.dependency_versions_table import deps lowerCAmelCase__ : List[str] = inspect.getmembers(_SCREAMING_SNAKE_CASE , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": lowerCAmelCase__ : Any = '''k-diffusion''' elif backend == "invisible_watermark": lowerCAmelCase__ : Union[str, Any] = '''invisible-watermark''' assert backend in deps, F'{backend} is not in the deps table!'
211
from math import isqrt def lowerCamelCase_ ( _a ): """simple docstring""" lowerCAmelCase__ : Dict = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , _a , _a ): lowerCAmelCase__ : int = False return [i for i in range(2 , _a ) if is_prime[i]] def lowerCamelCase_ ( _a = 10**8 ): """simple docstring""" lowerCAmelCase__ : Any = calculate_prime_numbers(max_number // 2 ) lowerCAmelCase__ : Tuple = 0 lowerCAmelCase__ : List[Any] = 0 lowerCAmelCase__ : Optional[int] = len(_a ) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f'''{solution() = }''')
211
1
'''simple docstring''' from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. UpperCamelCase_ = 10 def _UpperCAmelCase ( _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : list[int] , _lowerCamelCase : int ) -> int: for i in range(_lowerCamelCase , _lowerCamelCase ): if array[i] == target: return i return -1 def _UpperCAmelCase ( _lowerCamelCase : list[int] , _lowerCamelCase : int ) -> int: _lowerCAmelCase : Optional[int] = 0 _lowerCAmelCase : Union[str, Any] = len(_lowerCamelCase ) while left <= right: if right - left < precision: return lin_search(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) _lowerCAmelCase : Union[str, Any] = (left + right) // 3 + 1 _lowerCAmelCase : Optional[int] = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: _lowerCAmelCase : Optional[Any] = one_third - 1 elif array[two_third] < target: _lowerCAmelCase : List[Any] = two_third + 1 else: _lowerCAmelCase : Optional[int] = one_third + 1 _lowerCAmelCase : List[str] = two_third - 1 else: return -1 def _UpperCAmelCase ( _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : list[int] , _lowerCamelCase : int ) -> int: if left < right: if right - left < precision: return lin_search(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) _lowerCAmelCase : List[Any] = (left + right) // 3 + 1 _lowerCAmelCase : List[str] = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(_lowerCamelCase , one_third - 1 , _lowerCamelCase , _lowerCamelCase ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , _lowerCamelCase , _lowerCamelCase ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase_ = input("""Enter numbers separated by comma:\n""").strip() UpperCamelCase_ = [int(item.strip()) for item in user_input.split(""",""")] assert collection == sorted(collection), F"List must be ordered.\n{collection}." UpperCamelCase_ = int(input("""Enter the number to be found in the list:\n""").strip()) UpperCamelCase_ = ite_ternary_search(collection, target) UpperCamelCase_ = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(F'Iterative search: {target} found at positions: {resulta}') print(F'Recursive search: {target} found at positions: {resulta}') else: print("""Not found""")
309
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = {"""vocab_file""": """vocab.txt"""} UpperCamelCase_ = { """vocab_file""": { """YituTech/conv-bert-base""": """https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt""", """YituTech/conv-bert-medium-small""": ( """https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt""" ), """YituTech/conv-bert-small""": """https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt""", } } UpperCamelCase_ = { """YituTech/conv-bert-base""": 5_12, """YituTech/conv-bert-medium-small""": 5_12, """YituTech/conv-bert-small""": 5_12, } UpperCamelCase_ = { """YituTech/conv-bert-base""": {"""do_lower_case""": True}, """YituTech/conv-bert-medium-small""": {"""do_lower_case""": True}, """YituTech/conv-bert-small""": {"""do_lower_case""": True}, } class a_ (_a ): __lowerCAmelCase : Any = VOCAB_FILES_NAMES __lowerCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase : Dict = PRETRAINED_INIT_CONFIGURATION __lowerCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase : Optional[int] = ConvBertTokenizer def __init__( self , snake_case_=None , snake_case_=None , snake_case_=True , snake_case_="[UNK]" , snake_case_="[SEP]" , snake_case_="[PAD]" , snake_case_="[CLS]" , snake_case_="[MASK]" , snake_case_=True , snake_case_=None , **snake_case_ , ): super().__init__( snake_case_ , tokenizer_file=snake_case_ , do_lower_case=snake_case_ , unk_token=snake_case_ , sep_token=snake_case_ , pad_token=snake_case_ , cls_token=snake_case_ , mask_token=snake_case_ , tokenize_chinese_chars=snake_case_ , strip_accents=snake_case_ , **snake_case_ , ) _lowerCAmelCase : List[str] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , snake_case_ ) != do_lower_case or normalizer_state.get("""strip_accents""" , snake_case_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , snake_case_ ) != tokenize_chinese_chars ): _lowerCAmelCase : Dict = getattr(snake_case_ , normalizer_state.pop("""type""" ) ) _lowerCAmelCase : List[str] = do_lower_case _lowerCAmelCase : str = strip_accents _lowerCAmelCase : List[Any] = tokenize_chinese_chars _lowerCAmelCase : List[Any] = normalizer_class(**snake_case_ ) _lowerCAmelCase : str = do_lower_case def __UpperCamelCase ( self , snake_case_ , snake_case_=None ): _lowerCAmelCase : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __UpperCamelCase ( self , snake_case_ , snake_case_ = None ): _lowerCAmelCase : Optional[Any] = [self.sep_token_id] _lowerCAmelCase : 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 , snake_case_ , snake_case_ = None ): _lowerCAmelCase : Any = self._tokenizer.model.save(snake_case_ , name=snake_case_ ) return tuple(snake_case_ )
309
1
"""simple docstring""" import math import qiskit def __A ( a_ :int = 1 , a_ :int = 1 , a_ :int = 1) -> qiskit.result.counts.Counts: if ( isinstance(a_ , a_) or isinstance(a_ , a_) or isinstance(a_ , a_) ): raise TypeError('''inputs must be integers.''') if (input_a < 0) or (input_a < 0) or (carry_in < 0): raise ValueError('''inputs must be positive.''') if ( (math.floor(a_) != input_a) or (math.floor(a_) != input_a) or (math.floor(a_) != carry_in) ): raise ValueError('''inputs must be exact integers.''') if (input_a > 2) or (input_a > 2) or (carry_in > 2): raise ValueError('''inputs must be less or equal to 2.''') # build registers __a : str = qiskit.QuantumRegister(4 , '''qr''') __a : List[Any] = qiskit.ClassicalRegister(2 , '''cr''') # list the entries __a : Any = [input_a, input_a, carry_in] __a : List[Any] = qiskit.QuantumCircuit(a_ , a_) for i in range(0 , 3): if entry[i] == 2: quantum_circuit.h(a_) # for hadamard entries elif entry[i] == 1: quantum_circuit.x(a_) # for 1 entries elif entry[i] == 0: quantum_circuit.i(a_) # for 0 entries # build the circuit quantum_circuit.ccx(0 , 1 , 3) # ccx = toffoli gate quantum_circuit.cx(0 , 1) quantum_circuit.ccx(1 , 2 , 3) quantum_circuit.cx(1 , 2) quantum_circuit.cx(0 , 1) quantum_circuit.measure([2, 3] , a_) # measure the last two qbits __a : int = qiskit.Aer.get_backend('''aer_simulator''') __a : Union[str, Any] = qiskit.execute(a_ , a_ , shots=10_00) return job.result().get_counts(a_) if __name__ == "__main__": print(F'Total sum count for state is: {quantum_full_adder(1, 1, 1)}')
188
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A = logging.get_logger(__name__) A = {'''vocab_file''': '''spiece.model'''} A = { '''vocab_file''': { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''', '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/spiece.model''', '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model''', '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model''', '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/spiece.model''', '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/spiece.model''', '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model''', '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model''', } } A = { '''albert-base-v1''': 512, '''albert-large-v1''': 512, '''albert-xlarge-v1''': 512, '''albert-xxlarge-v1''': 512, '''albert-base-v2''': 512, '''albert-large-v2''': 512, '''albert-xlarge-v2''': 512, '''albert-xxlarge-v2''': 512, } A = '''▁''' class __lowercase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _UpperCAmelCase , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=False , _UpperCAmelCase="[CLS]" , _UpperCAmelCase="[SEP]" , _UpperCAmelCase="<unk>" , _UpperCAmelCase="[SEP]" , _UpperCAmelCase="<pad>" , _UpperCAmelCase="[CLS]" , _UpperCAmelCase="[MASK]" , _UpperCAmelCase = None , **_UpperCAmelCase , ): # 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. __a : int = ( AddedToken(_UpperCAmelCase , lstrip=_UpperCAmelCase , rstrip=_UpperCAmelCase , normalized=_UpperCAmelCase ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ) else mask_token ) __a : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_UpperCAmelCase , remove_space=_UpperCAmelCase , keep_accents=_UpperCAmelCase , bos_token=_UpperCAmelCase , eos_token=_UpperCAmelCase , unk_token=_UpperCAmelCase , sep_token=_UpperCAmelCase , pad_token=_UpperCAmelCase , cls_token=_UpperCAmelCase , mask_token=_UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **_UpperCAmelCase , ) __a : Tuple = do_lower_case __a : Optional[Any] = remove_space __a : Optional[Any] = keep_accents __a : Union[str, Any] = vocab_file __a : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_UpperCAmelCase ) @property def _lowerCamelCase ( self ): return len(self.sp_model ) def _lowerCamelCase ( self ): __a : Any = {self.convert_ids_to_tokens(_UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): __a : str = self.__dict__.copy() __a : Tuple = None return state def __setstate__( self , _UpperCAmelCase ): __a : Any = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __a : Optional[Any] = {} __a : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowerCamelCase ( self , _UpperCAmelCase ): if self.remove_space: __a : Any = ''' '''.join(inputs.strip().split() ) else: __a : Tuple = inputs __a : Union[str, Any] = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: __a : List[str] = unicodedata.normalize('''NFKD''' , _UpperCAmelCase ) __a : Optional[int] = ''''''.join([c for c in outputs if not unicodedata.combining(_UpperCAmelCase )] ) if self.do_lower_case: __a : Optional[Any] = outputs.lower() return outputs def _lowerCamelCase ( self , _UpperCAmelCase ): __a : int = self.preprocess_text(_UpperCAmelCase ) __a : Tuple = self.sp_model.encode(_UpperCAmelCase , out_type=_UpperCAmelCase ) __a : int = [] for piece in pieces: if len(_UpperCAmelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): __a : List[str] = self.sp_model.EncodeAsPieces(piece[:-1].replace(_UpperCAmelCase , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: __a : Tuple = cur_pieces[1:] else: __a : Optional[Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(_UpperCAmelCase ) else: new_pieces.append(_UpperCAmelCase ) return new_pieces def _lowerCamelCase ( self , _UpperCAmelCase ): return self.sp_model.PieceToId(_UpperCAmelCase ) def _lowerCamelCase ( self , _UpperCAmelCase ): return self.sp_model.IdToPiece(_UpperCAmelCase ) def _lowerCamelCase ( self , _UpperCAmelCase ): __a : List[str] = [] __a : str = '''''' __a : Any = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_UpperCAmelCase ) + token __a : Tuple = True __a : Tuple = [] else: current_sub_tokens.append(_UpperCAmelCase ) __a : Optional[int] = False out_string += self.sp_model.decode(_UpperCAmelCase ) return out_string.strip() def _lowerCamelCase ( self , _UpperCAmelCase , _UpperCAmelCase = None ): __a : int = [self.sep_token_id] __a : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _lowerCamelCase ( self , _UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCAmelCase , token_ids_a=_UpperCAmelCase , already_has_special_tokens=_UpperCAmelCase ) if token_ids_a is not None: return [1] + ([0] * len(_UpperCAmelCase )) + [1] + ([0] * len(_UpperCAmelCase )) + [1] return [1] + ([0] * len(_UpperCAmelCase )) + [1] def _lowerCamelCase ( self , _UpperCAmelCase , _UpperCAmelCase = None ): __a : Union[str, Any] = [self.sep_token_id] __a : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowerCamelCase ( self , _UpperCAmelCase , _UpperCAmelCase = None ): if not os.path.isdir(_UpperCAmelCase ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __a : List[str] = os.path.join( _UpperCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(_UpperCAmelCase , '''wb''' ) as fi: __a : Any = self.sp_model.serialized_model_proto() fi.write(_UpperCAmelCase ) return (out_vocab_file,)
188
1
'''simple docstring''' import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () _UpperCamelCase = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). _UpperCamelCase = [0, 25, 50] _UpperCamelCase = [25, 50, 75] _UpperCamelCase = fuzz.membership.trimf(X, abca) _UpperCamelCase = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. _UpperCamelCase = np.ones(75) _UpperCamelCase = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) _UpperCamelCase = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) _UpperCamelCase = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) _UpperCamelCase = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) _UpperCamelCase = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] _UpperCamelCase = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) _UpperCamelCase = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] _UpperCamelCase = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] _UpperCamelCase = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('Young') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('Middle aged') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('union') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('intersection') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('complement_a') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('difference a/b') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('alg_sum') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('alg_product') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('bdd_sum') plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title('bdd_difference') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
208
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL A__ : List[str] =logging.get_logger(__name__) def UpperCamelCase__ ( lowerCAmelCase ): """simple docstring""" if isinstance(lowerCAmelCase , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(lowerCAmelCase , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(lowerCAmelCase ): return [[videos]] raise ValueError(f"Could not make batched video from {videos}" ) class UpperCAmelCase ( snake_case_ ): _lowercase: Any = ['''pixel_values'''] def __init__( self : Tuple , __snake_case : bool = True , __snake_case : Dict[str, int] = None , __snake_case : PILImageResampling = PILImageResampling.BILINEAR , __snake_case : bool = True , __snake_case : Dict[str, int] = None , __snake_case : bool = True , __snake_case : Union[int, float] = 1 / 2_55 , __snake_case : bool = True , __snake_case : bool = True , __snake_case : Optional[Union[float, List[float]]] = None , __snake_case : Optional[Union[float, List[float]]] = None , **__snake_case : str , ) -> None: super().__init__(**__snake_case ) _lowerCAmelCase = size if size is not None else {"""shortest_edge""": 2_56} _lowerCAmelCase = get_size_dict(__snake_case , default_to_square=__snake_case ) _lowerCAmelCase = crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24} _lowerCAmelCase = get_size_dict(__snake_case , param_name="""crop_size""" ) _lowerCAmelCase = do_resize _lowerCAmelCase = size _lowerCAmelCase = do_center_crop _lowerCAmelCase = crop_size _lowerCAmelCase = resample _lowerCAmelCase = do_rescale _lowerCAmelCase = rescale_factor _lowerCAmelCase = offset _lowerCAmelCase = do_normalize _lowerCAmelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _lowerCAmelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD def lowercase__ ( self : int , __snake_case : np.ndarray , __snake_case : Dict[str, int] , __snake_case : PILImageResampling = PILImageResampling.BILINEAR , __snake_case : Optional[Union[str, ChannelDimension]] = None , **__snake_case : Optional[Any] , ) -> np.ndarray: _lowerCAmelCase = get_size_dict(__snake_case , default_to_square=__snake_case ) if "shortest_edge" in size: _lowerCAmelCase = get_resize_output_image_size(__snake_case , size["""shortest_edge"""] , default_to_square=__snake_case ) elif "height" in size and "width" in size: _lowerCAmelCase = (size["""height"""], size["""width"""]) else: raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(__snake_case , size=__snake_case , resample=__snake_case , data_format=__snake_case , **__snake_case ) def lowercase__ ( self : Union[str, Any] , __snake_case : np.ndarray , __snake_case : Dict[str, int] , __snake_case : Optional[Union[str, ChannelDimension]] = None , **__snake_case : List[Any] , ) -> np.ndarray: _lowerCAmelCase = get_size_dict(__snake_case ) if "height" not in size or "width" not in size: raise ValueError(f"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(__snake_case , size=(size["""height"""], size["""width"""]) , data_format=__snake_case , **__snake_case ) def lowercase__ ( self : Union[str, Any] , __snake_case : np.ndarray , __snake_case : Union[int, float] , __snake_case : bool = True , __snake_case : Optional[Union[str, ChannelDimension]] = None , **__snake_case : Optional[Any] , ) -> Dict: _lowerCAmelCase = image.astype(np.floataa ) if offset: _lowerCAmelCase = image - (scale / 2) return rescale(__snake_case , scale=__snake_case , data_format=__snake_case , **__snake_case ) def lowercase__ ( self : Optional[int] , __snake_case : np.ndarray , __snake_case : Union[float, List[float]] , __snake_case : Union[float, List[float]] , __snake_case : Optional[Union[str, ChannelDimension]] = None , **__snake_case : Tuple , ) -> np.ndarray: return normalize(__snake_case , mean=__snake_case , std=__snake_case , data_format=__snake_case , **__snake_case ) def lowercase__ ( self : List[Any] , __snake_case : ImageInput , __snake_case : bool = None , __snake_case : Dict[str, int] = None , __snake_case : PILImageResampling = None , __snake_case : bool = None , __snake_case : Dict[str, int] = None , __snake_case : bool = None , __snake_case : float = None , __snake_case : bool = None , __snake_case : bool = None , __snake_case : Optional[Union[float, List[float]]] = None , __snake_case : Optional[Union[float, List[float]]] = None , __snake_case : Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.ndarray: if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) if offset and not do_rescale: raise ValueError("""For offset, do_rescale must also be set to True.""" ) # All transformations expect numpy arrays. _lowerCAmelCase = to_numpy_array(__snake_case ) if do_resize: _lowerCAmelCase = self.resize(image=__snake_case , size=__snake_case , resample=__snake_case ) if do_center_crop: _lowerCAmelCase = self.center_crop(__snake_case , size=__snake_case ) if do_rescale: _lowerCAmelCase = self.rescale(image=__snake_case , scale=__snake_case , offset=__snake_case ) if do_normalize: _lowerCAmelCase = self.normalize(image=__snake_case , mean=__snake_case , std=__snake_case ) _lowerCAmelCase = to_channel_dimension_format(__snake_case , __snake_case ) return image def lowercase__ ( self : List[Any] , __snake_case : ImageInput , __snake_case : bool = None , __snake_case : Dict[str, int] = None , __snake_case : PILImageResampling = None , __snake_case : bool = None , __snake_case : Dict[str, int] = None , __snake_case : bool = None , __snake_case : float = None , __snake_case : bool = None , __snake_case : bool = None , __snake_case : Optional[Union[float, List[float]]] = None , __snake_case : Optional[Union[float, List[float]]] = None , __snake_case : Optional[Union[str, TensorType]] = None , __snake_case : ChannelDimension = ChannelDimension.FIRST , **__snake_case : List[str] , ) -> PIL.Image.Image: _lowerCAmelCase = do_resize if do_resize is not None else self.do_resize _lowerCAmelCase = resample if resample is not None else self.resample _lowerCAmelCase = do_center_crop if do_center_crop is not None else self.do_center_crop _lowerCAmelCase = do_rescale if do_rescale is not None else self.do_rescale _lowerCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor _lowerCAmelCase = offset if offset is not None else self.offset _lowerCAmelCase = do_normalize if do_normalize is not None else self.do_normalize _lowerCAmelCase = image_mean if image_mean is not None else self.image_mean _lowerCAmelCase = image_std if image_std is not None else self.image_std _lowerCAmelCase = size if size is not None else self.size _lowerCAmelCase = get_size_dict(__snake_case , default_to_square=__snake_case ) _lowerCAmelCase = crop_size if crop_size is not None else self.crop_size _lowerCAmelCase = get_size_dict(__snake_case , param_name="""crop_size""" ) if not valid_images(__snake_case ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) _lowerCAmelCase = make_batched(__snake_case ) _lowerCAmelCase = [ [ self._preprocess_image( image=__snake_case , do_resize=__snake_case , size=__snake_case , resample=__snake_case , do_center_crop=__snake_case , crop_size=__snake_case , do_rescale=__snake_case , rescale_factor=__snake_case , offset=__snake_case , do_normalize=__snake_case , image_mean=__snake_case , image_std=__snake_case , data_format=__snake_case , ) for img in video ] for video in videos ] _lowerCAmelCase = {"""pixel_values""": videos} return BatchFeature(data=__snake_case , tensor_type=__snake_case )
70
0
# 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 typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class A ( _UpperCAmelCase ): """simple docstring""" lowerCamelCase = 'dandelin/vilt-b32-finetuned-vqa' lowerCamelCase = ( 'This is a tool that answers a question about an image. It takes an input named `image` which should be the ' 'image containing the information, as well as a `question` which should be the question in English. It ' 'returns a text that is the answer to the question.' ) lowerCamelCase = 'image_qa' lowerCamelCase = AutoProcessor lowerCamelCase = AutoModelForVisualQuestionAnswering lowerCamelCase = ['image', 'text'] lowerCamelCase = ['text'] def __init__( self : Dict,*lowercase_ : Optional[Any],**lowercase_ : int )-> Any: '''simple docstring''' requires_backends(self,['vision'] ) super().__init__(*lowercase_,**lowercase_ ) def snake_case__ ( self : Dict,lowercase_ : "Image",lowercase_ : str )-> int: '''simple docstring''' return self.pre_processor(lowercase_,lowercase_,return_tensors='pt' ) def snake_case__ ( self : Optional[int],lowercase_ : int )-> Tuple: '''simple docstring''' with torch.no_grad(): return self.model(**lowercase_ ).logits def snake_case__ ( self : List[str],lowercase_ : Optional[int] )-> Optional[int]: '''simple docstring''' A__ = outputs.argmax(-1 ).item() return self.model.config.idalabel[idx]
357
import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/config.json", # See all BART models at https://huggingface.co/models?filter=bart } class A ( _UpperCAmelCase ): """simple docstring""" lowerCamelCase = 'bart' lowerCamelCase = ['past_key_values'] lowerCamelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : Tuple,lowercase_ : Optional[int]=5_0_2_6_5,lowercase_ : List[str]=1_0_2_4,lowercase_ : Any=1_2,lowercase_ : Optional[Any]=4_0_9_6,lowercase_ : str=1_6,lowercase_ : int=1_2,lowercase_ : Optional[Any]=4_0_9_6,lowercase_ : Any=1_6,lowercase_ : Any=0.0,lowercase_ : str=0.0,lowercase_ : Optional[Any]="gelu",lowercase_ : List[str]=1_0_2_4,lowercase_ : List[Any]=0.1,lowercase_ : Union[str, Any]=0.0,lowercase_ : Optional[int]=0.0,lowercase_ : List[Any]=0.02,lowercase_ : int=0.0,lowercase_ : Optional[Any]=False,lowercase_ : List[Any]=True,lowercase_ : Union[str, Any]=3,lowercase_ : int=1,lowercase_ : int=0,lowercase_ : List[str]=2,lowercase_ : Optional[int]=True,lowercase_ : Tuple=2,lowercase_ : List[str]=2,**lowercase_ : Dict,)-> List[Any]: '''simple docstring''' 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__ = classifier_dropout A__ = use_cache A__ = encoder_layers A__ = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( num_labels=lowercase_,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_,) # ensure backward compatibility for BART CNN models if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated',lowercase_ ): A__ = 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.' ) class A ( _UpperCAmelCase ): """simple docstring""" @property def snake_case__ ( self : Dict )-> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: A__ = OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: A__ = {0: 'batch'} A__ = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: A__ = {0: 'batch', 1: 'decoder_sequence'} A__ = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(lowercase_,direction='inputs' ) elif self.task == "causal-lm": # TODO: figure this case out. A__ = OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: A__ , A__ = self.num_layers for i in range(lowercase_ ): A__ = {0: 'batch', 2: 'past_sequence + sequence'} A__ = {0: 'batch', 2: 'past_sequence + sequence'} else: A__ = OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}), ('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}), ] ) return common_inputs @property def snake_case__ ( self : Optional[Any] )-> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: A__ = super().outputs else: A__ = super(lowercase_,self ).outputs if self.use_past: A__ , A__ = self.num_layers for i in range(lowercase_ ): A__ = {0: 'batch', 2: 'past_sequence + sequence'} A__ = {0: 'batch', 2: 'past_sequence + sequence'} return common_outputs def snake_case__ ( self : Tuple,lowercase_ : PreTrainedTokenizer,lowercase_ : int = -1,lowercase_ : int = -1,lowercase_ : bool = False,lowercase_ : Optional[TensorType] = None,)-> Mapping[str, Any]: '''simple docstring''' A__ = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowercase_,lowercase_,lowercase_,lowercase_,lowercase_ ) # Generate decoder inputs A__ = seq_length if not self.use_past else 1 A__ = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowercase_,lowercase_,lowercase_,lowercase_,lowercase_ ) A__ = {F'decoder_{name}': tensor for name, tensor in decoder_inputs.items()} A__ = dict(**lowercase_,**lowercase_ ) if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch A__ , A__ = common_inputs['input_ids'].shape A__ = common_inputs['decoder_input_ids'].shape[1] A__ , A__ = self.num_attention_heads A__ = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) A__ = decoder_seq_length + 3 A__ = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) A__ = torch.cat( [common_inputs['decoder_attention_mask'], torch.ones(lowercase_,lowercase_ )],dim=1 ) A__ = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered A__ , A__ = self.num_layers A__ = min(lowercase_,lowercase_ ) A__ = max(lowercase_,lowercase_ ) - min_num_layers A__ = 'encoder' if num_encoder_layers > num_decoder_layers else 'decoder' for _ in range(lowercase_ ): common_inputs["past_key_values"].append( ( torch.zeros(lowercase_ ), torch.zeros(lowercase_ ), torch.zeros(lowercase_ ), torch.zeros(lowercase_ ), ) ) # TODO: test this. A__ = encoder_shape if remaining_side_name == 'encoder' else decoder_shape for _ in range(lowercase_,lowercase_ ): common_inputs["past_key_values"].append((torch.zeros(lowercase_ ), torch.zeros(lowercase_ )) ) return common_inputs def snake_case__ ( self : List[str],lowercase_ : PreTrainedTokenizer,lowercase_ : int = -1,lowercase_ : int = -1,lowercase_ : bool = False,lowercase_ : Optional[TensorType] = None,)-> Mapping[str, Any]: '''simple docstring''' A__ = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowercase_,lowercase_,lowercase_,lowercase_,lowercase_ ) if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch A__ , A__ = common_inputs['input_ids'].shape # Not using the same length for past_key_values A__ = seqlen + 2 A__ , A__ = self.num_layers A__ , A__ = self.num_attention_heads A__ = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) A__ = common_inputs['attention_mask'].dtype A__ = torch.cat( [common_inputs['attention_mask'], torch.ones(lowercase_,lowercase_,dtype=lowercase_ )],dim=1 ) A__ = [ (torch.zeros(lowercase_ ), torch.zeros(lowercase_ )) for _ in range(lowercase_ ) ] return common_inputs def snake_case__ ( self : Union[str, Any],lowercase_ : PreTrainedTokenizer,lowercase_ : int = -1,lowercase_ : int = -1,lowercase_ : bool = False,lowercase_ : Optional[TensorType] = None,)-> Mapping[str, Any]: '''simple docstring''' A__ = compute_effective_axis_dimension( lowercase_,fixed_dimension=OnnxConfig.default_fixed_batch,num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX A__ = tokenizer.num_special_tokens_to_add(lowercase_ ) A__ = compute_effective_axis_dimension( lowercase_,fixed_dimension=OnnxConfig.default_fixed_sequence,num_token_to_add=lowercase_ ) # Generate dummy inputs according to compute batch and sequence A__ = [' '.join([tokenizer.unk_token] ) * seq_length] * batch_size A__ = dict(tokenizer(lowercase_,return_tensors=lowercase_ ) ) return common_inputs def snake_case__ ( self : Union[str, Any],lowercase_ : PreTrainedTokenizer,lowercase_ : int = -1,lowercase_ : int = -1,lowercase_ : bool = False,lowercase_ : Optional[TensorType] = None,)-> Mapping[str, Any]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: A__ = self._generate_dummy_inputs_for_default_and_seqaseq_lm( lowercase_,batch_size=lowercase_,seq_length=lowercase_,is_pair=lowercase_,framework=lowercase_ ) elif self.task == "causal-lm": A__ = self._generate_dummy_inputs_for_causal_lm( lowercase_,batch_size=lowercase_,seq_length=lowercase_,is_pair=lowercase_,framework=lowercase_ ) else: A__ = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowercase_,batch_size=lowercase_,seq_length=lowercase_,is_pair=lowercase_,framework=lowercase_ ) return common_inputs def snake_case__ ( self : int,lowercase_ : Tuple,lowercase_ : int,lowercase_ : int,lowercase_ : str )-> str: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: A__ = super()._flatten_past_key_values_(lowercase_,lowercase_,lowercase_,lowercase_ ) else: A__ = super(lowercase_,self )._flatten_past_key_values_( lowercase_,lowercase_,lowercase_,lowercase_ )
282
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available __lowerCamelCase = {"""tokenization_herbert""": ["""HerbertTokenizer"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = ["""HerbertTokenizerFast"""] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys __lowerCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
59
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Dict ) -> List[str]: if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class A__ ( nn.Module ): def __init__( self : Any , _UpperCAmelCase : nn.Module , _UpperCAmelCase : int ) -> Optional[int]: """simple docstring""" super().__init__() __lowercase = module __lowercase = nn.Sequential( nn.Linear(module.in_features , _UpperCAmelCase , bias=_UpperCAmelCase ) , nn.Linear(_UpperCAmelCase , module.out_features , bias=_UpperCAmelCase ) , ) __lowercase = (2.0 / (5 * min(module.in_features , module.out_features ))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=_UpperCAmelCase ) nn.init.zeros_(self.adapter[1].weight ) self.adapter.to(module.weight.device ) def a__ ( self : str , _UpperCAmelCase : List[str] , *_UpperCAmelCase : List[Any] , **_UpperCAmelCase : List[str] ) -> Optional[Any]: """simple docstring""" return self.module(_UpperCAmelCase , *_UpperCAmelCase , **_UpperCAmelCase ) + self.adapter(_UpperCAmelCase ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class A__ ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module lowerCAmelCase__ : int = "bigscience/bloom-1b7" # Constant values lowerCAmelCase__ : Any = 2.109659552692574 lowerCAmelCase__ : str = "Hello my name is" lowerCAmelCase__ : Any = set() EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I" ) EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n" ) EXPECTED_OUTPUTS.add("Hello my name is John Doe, I am a student at the University" ) lowerCAmelCase__ : List[Any] = 10 def a__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __lowercase = AutoTokenizer.from_pretrained(self.model_name ) class A__ ( lowerCAmelCase__ ): def a__ ( self : Any ) -> Union[str, Any]: """simple docstring""" super().setUp() # Models and tokenizer __lowercase = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto' ) __lowercase = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) def a__ ( self : Any ) -> Optional[Any]: """simple docstring""" del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def a__ ( self : str ) -> int: """simple docstring""" __lowercase = self.model_abit.config self.assertTrue(hasattr(_UpperCAmelCase , 'quantization_config' ) ) __lowercase = config.to_dict() __lowercase = config.to_diff_dict() __lowercase = config.to_json_string() def a__ ( self : Dict ) -> Tuple: """simple docstring""" from bitsandbytes.nn import Paramsabit __lowercase = self.model_fpaa.get_memory_footprint() __lowercase = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE ) __lowercase = get_some_linear_layer(self.model_abit ) self.assertTrue(linear.weight.__class__ == Paramsabit ) def a__ ( self : Tuple ) -> str: """simple docstring""" from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(_UpperCAmelCase , torch.nn.Linear ): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta ) def a__ ( self : List[str] ) -> str: """simple docstring""" __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ) __lowercase = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=_UpperCAmelCase ) , self.EXPECTED_OUTPUTS ) def a__ ( self : Union[str, Any] ) -> str: """simple docstring""" __lowercase = BitsAndBytesConfig() __lowercase = True __lowercase = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=_UpperCAmelCase , device_map='auto' ) __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ) __lowercase = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=_UpperCAmelCase ) , self.EXPECTED_OUTPUTS ) def a__ ( self : str ) -> List[str]: """simple docstring""" with self.assertRaises(_UpperCAmelCase ), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(_UpperCAmelCase ) def a__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __lowercase = BitsAndBytesConfig() with self.assertRaises(_UpperCAmelCase ): __lowercase = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=_UpperCAmelCase , load_in_abit=_UpperCAmelCase , device_map='auto' , bnb_abit_quant_type='nf4' , ) def a__ ( self : Optional[Any] ) -> Tuple: """simple docstring""" with self.assertRaises(_UpperCAmelCase ): # Tries with `str` self.model_abit.to('cpu' ) with self.assertRaises(_UpperCAmelCase ): # Tries with a `dtype`` self.model_abit.to(torch.floataa ) with self.assertRaises(_UpperCAmelCase ): # Tries with a `device` self.model_abit.to(torch.device('cuda:0' ) ) with self.assertRaises(_UpperCAmelCase ): # Tries with a `device` self.model_abit.float() with self.assertRaises(_UpperCAmelCase ): # Tries with a `device` self.model_abit.half() # Test if we did not break anything __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ) __lowercase = self.model_fpaa.to(torch.floataa ) __lowercase = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) # Check this does not throw an error __lowercase = self.model_fpaa.to('cpu' ) # Check this does not throw an error __lowercase = self.model_fpaa.half() # Check this does not throw an error __lowercase = self.model_fpaa.float() def a__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __lowercase = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=_UpperCAmelCase , device_map='auto' ) self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class A__ ( unittest.TestCase ): @classmethod def a__ ( cls : int ) -> Tuple: """simple docstring""" __lowercase = 't5-small' __lowercase = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense __lowercase = AutoTokenizer.from_pretrained(cls.model_name ) __lowercase = 'Translate in German: Hello, my dog is cute' def a__ ( self : List[Any] ) -> Dict: """simple docstring""" gc.collect() torch.cuda.empty_cache() def a__ ( self : int ) -> int: """simple docstring""" from transformers import TaForConditionalGeneration __lowercase = TaForConditionalGeneration._keep_in_fpaa_modules __lowercase = None # test with `t5-small` __lowercase = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __lowercase = model.generate(**_UpperCAmelCase ) # test with `flan-t5-small` __lowercase = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __lowercase = model.generate(**_UpperCAmelCase ) __lowercase = modules def a__ ( self : str ) -> Optional[Any]: """simple docstring""" import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` __lowercase = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit ) ) __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __lowercase = model.generate(**_UpperCAmelCase ) # test with `flan-t5-small` __lowercase = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) __lowercase = model.generate(**_UpperCAmelCase ) class A__ ( lowerCAmelCase__ ): def a__ ( self : Union[str, Any] ) -> Any: """simple docstring""" super().setUp() # model_name __lowercase = 'bigscience/bloom-560m' __lowercase = 't5-small' # Different types of model __lowercase = AutoModel.from_pretrained(self.model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) # Sequence classification model __lowercase = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) # CausalLM model __lowercase = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) # Seq2seq model __lowercase = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=_UpperCAmelCase , device_map='auto' ) def a__ ( self : int ) -> List[str]: """simple docstring""" del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def a__ ( self : Tuple ) -> str: """simple docstring""" from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit ) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter ) class A__ ( lowerCAmelCase__ ): def a__ ( self : str ) -> str: """simple docstring""" super().setUp() def a__ ( self : Dict ) -> Any: """simple docstring""" del self.pipe gc.collect() torch.cuda.empty_cache() def a__ ( self : Tuple ) -> int: """simple docstring""" __lowercase = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass __lowercase = self.pipe(self.input_text ) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS ) @require_torch_multi_gpu class A__ ( lowerCAmelCase__ ): def a__ ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" super().setUp() def a__ ( self : List[Any] ) -> int: """simple docstring""" __lowercase = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=_UpperCAmelCase , device_map='balanced' ) # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values() ) , {0, 1} ) # Check that inference pass works on the model __lowercase = self.tokenizer(self.input_text , return_tensors='pt' ) # Second real batch __lowercase = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=_UpperCAmelCase ) , self.EXPECTED_OUTPUTS ) class A__ ( lowerCAmelCase__ ): def a__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __lowercase = 'facebook/opt-350m' super().setUp() def a__ ( self : Dict ) -> List[str]: """simple docstring""" if version.parse(importlib.metadata.version('bitsandbytes' ) ) < version.parse('0.37.0' ): return # Step 1: freeze all parameters __lowercase = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=_UpperCAmelCase ) self.assertEqual(set(model.hf_device_map.values() ) , {torch.cuda.current_device()} ) for param in model.parameters(): __lowercase = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability __lowercase = param.data.to(torch.floataa ) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(_UpperCAmelCase ) ): __lowercase = LoRALayer(module.q_proj , rank=16 ) __lowercase = LoRALayer(module.k_proj , rank=16 ) __lowercase = LoRALayer(module.v_proj , rank=16 ) # Step 3: dummy batch __lowercase = self.tokenizer('Test batch ' , return_tensors='pt' ).to(0 ) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): __lowercase = model.forward(**_UpperCAmelCase ) out.logits.norm().backward() for module in model.modules(): if isinstance(_UpperCAmelCase , _UpperCAmelCase ): self.assertTrue(module.adapter[1].weight.grad is not None ) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 ) elif isinstance(_UpperCAmelCase , nn.Embedding ): self.assertTrue(module.weight.grad is None ) class A__ ( lowerCAmelCase__ ): lowerCAmelCase__ : Any = "gpt2-xl" lowerCAmelCase__ : str = 3.3191854854152187
325
0
import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCamelCase_ : def __init__( self : str ,__lowerCamelCase : Any ,__lowerCamelCase : Optional[Any]=13 ,__lowerCamelCase : int=32 ,__lowerCamelCase : List[str]=3 ,__lowerCamelCase : int=4 ,__lowerCamelCase : Tuple=[10, 20, 30, 40] ,__lowerCamelCase : Optional[int]=[2, 2, 3, 2] ,__lowerCamelCase : int=True ,__lowerCamelCase : Tuple=True ,__lowerCamelCase : Union[str, Any]=37 ,__lowerCamelCase : Dict="gelu" ,__lowerCamelCase : int=10 ,__lowerCamelCase : Any=0.02 ,__lowerCamelCase : Dict=["stage2", "stage3", "stage4"] ,__lowerCamelCase : Tuple=[2, 3, 4] ,__lowerCamelCase : Dict=None ,): '''simple docstring''' a = parent a = batch_size a = image_size a = num_channels a = num_stages a = hidden_sizes a = depths a = is_training a = use_labels a = intermediate_size a = hidden_act a = num_labels a = initializer_range a = out_features a = out_indices a = scope def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = None if self.use_labels: a = ids_tensor([self.batch_size] ,self.num_labels ) a = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return ConvNextVaConfig( num_channels=self.num_channels ,hidden_sizes=self.hidden_sizes ,depths=self.depths ,num_stages=self.num_stages ,hidden_act=self.hidden_act ,is_decoder=__lowerCamelCase ,initializer_range=self.initializer_range ,out_features=self.out_features ,out_indices=self.out_indices ,num_labels=self.num_labels ,) def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : Optional[int] ): '''simple docstring''' a = ConvNextVaModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ,__lowerCamelCase : Tuple ,__lowerCamelCase : Dict ,__lowerCamelCase : int ): '''simple docstring''' a = ConvNextVaForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ,labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[str] ,__lowerCamelCase : Optional[int] ): '''simple docstring''' a = ConvNextVaBackbone(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) ,len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) ,len(config.out_features ) ) self.parent.assertListEqual(model.channels ,config.hidden_sizes[1:] ) # verify backbone works with out_features=None a = None a = ConvNextVaBackbone(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) ,1 ) self.parent.assertListEqual(model.channels ,[config.hidden_sizes[-1]] ) def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = self.prepare_config_and_inputs() a = config_and_inputs a = {"""pixel_values""": pixel_values} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = self.prepare_config_and_inputs() a = config_and_inputs a = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE_ = ( {'feature-extraction': ConvNextVaModel, 'image-classification': ConvNextVaForImageClassification} if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = ConvNextVaModelTester(self ) a = ConfigTester(self ,config_class=__lowerCamelCase ,has_text_modality=__lowerCamelCase ,hidden_size=37 ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' return @unittest.skip(reason='''ConvNextV2 does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' pass @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking''' ) def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: a = self.model_tester.prepare_config_and_inputs_with_labels() a = True if model_class.__name__ in [ *get_values(__lowerCamelCase ), *get_values(__lowerCamelCase ), ]: continue a = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() a = self._prepare_for_class(__lowerCamelCase ,__lowerCamelCase ,return_labels=__lowerCamelCase ) a = model(**__lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: a = self.model_tester.prepare_config_and_inputs_with_labels() a = False a = True if ( model_class.__name__ in [*get_values(__lowerCamelCase ), *get_values(__lowerCamelCase )] or not model_class.supports_gradient_checkpointing ): continue a = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.gradient_checkpointing_enable() model.train() a = self._prepare_for_class(__lowerCamelCase ,__lowerCamelCase ,return_labels=__lowerCamelCase ) a = model(**__lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__lowerCamelCase ) a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a = [*signature.parameters.keys()] a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' def check_hidden_states_output(__lowerCamelCase : Optional[int] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : int ): a = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): a = model(**self._prepare_for_class(__lowerCamelCase ,__lowerCamelCase ) ) a = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states a = self.model_tester.num_stages self.assertEqual(len(__lowerCamelCase ) ,expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,) a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = True check_hidden_states_output(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a = True check_hidden_states_output(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = ConvNextVaModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( ) -> int: """simple docstring""" a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCamelCase_ ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ).to(__lowerCamelCase ) a = self.default_image_processor a = prepare_img() a = preprocessor(images=__lowerCamelCase ,return_tensors='''pt''' ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): a = model(**__lowerCamelCase ) # verify the logits a = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape ,__lowerCamelCase ) a = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,__lowerCamelCase ,atol=1e-4 ) )
351
import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class lowerCamelCase_ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = FlaxXLMRobertaModel.from_pretrained('''xlm-roberta-base''' ) a = AutoTokenizer.from_pretrained('''xlm-roberta-base''' ) a = '''The dog is cute and lives in the garden house''' a = jnp.array([tokenizer.encode(__lowerCamelCase )] ) a = (1, 12, 7_68) # batch_size, sequence_length, embedding_vector_dim a = jnp.array( [[-0.0_101, 0.1_218, -0.0_803, 0.0_801, 0.1_327, 0.0_776, -0.1_215, 0.2_383, 0.3_338, 0.3_106, 0.0_300, 0.0_252]] ) a = model(__lowerCamelCase )['''last_hidden_state'''] self.assertEqual(output.shape ,__lowerCamelCase ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] ,__lowerCamelCase ,atol=1e-3 ) )
330
0
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 _lowerCAmelCase ( __a ): _lowercase ='''gpt_neox''' def __init__( self , _UpperCamelCase=50_432 , _UpperCamelCase=6_144 , _UpperCamelCase=44 , _UpperCamelCase=64 , _UpperCamelCase=24_576 , _UpperCamelCase="gelu" , _UpperCamelCase=0.25 , _UpperCamelCase=10_000 , _UpperCamelCase=0.0 , _UpperCamelCase=0.0 , _UpperCamelCase=0.1 , _UpperCamelCase=2_048 , _UpperCamelCase=0.02 , _UpperCamelCase=1e-5 , _UpperCamelCase=True , _UpperCamelCase=0 , _UpperCamelCase=2 , _UpperCamelCase=False , _UpperCamelCase=True , _UpperCamelCase=None , **_UpperCamelCase , ) -> Dict: super().__init__(bos_token_id=_UpperCamelCase , eos_token_id=_UpperCamelCase , **_UpperCamelCase ) lowerCAmelCase_ = vocab_size lowerCAmelCase_ = max_position_embeddings lowerCAmelCase_ = hidden_size lowerCAmelCase_ = num_hidden_layers lowerCAmelCase_ = num_attention_heads lowerCAmelCase_ = intermediate_size lowerCAmelCase_ = hidden_act lowerCAmelCase_ = rotary_pct lowerCAmelCase_ = rotary_emb_base lowerCAmelCase_ = attention_dropout lowerCAmelCase_ = hidden_dropout lowerCAmelCase_ = classifier_dropout lowerCAmelCase_ = initializer_range lowerCAmelCase_ = layer_norm_eps lowerCAmelCase_ = use_cache lowerCAmelCase_ = tie_word_embeddings lowerCAmelCase_ = use_parallel_residual lowerCAmelCase_ = 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 __a ( self ) -> Tuple: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _UpperCamelCase ) 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}""" ) lowerCAmelCase_ = self.rope_scaling.get("type" , _UpperCamelCase ) lowerCAmelCase_ = self.rope_scaling.get("factor" , _UpperCamelCase ) 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(_UpperCamelCase , _UpperCamelCase ) or rope_scaling_factor <= 1.0: raise ValueError(f"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
231
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { "configuration_distilbert": [ "DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DistilBertConfig", "DistilBertOnnxConfig", ], "tokenization_distilbert": ["DistilBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ["DistilBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ "DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "DistilBertForMaskedLM", "DistilBertForMultipleChoice", "DistilBertForQuestionAnswering", "DistilBertForSequenceClassification", "DistilBertForTokenClassification", "DistilBertModel", "DistilBertPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ "TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDistilBertForMaskedLM", "TFDistilBertForMultipleChoice", "TFDistilBertForQuestionAnswering", "TFDistilBertForSequenceClassification", "TFDistilBertForTokenClassification", "TFDistilBertMainLayer", "TFDistilBertModel", "TFDistilBertPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ "FlaxDistilBertForMaskedLM", "FlaxDistilBertForMultipleChoice", "FlaxDistilBertForQuestionAnswering", "FlaxDistilBertForSequenceClassification", "FlaxDistilBertForTokenClassification", "FlaxDistilBertModel", "FlaxDistilBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
231
1
import argparse from .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def __lowerCamelCase ( lowerCAmelCase__=None ): lowerCAmelCase__ = argparse.ArgumentParser(add_help=lowerCAmelCase__ , allow_abbrev=lowerCAmelCase__ ) # The main config parser lowerCAmelCase__ = config_command_parser(lowerCAmelCase__ ) # The subparser to add commands to lowerCAmelCase__ = config_parser.add_subparsers(title='subcommands' , dest='subcommand' ) # Then add other parsers with the parent parser default_command_parser(lowerCAmelCase__ , parents=[parent_parser] ) update_command_parser(lowerCAmelCase__ , parents=[parent_parser] ) return config_parser def __lowerCamelCase ( ): lowerCAmelCase__ = get_config_parser() lowerCAmelCase__ = config_parser.parse_args() if not hasattr(lowerCAmelCase__ , 'func' ): config_parser.print_help() exit(1 ) # Run args.func(lowerCAmelCase__ ) if __name__ == "__main__": main()
352
import numpy as np def __lowerCamelCase ( lowerCAmelCase__ ): return 1 / (1 + np.exp(-vector )) def __lowerCamelCase ( lowerCAmelCase__ ): return vector * sigmoid(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
119
0
'''simple docstring''' from typing import Dict from .base import GenericTensor, Pipeline class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" def A ( self : Optional[int] , UpperCamelCase__ : Dict=None , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : Any=None , **UpperCamelCase__ : List[str] ): """simple docstring""" if tokenize_kwargs is None: UpperCamelCase = {} if truncation is not None: if "truncation" in tokenize_kwargs: raise ValueError( 'truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)' ) UpperCamelCase = truncation UpperCamelCase = tokenize_kwargs UpperCamelCase = {} if return_tensors is not None: UpperCamelCase = return_tensors return preprocess_params, {}, postprocess_params def A ( self : List[Any] , UpperCamelCase__ : int , **UpperCamelCase__ : Union[str, Any] ): """simple docstring""" UpperCamelCase = self.framework UpperCamelCase = self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) return model_inputs def A ( self : Any , UpperCamelCase__ : str ): """simple docstring""" UpperCamelCase = self.model(**UpperCamelCase__ ) return model_outputs def A ( self : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str]=False ): """simple docstring""" if return_tensors: return model_outputs[0] if self.framework == "pt": return model_outputs[0].tolist() elif self.framework == "tf": return model_outputs[0].numpy().tolist() def __call__( self : Tuple , *UpperCamelCase__ : Tuple , **UpperCamelCase__ : str ): """simple docstring""" return super().__call__(*UpperCamelCase__ , **UpperCamelCase__ )
28
"""simple docstring""" import json import re from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np from ...utils import is_tf_available, is_torch_available, logging if TYPE_CHECKING: if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_codegen import CodeGenTokenizer A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''vocab_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json''', }, '''merges_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''Salesforce/codegen-350M-mono''': ( '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json''' ), }, } A_ = { '''Salesforce/codegen-350M-mono''': 20_48, } class lowercase( __a ): '''simple docstring''' lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["input_ids", "attention_mask"] lowercase__ = CodeGenTokenizer def __init__( self: Union[str, Any], a_: List[Any]=None, a_: str=None, a_: str=None, a_: Dict="<|endoftext|>", a_: Tuple="<|endoftext|>", a_: str="<|endoftext|>", a_: List[Any]=False, **a_: List[str], ): '''simple docstring''' super().__init__( a_, a_, tokenizer_file=a_, unk_token=a_, bos_token=a_, eos_token=a_, add_prefix_space=a_, **a_, ) if kwargs.pop("""add_bos_token""", a_ ): _snake_case : str = kwargs.pop("""name_or_path""", """""" ) raise ValueError( """Currenty GPT2's fast tokenizer does NOT support adding a BOS token.""" """Instead you should use GPT2's slow tokenizer class `CodeGenTokenizer` as follows: \n""" f"`CodeGenTokenizer.from_pretrained('{model_id}')`\nor\n" f"`AutoTokenizer.from_pretrained('{model_id}', use_fast=False)`\n" """This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.""" """ so that the fast tokenizer works correctly.""" ) _snake_case : Tuple = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""", a_ ) != add_prefix_space: _snake_case : Dict = getattr(a_, pre_tok_state.pop("""type""" ) ) _snake_case : Dict = add_prefix_space _snake_case : str = pre_tok_class(**a_ ) _snake_case : List[Any] = add_prefix_space def UpperCamelCase_ ( self: Any, *a_: Any, **a_: int ): '''simple docstring''' _snake_case : Optional[int] = kwargs.get("""is_split_into_words""", a_ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Optional[Any], *a_: Any, **a_: List[str] ): '''simple docstring''' _snake_case : Dict = kwargs.get("""is_split_into_words""", a_ ) assert self.add_prefix_space or not is_split_into_words, ( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*a_, **a_ ) def UpperCamelCase_ ( self: Optional[int], a_: str, a_: Optional[str] = None ): '''simple docstring''' _snake_case : List[Any] = self._tokenizer.model.save(a_, name=a_ ) return tuple(a_ ) def UpperCamelCase_ ( self: str, a_: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"], a_: bool = False, a_: bool = None, a_: Optional[List[str]] = None, **a_: List[str], ): '''simple docstring''' _snake_case : Any = super().decode( token_ids=a_, skip_special_tokens=a_, clean_up_tokenization_spaces=a_, **a_, ) if truncate_before_pattern is not None and len(a_ ) > 0: _snake_case : List[str] = self.truncate(a_, a_ ) return decoded_text def UpperCamelCase_ ( self: Dict, a_: Tuple, a_: Optional[Any] ): '''simple docstring''' def find_re(a_: Dict, a_: str, a_: Union[str, Any] ): _snake_case : Any = pattern.search(a_, a_ ) return m.start() if m else -1 _snake_case : Tuple = [re.compile(a_, re.MULTILINE ) for pattern in truncate_before_pattern] _snake_case : List[Any] = list(re.finditer("""^print""", a_, re.MULTILINE ) ) if len(a_ ) > 1: _snake_case : int = completion[: prints[1].start()] _snake_case : List[str] = list(re.finditer("""^def""", a_, re.MULTILINE ) ) if len(a_ ) > 1: _snake_case : List[Any] = completion[: defs[1].start()] _snake_case : int = 0 _snake_case : List[Any] = [ pos for pos in [find_re(a_, a_, a_ ) for terminal in terminals] if pos != -1 ] if len(a_ ) > 0: return completion[: min(a_ )] else: return completion
64
0
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar _SCREAMING_SNAKE_CASE = TypeVar("""T""") def lowercase( UpperCamelCase_ ) -> int: '''simple docstring''' return (position - 1) // 2 def lowercase( UpperCamelCase_ ) -> int: '''simple docstring''' return (2 * position) + 1 def lowercase( UpperCamelCase_ ) -> int: '''simple docstring''' return (2 * position) + 2 class SCREAMING_SNAKE_CASE_ ( Generic[T] ): def __init__( self : List[str] ): """simple docstring""" UpperCamelCase = [] UpperCamelCase = {} UpperCamelCase = 0 def __len__( self : Dict ): """simple docstring""" return self.elements def __repr__( self : Union[str, Any] ): """simple docstring""" return str(self.heap ) def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" return self.elements == 0 def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : T , lowerCamelCase_ : int ): """simple docstring""" self.heap.append((elem, weight) ) UpperCamelCase = self.elements self.elements += 1 self._bubble_up(lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple ): """simple docstring""" if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) UpperCamelCase , UpperCamelCase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: UpperCamelCase , UpperCamelCase = self.heap[0] self._bubble_down(lowerCamelCase_ ) return elem def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : T , lowerCamelCase_ : int ): """simple docstring""" UpperCamelCase = self.position_map[elem] UpperCamelCase = (elem, weight) if position > 0: UpperCamelCase = get_parent_position(lowerCamelCase_ ) UpperCamelCase , UpperCamelCase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(lowerCamelCase_ ) else: self._bubble_down(lowerCamelCase_ ) else: self._bubble_down(lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : T ): """simple docstring""" UpperCamelCase = self.position_map[elem] if curr_pos == 0: return None UpperCamelCase = get_parent_position(lowerCamelCase_ ) UpperCamelCase , UpperCamelCase = self.heap[curr_pos] UpperCamelCase , UpperCamelCase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(lowerCamelCase_ , lowerCamelCase_ ) return self._bubble_up(lowerCamelCase_ ) return None def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : T ): """simple docstring""" UpperCamelCase = self.position_map[elem] UpperCamelCase , UpperCamelCase = self.heap[curr_pos] UpperCamelCase = get_child_left_position(lowerCamelCase_ ) UpperCamelCase = get_child_right_position(lowerCamelCase_ ) if child_left_position < self.elements and child_right_position < self.elements: UpperCamelCase , UpperCamelCase = self.heap[child_left_position] UpperCamelCase , UpperCamelCase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(lowerCamelCase_ , lowerCamelCase_ ) return self._bubble_down(lowerCamelCase_ ) if child_left_position < self.elements: UpperCamelCase , UpperCamelCase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(lowerCamelCase_ , lowerCamelCase_ ) return self._bubble_down(lowerCamelCase_ ) else: return None if child_right_position < self.elements: UpperCamelCase , UpperCamelCase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(lowerCamelCase_ , lowerCamelCase_ ) return self._bubble_down(lowerCamelCase_ ) return None def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : int , lowerCamelCase_ : int ): """simple docstring""" UpperCamelCase = self.heap[nodea_pos][0] UpperCamelCase = self.heap[nodea_pos][0] UpperCamelCase , UpperCamelCase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) UpperCamelCase = nodea_pos UpperCamelCase = nodea_pos class SCREAMING_SNAKE_CASE_ ( Generic[T] ): def __init__( self : Optional[Any] ): """simple docstring""" UpperCamelCase = {} UpperCamelCase = 0 def __repr__( self : Union[str, Any] ): """simple docstring""" return str(self.connections ) def __len__( self : int ): """simple docstring""" return self.nodes def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : T ): """simple docstring""" if node not in self.connections: UpperCamelCase = {} self.nodes += 1 def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : T , lowerCamelCase_ : T , lowerCamelCase_ : int ): """simple docstring""" self.add_node(lowerCamelCase_ ) self.add_node(lowerCamelCase_ ) UpperCamelCase = weight UpperCamelCase = weight def lowercase( UpperCamelCase_ , ) -> tuple[dict[T, int], dict[T, T | None]]: '''simple docstring''' UpperCamelCase = {node: maxsize for node in graph.connections} UpperCamelCase = {node: None for node in graph.connections} UpperCamelCase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(UpperCamelCase_ , UpperCamelCase_ ) if priority_queue.is_empty(): return dist, parent # initialization UpperCamelCase = priority_queue.extract_min() UpperCamelCase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: UpperCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(UpperCamelCase_ , dist[neighbour] ) UpperCamelCase = node # running prim's algorithm while not priority_queue.is_empty(): UpperCamelCase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: UpperCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(UpperCamelCase_ , dist[neighbour] ) UpperCamelCase = node return dist, parent
359
def lowercase( UpperCamelCase_ ) -> list[list]: '''simple docstring''' UpperCamelCase = current_set.copy() for row_index, row in enumerate(UpperCamelCase_ ): UpperCamelCase = row[0] for column_index, column in enumerate(UpperCamelCase_ ): if magnitude == 0: UpperCamelCase = column continue UpperCamelCase = column / magnitude # Subtract to cancel term UpperCamelCase = current_set[0] UpperCamelCase = [first_row] UpperCamelCase = current_set[1::] for row in current_set: UpperCamelCase = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(UpperCamelCase_ ) continue for column_index in range(len(UpperCamelCase_ ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(UpperCamelCase_ ) # Create next recursion iteration set if len(final_set[0] ) != 3: UpperCamelCase = final_set[0] UpperCamelCase = [] UpperCamelCase = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) UpperCamelCase = simplify(UpperCamelCase_ ) for i in range(len(UpperCamelCase_ ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , UpperCamelCase_ ) UpperCamelCase = resultant return final_set def lowercase( UpperCamelCase_ ) -> list: '''simple docstring''' if len(UpperCamelCase_ ) == 0: raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) UpperCamelCase = len(UpperCamelCase_ ) + 1 if any(len(UpperCamelCase_ ) != _length for item in equations ): raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) for row in equations: if any(not isinstance(UpperCamelCase_ , (int, float) ) for column in row ): raise ValueError("""solve_simultaneous() requires lists of integers""" ) if len(UpperCamelCase_ ) == 1: return [equations[0][-1] / equations[0][0]] UpperCamelCase = equations.copy() if any(0 in row for row in data_set ): UpperCamelCase = data_set.copy() UpperCamelCase = [] for row_index, row in enumerate(UpperCamelCase_ ): if 0 not in row: UpperCamelCase = data_set.pop(UpperCamelCase_ ) break if not full_row: raise ValueError("""solve_simultaneous() requires at least 1 full equation""" ) data_set.insert(0 , UpperCamelCase_ ) UpperCamelCase = data_set.copy() UpperCamelCase = simplify(UpperCamelCase_ ) UpperCamelCase = simplified[::-1] UpperCamelCase = [] for row in simplified: UpperCamelCase = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue UpperCamelCase = row.copy()[: len(UpperCamelCase_ ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(UpperCamelCase_ ) == 0: solutions.append(0 ) continue UpperCamelCase = temp_row[1::] UpperCamelCase = temp_row[::-1] for column_index, column in enumerate(UpperCamelCase_ ): current_solution -= column * solutions[column_index] solutions.append(UpperCamelCase_ ) UpperCamelCase = [] for item in solutions: final.append(float(round(UpperCamelCase_ , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() _SCREAMING_SNAKE_CASE = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
165
0
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class lowerCAmelCase ( __UpperCamelCase ): UpperCAmelCase__ = 42 class lowerCAmelCase ( nn.Module ): def __init__( self : Tuple , UpperCAmelCase : Dict=3 , UpperCAmelCase : Union[str, Any]=3 , UpperCAmelCase : Optional[Any]=("DownEncoderBlock2D",) , UpperCAmelCase : List[str]=(64,) , UpperCAmelCase : Any=2 , UpperCAmelCase : List[Any]=32 , UpperCAmelCase : List[str]="silu" , UpperCAmelCase : Tuple=True , ) -> Tuple: super().__init__() lowerCamelCase__ : Optional[Any] = layers_per_block lowerCamelCase__ : Dict = torch.nn.Convad( UpperCAmelCase , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) lowerCamelCase__ : Tuple = None lowerCamelCase__ : Union[str, Any] = nn.ModuleList([] ) # down lowerCamelCase__ : Tuple = block_out_channels[0] for i, down_block_type in enumerate(UpperCAmelCase ): lowerCamelCase__ : List[Any] = output_channel lowerCamelCase__ : Dict = block_out_channels[i] lowerCamelCase__ : int = i == len(UpperCAmelCase ) - 1 lowerCamelCase__ : int = get_down_block( UpperCAmelCase , num_layers=self.layers_per_block , in_channels=UpperCAmelCase , out_channels=UpperCAmelCase , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=UpperCAmelCase , resnet_groups=UpperCAmelCase , attention_head_dim=UpperCAmelCase , temb_channels=UpperCAmelCase , ) self.down_blocks.append(UpperCAmelCase ) # mid lowerCamelCase__ : Tuple = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=UpperCAmelCase , output_scale_factor=1 , resnet_time_scale_shift='default' , attention_head_dim=block_out_channels[-1] , resnet_groups=UpperCAmelCase , temb_channels=UpperCAmelCase , ) # out lowerCamelCase__ : Optional[Any] = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=UpperCAmelCase , eps=1e-6 ) lowerCamelCase__ : List[Any] = nn.SiLU() lowerCamelCase__ : List[str] = 2 * out_channels if double_z else out_channels lowerCamelCase__ : Any = nn.Convad(block_out_channels[-1] , UpperCAmelCase , 3 , padding=1 ) lowerCamelCase__ : List[Any] = False def A_ ( self : Dict , UpperCAmelCase : Optional[int] ) -> Union[str, Any]: lowerCamelCase__ : Dict = x lowerCamelCase__ : Dict = self.conv_in(UpperCAmelCase ) if self.training and self.gradient_checkpointing: def create_custom_forward(UpperCAmelCase : Dict ): def custom_forward(*UpperCAmelCase : Any ): return module(*UpperCAmelCase ) return custom_forward # down if is_torch_version('>=' , '1.11.0' ): for down_block in self.down_blocks: lowerCamelCase__ : Optional[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(UpperCAmelCase ) , UpperCAmelCase , use_reentrant=UpperCAmelCase ) # middle lowerCamelCase__ : Tuple = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , UpperCAmelCase , use_reentrant=UpperCAmelCase ) else: for down_block in self.down_blocks: lowerCamelCase__ : str = torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCAmelCase ) , UpperCAmelCase ) # middle lowerCamelCase__ : Dict = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , UpperCAmelCase ) else: # down for down_block in self.down_blocks: lowerCamelCase__ : Optional[Any] = down_block(UpperCAmelCase ) # middle lowerCamelCase__ : List[str] = self.mid_block(UpperCAmelCase ) # post-process lowerCamelCase__ : str = self.conv_norm_out(UpperCAmelCase ) lowerCamelCase__ : List[Any] = self.conv_act(UpperCAmelCase ) lowerCamelCase__ : Union[str, Any] = self.conv_out(UpperCAmelCase ) return sample class lowerCAmelCase ( nn.Module ): def __init__( self : Any , UpperCAmelCase : Optional[int]=3 , UpperCAmelCase : List[Any]=3 , UpperCAmelCase : int=("UpDecoderBlock2D",) , UpperCAmelCase : Optional[Any]=(64,) , UpperCAmelCase : str=2 , UpperCAmelCase : Union[str, Any]=32 , UpperCAmelCase : int="silu" , UpperCAmelCase : List[str]="group" , ) -> Any: super().__init__() lowerCamelCase__ : List[str] = layers_per_block lowerCamelCase__ : Optional[Any] = nn.Convad( UpperCAmelCase , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) lowerCamelCase__ : Dict = None lowerCamelCase__ : List[str] = nn.ModuleList([] ) lowerCamelCase__ : Dict = in_channels if norm_type == 'spatial' else None # mid lowerCamelCase__ : List[Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=UpperCAmelCase , output_scale_factor=1 , resnet_time_scale_shift='default' if norm_type == 'group' else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=UpperCAmelCase , temb_channels=UpperCAmelCase , ) # up lowerCamelCase__ : Tuple = list(reversed(UpperCAmelCase ) ) lowerCamelCase__ : Dict = reversed_block_out_channels[0] for i, up_block_type in enumerate(UpperCAmelCase ): lowerCamelCase__ : Dict = output_channel lowerCamelCase__ : List[Any] = reversed_block_out_channels[i] lowerCamelCase__ : Union[str, Any] = i == len(UpperCAmelCase ) - 1 lowerCamelCase__ : Union[str, Any] = get_up_block( UpperCAmelCase , num_layers=self.layers_per_block + 1 , in_channels=UpperCAmelCase , out_channels=UpperCAmelCase , prev_output_channel=UpperCAmelCase , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=UpperCAmelCase , resnet_groups=UpperCAmelCase , attention_head_dim=UpperCAmelCase , temb_channels=UpperCAmelCase , resnet_time_scale_shift=UpperCAmelCase , ) self.up_blocks.append(UpperCAmelCase ) lowerCamelCase__ : str = output_channel # out if norm_type == "spatial": lowerCamelCase__ : Any = SpatialNorm(block_out_channels[0] , UpperCAmelCase ) else: lowerCamelCase__ : Optional[Any] = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=UpperCAmelCase , eps=1e-6 ) lowerCamelCase__ : Tuple = nn.SiLU() lowerCamelCase__ : Union[str, Any] = nn.Convad(block_out_channels[0] , UpperCAmelCase , 3 , padding=1 ) lowerCamelCase__ : Dict = False def A_ ( self : Tuple , UpperCAmelCase : Tuple , UpperCAmelCase : Any=None ) -> List[str]: lowerCamelCase__ : Any = z lowerCamelCase__ : Union[str, Any] = self.conv_in(UpperCAmelCase ) lowerCamelCase__ : Optional[int] = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(UpperCAmelCase : Any ): def custom_forward(*UpperCAmelCase : Any ): return module(*UpperCAmelCase ) return custom_forward if is_torch_version('>=' , '1.11.0' ): # middle lowerCamelCase__ : str = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , UpperCAmelCase , UpperCAmelCase , use_reentrant=UpperCAmelCase ) lowerCamelCase__ : Tuple = sample.to(UpperCAmelCase ) # up for up_block in self.up_blocks: lowerCamelCase__ : str = torch.utils.checkpoint.checkpoint( create_custom_forward(UpperCAmelCase ) , UpperCAmelCase , UpperCAmelCase , use_reentrant=UpperCAmelCase ) else: # middle lowerCamelCase__ : str = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Dict = sample.to(UpperCAmelCase ) # up for up_block in self.up_blocks: lowerCamelCase__ : Tuple = torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCAmelCase ) , UpperCAmelCase , UpperCAmelCase ) else: # middle lowerCamelCase__ : Any = self.mid_block(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : Optional[int] = sample.to(UpperCAmelCase ) # up for up_block in self.up_blocks: lowerCamelCase__ : List[Any] = up_block(UpperCAmelCase , UpperCAmelCase ) # post-process if latent_embeds is None: lowerCamelCase__ : str = self.conv_norm_out(UpperCAmelCase ) else: lowerCamelCase__ : Optional[Any] = self.conv_norm_out(UpperCAmelCase , UpperCAmelCase ) lowerCamelCase__ : List[str] = self.conv_act(UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = self.conv_out(UpperCAmelCase ) return sample class lowerCAmelCase ( nn.Module ): def __init__( self : Dict , UpperCAmelCase : str , UpperCAmelCase : Optional[int] , UpperCAmelCase : Optional[Any] , UpperCAmelCase : str=None , UpperCAmelCase : Optional[Any]="random" , UpperCAmelCase : Optional[int]=False , UpperCAmelCase : List[Any]=True ) -> Optional[int]: super().__init__() lowerCamelCase__ : int = n_e lowerCamelCase__ : Any = vq_embed_dim lowerCamelCase__ : Optional[int] = beta lowerCamelCase__ : Optional[Any] = legacy lowerCamelCase__ : Any = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) lowerCamelCase__ : Any = remap if self.remap is not None: self.register_buffer('used' , torch.tensor(np.load(self.remap ) ) ) lowerCamelCase__ : str = self.used.shape[0] lowerCamelCase__ : Any = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": lowerCamelCase__ : List[Any] = self.re_embed lowerCamelCase__ : List[Any] = self.re_embed + 1 print( F"""Remapping {self.n_e} indices to {self.re_embed} indices. """ F"""Using {self.unknown_index} for unknown indices.""" ) else: lowerCamelCase__ : List[Any] = n_e lowerCamelCase__ : Optional[Any] = sane_index_shape def A_ ( self : Union[str, Any] , UpperCAmelCase : Any ) -> Dict: lowerCamelCase__ : Any = inds.shape assert len(UpperCAmelCase ) > 1 lowerCamelCase__ : str = inds.reshape(ishape[0] , -1 ) lowerCamelCase__ : str = self.used.to(UpperCAmelCase ) lowerCamelCase__ : Dict = (inds[:, :, None] == used[None, None, ...]).long() lowerCamelCase__ : Optional[int] = match.argmax(-1 ) lowerCamelCase__ : Dict = match.sum(2 ) < 1 if self.unknown_index == "random": lowerCamelCase__ : Optional[int] = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: lowerCamelCase__ : int = self.unknown_index return new.reshape(UpperCAmelCase ) def A_ ( self : List[str] , UpperCAmelCase : Tuple ) -> Optional[int]: lowerCamelCase__ : List[Any] = inds.shape assert len(UpperCAmelCase ) > 1 lowerCamelCase__ : List[Any] = inds.reshape(ishape[0] , -1 ) lowerCamelCase__ : str = self.used.to(UpperCAmelCase ) if self.re_embed > self.used.shape[0]: # extra token lowerCamelCase__ : Any = 0 # simply set to zero lowerCamelCase__ : Any = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , UpperCAmelCase ) return back.reshape(UpperCAmelCase ) def A_ ( self : Tuple , UpperCAmelCase : Union[str, Any] ) -> Optional[int]: # reshape z -> (batch, height, width, channel) and flatten lowerCamelCase__ : Tuple = z.permute(0 , 2 , 3 , 1 ).contiguous() lowerCamelCase__ : List[Any] = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z lowerCamelCase__ : List[str] = torch.argmin(torch.cdist(UpperCAmelCase , self.embedding.weight ) , dim=1 ) lowerCamelCase__ : Optional[Any] = self.embedding(UpperCAmelCase ).view(z.shape ) lowerCamelCase__ : int = None lowerCamelCase__ : Union[str, Any] = None # compute loss for embedding if not self.legacy: lowerCamelCase__ : Dict = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: lowerCamelCase__ : List[str] = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients lowerCamelCase__ : Union[str, Any] = z + (z_q - z).detach() # reshape back to match original input shape lowerCamelCase__ : Any = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: lowerCamelCase__ : int = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis lowerCamelCase__ : Union[str, Any] = self.remap_to_used(UpperCAmelCase ) lowerCamelCase__ : Optional[int] = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: lowerCamelCase__ : Any = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def A_ ( self : int , UpperCAmelCase : Dict , UpperCAmelCase : List[Any] ) -> List[Any]: # shape specifying (batch, height, width, channel) if self.remap is not None: lowerCamelCase__ : str = indices.reshape(shape[0] , -1 ) # add batch axis lowerCamelCase__ : Optional[Any] = self.unmap_to_all(UpperCAmelCase ) lowerCamelCase__ : Union[str, Any] = indices.reshape(-1 ) # flatten again # get quantized latent vectors lowerCamelCase__ : str = self.embedding(UpperCAmelCase ) if shape is not None: lowerCamelCase__ : List[str] = z_q.view(UpperCAmelCase ) # reshape back to match original input shape lowerCamelCase__ : Union[str, Any] = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class lowerCAmelCase ( __UpperCamelCase ): def __init__( self : Any , UpperCAmelCase : Tuple , UpperCAmelCase : List[Any]=False ) -> List[str]: lowerCamelCase__ : List[str] = parameters lowerCamelCase__ , lowerCamelCase__ : List[str] = torch.chunk(UpperCAmelCase , 2 , dim=1 ) lowerCamelCase__ : Union[str, Any] = torch.clamp(self.logvar , -3_0.0 , 2_0.0 ) lowerCamelCase__ : List[Any] = deterministic lowerCamelCase__ : Optional[int] = torch.exp(0.5 * self.logvar ) lowerCamelCase__ : Optional[Any] = torch.exp(self.logvar ) if self.deterministic: lowerCamelCase__ : str = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def A_ ( self : List[str] , UpperCAmelCase : Optional[torch.Generator] = None ) -> torch.FloatTensor: # make sure sample is on the same device as the parameters and has same dtype lowerCamelCase__ : Any = randn_tensor( self.mean.shape , generator=UpperCAmelCase , device=self.parameters.device , dtype=self.parameters.dtype ) lowerCamelCase__ : Optional[int] = self.mean + self.std * sample return x def A_ ( self : Dict , UpperCAmelCase : Optional[Any]=None ) -> Optional[Any]: if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def A_ ( self : str , UpperCAmelCase : int , UpperCAmelCase : List[Any]=[1, 2, 3] ) -> List[str]: if self.deterministic: return torch.Tensor([0.0] ) lowerCamelCase__ : int = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=UpperCAmelCase ) def A_ ( self : Optional[int] ) -> List[str]: return self.mean
50
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class lowerCAmelCase ( __UpperCamelCase ): UpperCAmelCase__ = 42 class lowerCAmelCase ( __UpperCamelCase, __UpperCamelCase ): @register_to_config def __init__( self : List[str] , UpperCAmelCase : int = 65536 , UpperCAmelCase : Optional[int] = None , UpperCAmelCase : int = 2 , UpperCAmelCase : int = 2 , UpperCAmelCase : int = 0 , UpperCAmelCase : str = "fourier" , UpperCAmelCase : bool = True , UpperCAmelCase : bool = False , UpperCAmelCase : float = 0.0 , UpperCAmelCase : Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , UpperCAmelCase : Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , UpperCAmelCase : Tuple[str] = "UNetMidBlock1D" , UpperCAmelCase : str = None , UpperCAmelCase : Tuple[int] = (32, 32, 64) , UpperCAmelCase : str = None , UpperCAmelCase : int = 8 , UpperCAmelCase : int = 1 , UpperCAmelCase : bool = False , ) -> List[Any]: super().__init__() lowerCamelCase__ : Optional[int] = sample_size # time if time_embedding_type == "fourier": lowerCamelCase__ : Optional[Any] = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=UpperCAmelCase , log=UpperCAmelCase , flip_sin_to_cos=UpperCAmelCase ) lowerCamelCase__ : Any = 2 * block_out_channels[0] elif time_embedding_type == "positional": lowerCamelCase__ : List[Any] = Timesteps( block_out_channels[0] , flip_sin_to_cos=UpperCAmelCase , downscale_freq_shift=UpperCAmelCase ) lowerCamelCase__ : Dict = block_out_channels[0] if use_timestep_embedding: lowerCamelCase__ : str = block_out_channels[0] * 4 lowerCamelCase__ : List[Any] = TimestepEmbedding( in_channels=UpperCAmelCase , time_embed_dim=UpperCAmelCase , act_fn=UpperCAmelCase , out_dim=block_out_channels[0] , ) lowerCamelCase__ : Any = nn.ModuleList([] ) lowerCamelCase__ : Tuple = None lowerCamelCase__ : List[str] = nn.ModuleList([] ) lowerCamelCase__ : Optional[int] = None # down lowerCamelCase__ : Optional[int] = in_channels for i, down_block_type in enumerate(UpperCAmelCase ): lowerCamelCase__ : Union[str, Any] = output_channel lowerCamelCase__ : Tuple = block_out_channels[i] if i == 0: input_channel += extra_in_channels lowerCamelCase__ : Union[str, Any] = i == len(UpperCAmelCase ) - 1 lowerCamelCase__ : Optional[int] = get_down_block( UpperCAmelCase , num_layers=UpperCAmelCase , in_channels=UpperCAmelCase , out_channels=UpperCAmelCase , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(UpperCAmelCase ) # mid lowerCamelCase__ : Optional[int] = get_mid_block( UpperCAmelCase , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=UpperCAmelCase , add_downsample=UpperCAmelCase , ) # up lowerCamelCase__ : Optional[int] = list(reversed(UpperCAmelCase ) ) lowerCamelCase__ : Optional[int] = reversed_block_out_channels[0] if out_block_type is None: lowerCamelCase__ : List[str] = out_channels else: lowerCamelCase__ : Any = block_out_channels[0] for i, up_block_type in enumerate(UpperCAmelCase ): lowerCamelCase__ : Tuple = output_channel lowerCamelCase__ : Union[str, Any] = ( reversed_block_out_channels[i + 1] if i < len(UpperCAmelCase ) - 1 else final_upsample_channels ) lowerCamelCase__ : List[str] = i == len(UpperCAmelCase ) - 1 lowerCamelCase__ : Dict = get_up_block( UpperCAmelCase , num_layers=UpperCAmelCase , in_channels=UpperCAmelCase , out_channels=UpperCAmelCase , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(UpperCAmelCase ) lowerCamelCase__ : int = output_channel # out lowerCamelCase__ : int = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) lowerCamelCase__ : List[Any] = get_out_block( out_block_type=UpperCAmelCase , num_groups_out=UpperCAmelCase , embed_dim=block_out_channels[0] , out_channels=UpperCAmelCase , act_fn=UpperCAmelCase , fc_dim=block_out_channels[-1] // 4 , ) def A_ ( self : List[Any] , UpperCAmelCase : torch.FloatTensor , UpperCAmelCase : Union[torch.Tensor, float, int] , UpperCAmelCase : bool = True , ) -> Union[UNetaDOutput, Tuple]: lowerCamelCase__ : Optional[Any] = timestep if not torch.is_tensor(UpperCAmelCase ): lowerCamelCase__ : Optional[int] = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(UpperCAmelCase ) and len(timesteps.shape ) == 0: lowerCamelCase__ : List[str] = timesteps[None].to(sample.device ) lowerCamelCase__ : Optional[int] = self.time_proj(UpperCAmelCase ) if self.config.use_timestep_embedding: lowerCamelCase__ : str = self.time_mlp(UpperCAmelCase ) else: lowerCamelCase__ : List[str] = timestep_embed[..., None] lowerCamelCase__ : str = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) lowerCamelCase__ : str = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down lowerCamelCase__ : str = () for downsample_block in self.down_blocks: lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = downsample_block(hidden_states=UpperCAmelCase , temb=UpperCAmelCase ) down_block_res_samples += res_samples # 3. mid if self.mid_block: lowerCamelCase__ : Optional[Any] = self.mid_block(UpperCAmelCase , UpperCAmelCase ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): lowerCamelCase__ : Dict = down_block_res_samples[-1:] lowerCamelCase__ : Optional[Any] = down_block_res_samples[:-1] lowerCamelCase__ : Any = upsample_block(UpperCAmelCase , res_hidden_states_tuple=UpperCAmelCase , temb=UpperCAmelCase ) # 5. post-process if self.out_block: lowerCamelCase__ : Any = self.out_block(UpperCAmelCase , UpperCAmelCase ) if not return_dict: return (sample,) return UNetaDOutput(sample=UpperCAmelCase )
50
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ :Tuple = { '''configuration_jukebox''': [ '''JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''JukeboxConfig''', '''JukeboxPriorConfig''', '''JukeboxVQVAEConfig''', ], '''tokenization_jukebox''': ['''JukeboxTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ :Any = [ '''JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST''', '''JukeboxModel''', '''JukeboxPreTrainedModel''', '''JukeboxVQVAE''', '''JukeboxPrior''', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys A_ :Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
370
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING A_ :List[str] = { '''facebook/mask2former-swin-small-coco-instance''': ( '''https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json''' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } A_ :int = logging.get_logger(__name__) class __A ( a ): """simple docstring""" UpperCamelCase__ : Union[str, Any] ="""mask2former""" UpperCamelCase__ : Tuple =["""swin"""] UpperCamelCase__ : Dict ={"""hidden_size""": """hidden_dim"""} def __init__( self , lowerCamelCase__ = None , lowerCamelCase__ = 256 , lowerCamelCase__ = 256 , lowerCamelCase__ = 256 , lowerCamelCase__ = 1024 , lowerCamelCase__ = "relu" , lowerCamelCase__ = 6 , lowerCamelCase__ = 10 , lowerCamelCase__ = 8 , lowerCamelCase__ = 0.0 , lowerCamelCase__ = 2048 , lowerCamelCase__ = False , lowerCamelCase__ = False , lowerCamelCase__ = 4 , lowerCamelCase__ = 255 , lowerCamelCase__ = 100 , lowerCamelCase__ = 0.1 , lowerCamelCase__ = 2.0 , lowerCamelCase__ = 5.0 , lowerCamelCase__ = 5.0 , lowerCamelCase__ = 12544 , lowerCamelCase__ = 3.0 , lowerCamelCase__ = 0.75 , lowerCamelCase__ = 0.02 , lowerCamelCase__ = 1.0 , lowerCamelCase__ = True , lowerCamelCase__ = [4, 8, 16, 32] , lowerCamelCase__ = None , **lowerCamelCase__ , ): """simple docstring""" if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) __UpperCamelCase : Optional[int] =CONFIG_MAPPING['swin']( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=lowerCamelCase__ , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ): __UpperCamelCase : List[str] =backbone_config.pop('model_type' ) __UpperCamelCase : str =CONFIG_MAPPING[backbone_model_type] __UpperCamelCase : List[Any] =config_class.from_dict(lowerCamelCase__ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. ' f'Supported model types: {",".join(self.backbones_supported )}' ) __UpperCamelCase : Dict =backbone_config __UpperCamelCase : Optional[int] =feature_size __UpperCamelCase : Union[str, Any] =mask_feature_size __UpperCamelCase : Tuple =hidden_dim __UpperCamelCase : Optional[int] =encoder_feedforward_dim __UpperCamelCase : Optional[int] =activation_function __UpperCamelCase : Dict =encoder_layers __UpperCamelCase : List[Any] =decoder_layers __UpperCamelCase : int =num_attention_heads __UpperCamelCase : Optional[Any] =dropout __UpperCamelCase : int =dim_feedforward __UpperCamelCase : Any =pre_norm __UpperCamelCase : Union[str, Any] =enforce_input_projection __UpperCamelCase : str =common_stride __UpperCamelCase : List[str] =ignore_value __UpperCamelCase : Optional[int] =num_queries __UpperCamelCase : Any =no_object_weight __UpperCamelCase : int =class_weight __UpperCamelCase : str =mask_weight __UpperCamelCase : Dict =dice_weight __UpperCamelCase : str =train_num_points __UpperCamelCase : str =oversample_ratio __UpperCamelCase : int =importance_sample_ratio __UpperCamelCase : List[str] =init_std __UpperCamelCase : Union[str, Any] =init_xavier_std __UpperCamelCase : Any =use_auxiliary_loss __UpperCamelCase : Tuple =feature_strides __UpperCamelCase : Dict =output_auxiliary_logits __UpperCamelCase : Union[str, Any] =decoder_layers super().__init__(**lowerCamelCase__ ) @classmethod def __lowercase ( cls , lowerCamelCase__ , **lowerCamelCase__ ): """simple docstring""" return cls( backbone_config=lowerCamelCase__ , **lowerCamelCase__ , ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Any =copy.deepcopy(self.__dict__ ) __UpperCamelCase : List[Any] =self.backbone_config.to_dict() __UpperCamelCase : Union[str, Any] =self.__class__.model_type return output
245
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class _lowerCamelCase ( metaclass=a_ ): _lowerCamelCase :str = ["note_seq"] def __init__( self : Optional[Any] , *UpperCamelCase : List[Any] , **UpperCamelCase : List[str] ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""note_seq"""] ) @classmethod def _lowerCAmelCase ( cls : Optional[Any] , *UpperCamelCase : str , **UpperCamelCase : str ) -> str: """simple docstring""" requires_backends(cls , ["""note_seq"""] ) @classmethod def _lowerCAmelCase ( cls : int , *UpperCamelCase : Optional[Any] , **UpperCamelCase : List[str] ) -> int: """simple docstring""" requires_backends(cls , ["""note_seq"""] )
242
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { """facebook/levit-128S""": """https://huggingface.co/facebook/levit-128S/resolve/main/config.json""", # See all LeViT models at https://huggingface.co/models?filter=levit } class _lowerCamelCase ( a_ ): _lowerCamelCase :Optional[Any] = "levit" def __init__( self : List[Any] , UpperCamelCase : List[str]=2_24 , UpperCamelCase : Any=3 , UpperCamelCase : Optional[Any]=3 , UpperCamelCase : Union[str, Any]=2 , UpperCamelCase : Any=1 , UpperCamelCase : int=16 , UpperCamelCase : List[str]=[1_28, 2_56, 3_84] , UpperCamelCase : Optional[Any]=[4, 8, 12] , UpperCamelCase : Optional[int]=[4, 4, 4] , UpperCamelCase : str=[16, 16, 16] , UpperCamelCase : Tuple=0 , UpperCamelCase : List[str]=[2, 2, 2] , UpperCamelCase : Optional[int]=[2, 2, 2] , UpperCamelCase : Optional[int]=0.02 , **UpperCamelCase : Dict , ) -> Optional[Any]: """simple docstring""" super().__init__(**UpperCamelCase ) lowerCAmelCase__ : int = image_size lowerCAmelCase__ : Any = num_channels lowerCAmelCase__ : int = kernel_size lowerCAmelCase__ : Any = stride lowerCAmelCase__ : List[str] = padding lowerCAmelCase__ : Tuple = hidden_sizes lowerCAmelCase__ : str = num_attention_heads lowerCAmelCase__ : List[Any] = depths lowerCAmelCase__ : List[str] = key_dim lowerCAmelCase__ : List[str] = drop_path_rate lowerCAmelCase__ : List[Any] = patch_size lowerCAmelCase__ : Dict = attention_ratio lowerCAmelCase__ : Tuple = mlp_ratio lowerCAmelCase__ : Any = initializer_range lowerCAmelCase__ : Dict = [ ["""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], ] class _lowerCamelCase ( a_ ): _lowerCamelCase :Tuple = version.parse("1.11" ) @property def _lowerCAmelCase ( self : int ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _lowerCAmelCase ( self : List[str] ) -> float: """simple docstring""" return 1E-4
242
1
import unittest from transformers import XLMConfig, 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 ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class __magic_name__ : def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=False , _a=False , _a=False , _a=2 , _a=99 , _a=0 , _a=32 , _a=5 , _a=4 , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.0_2 , _a=2 , _a=4 , _a="last" , _a=True , _a=None , _a=0 , ) -> Union[str, Any]: lowerCAmelCase_ = parent lowerCAmelCase_ = batch_size lowerCAmelCase_ = seq_length lowerCAmelCase_ = is_training lowerCAmelCase_ = use_input_lengths lowerCAmelCase_ = use_token_type_ids lowerCAmelCase_ = use_labels lowerCAmelCase_ = gelu_activation lowerCAmelCase_ = sinusoidal_embeddings lowerCAmelCase_ = causal lowerCAmelCase_ = asm lowerCAmelCase_ = n_langs lowerCAmelCase_ = vocab_size lowerCAmelCase_ = n_special lowerCAmelCase_ = hidden_size lowerCAmelCase_ = num_hidden_layers lowerCAmelCase_ = num_attention_heads lowerCAmelCase_ = hidden_dropout_prob lowerCAmelCase_ = attention_probs_dropout_prob lowerCAmelCase_ = max_position_embeddings lowerCAmelCase_ = type_sequence_label_size lowerCAmelCase_ = initializer_range lowerCAmelCase_ = num_labels lowerCAmelCase_ = num_choices lowerCAmelCase_ = summary_type lowerCAmelCase_ = use_proj lowerCAmelCase_ = scope lowerCAmelCase_ = bos_token_id def __a ( self ) -> Dict: lowerCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase_ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase_ = None if self.use_input_lengths: lowerCAmelCase_ = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length lowerCAmelCase_ = None if self.use_token_type_ids: lowerCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) lowerCAmelCase_ = None lowerCAmelCase_ = None lowerCAmelCase_ = None if self.use_labels: lowerCAmelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase_ = ids_tensor([self.batch_size] , 2 ).float() lowerCAmelCase_ = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase_ = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def __a ( self ) -> List[str]: return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def __a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> List[str]: lowerCAmelCase_ = XLMModel(config=_a ) model.to(_a ) model.eval() lowerCAmelCase_ = model(_a , lengths=_a , langs=_a ) lowerCAmelCase_ = model(_a , langs=_a ) lowerCAmelCase_ = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> Optional[int]: lowerCAmelCase_ = XLMWithLMHeadModel(_a ) model.to(_a ) model.eval() lowerCAmelCase_ = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> List[Any]: lowerCAmelCase_ = XLMForQuestionAnsweringSimple(_a ) model.to(_a ) model.eval() lowerCAmelCase_ = model(_a ) lowerCAmelCase_ = model(_a , start_positions=_a , end_positions=_a ) lowerCAmelCase_ = outputs 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 __a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> Optional[Any]: lowerCAmelCase_ = XLMForQuestionAnswering(_a ) model.to(_a ) model.eval() lowerCAmelCase_ = model(_a ) lowerCAmelCase_ = model( _a , start_positions=_a , end_positions=_a , cls_index=_a , is_impossible=_a , p_mask=_a , ) lowerCAmelCase_ = model( _a , start_positions=_a , end_positions=_a , cls_index=_a , is_impossible=_a , ) ((lowerCAmelCase_) , ) = result_with_labels.to_tuple() lowerCAmelCase_ = model(_a , start_positions=_a , end_positions=_a ) ((lowerCAmelCase_) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def __a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> int: lowerCAmelCase_ = XLMForSequenceClassification(_a ) model.to(_a ) model.eval() lowerCAmelCase_ = model(_a ) lowerCAmelCase_ = model(_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> Any: lowerCAmelCase_ = self.num_labels lowerCAmelCase_ = XLMForTokenClassification(_a ) model.to(_a ) model.eval() lowerCAmelCase_ = model(_a , attention_mask=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __a ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) -> Tuple: lowerCAmelCase_ = self.num_choices lowerCAmelCase_ = XLMForMultipleChoice(config=_a ) model.to(_a ) model.eval() lowerCAmelCase_ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCAmelCase_ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCAmelCase_ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCAmelCase_ = model( _a , attention_mask=_a , token_type_ids=_a , labels=_a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __a ( self ) -> Dict: lowerCAmelCase_ = self.prepare_config_and_inputs() ( ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ) = config_and_inputs lowerCAmelCase_ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths} return config, inputs_dict @require_torch class __magic_name__ (__lowercase , __lowercase , __lowercase , unittest.TestCase ): lowerCamelCase__ = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) lowerCamelCase__ = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowerCamelCase__ = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def __a ( self , _a , _a , _a , _a , _a ) -> Optional[int]: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("Fast" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def __a ( self , _a , _a , _a=False ) -> str: lowerCAmelCase_ = super()._prepare_for_class(_a , _a , return_labels=_a ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": lowerCAmelCase_ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_a ) lowerCAmelCase_ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_a ) return inputs_dict def __a ( self ) -> Optional[Any]: lowerCAmelCase_ = XLMModelTester(self ) lowerCAmelCase_ = ConfigTester(self , config_class=_a , emb_dim=37 ) def __a ( self ) -> Optional[Any]: self.config_tester.run_common_tests() def __a ( self ) -> List[Any]: lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*_a ) def __a ( self ) -> Tuple: lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*_a ) def __a ( self ) -> Union[str, Any]: lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*_a ) def __a ( self ) -> Union[str, Any]: lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*_a ) def __a ( self ) -> Optional[int]: lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*_a ) def __a ( self ) -> Optional[Any]: lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*_a ) def __a ( self ) -> List[Any]: lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*_a ) def __a ( self , _a , _a , _a , _a , _a , _a=False , _a=1 ) -> List[str]: self.assertIsInstance(_a , _a ) self.assertListEqual( [isinstance(_a , _a ) for iter_attentions in attentions] , [True] * len(_a ) ) self.assertEqual(len(_a ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(_a ): # adds PAD dummy token lowerCAmelCase_ = min_length + idx + 1 lowerCAmelCase_ = min_length + idx + 1 lowerCAmelCase_ = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(_a ) ) def __a ( self , _a , _a , _a , _a , _a , _a=False , _a=1 ) -> str: self.assertIsInstance(_a , _a ) self.assertListEqual( [isinstance(_a , _a ) for iter_hidden_states in hidden_states] , [True] * len(_a ) , ) self.assertEqual(len(_a ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(_a ): # adds PAD dummy token lowerCAmelCase_ = min_length + idx + 1 lowerCAmelCase_ = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(_a ) , ) pass @slow def __a ( self ) -> Dict: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase_ = XLMModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_torch class __magic_name__ (unittest.TestCase ): @slow def __a ( self ) -> List[str]: lowerCAmelCase_ = XLMWithLMHeadModel.from_pretrained("xlm-mlm-en-2048" ) model.to(_a ) lowerCAmelCase_ = torch.tensor([[14, 447]] , dtype=torch.long , device=_a ) # the president lowerCAmelCase_ = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference lowerCAmelCase_ = model.generate(_a , do_sample=_a ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , _a )
22
import math from collections.abc import Iterator from itertools import takewhile def A(__a: int ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__a ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def A(): lowerCAmelCase_ = 2 while True: if is_prime(__a ): yield num num += 1 def A(__a: int = 200_0000 ): return sum(takewhile(lambda __a : x < n , prime_generator() ) ) if __name__ == "__main__": print(F'''{solution() = }''')
22
1
'''simple docstring''' import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) def lowerCAmelCase (__A , __A): """simple docstring""" _a = RobertaPreLayerNormConfig.from_pretrained( __A , architectures=['''RobertaPreLayerNormForMaskedLM''']) # convert state_dict _a = torch.load(hf_hub_download(repo_id=__A , filename='''pytorch_model.bin''')) _a = {} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith('''roberta.'''): _a = '''roberta_prelayernorm.''' + tensor_key[len('''roberta.''') :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith('''.self.LayerNorm.weight''') or tensor_key.endswith('''.self.LayerNorm.bias'''): continue _a = tensor_value _a = RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=__A , config=__A , state_dict=__A) model.save_pretrained(__A) # convert tokenizer _a = AutoTokenizer.from_pretrained(__A) tokenizer.save_pretrained(__A) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint-repo", default=None, type=str, required=True, help="Path the official PyTorch dump, e.g. 'andreasmadsen/efficient_mlm_m0.40'.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) lowercase_ = parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
211
'''simple docstring''' import random def lowerCAmelCase (__A): """simple docstring""" _a = num - 1 _a = 0 while s % 2 == 0: _a = s // 2 t += 1 for _ in range(5): _a = random.randrange(2 , num - 1) _a = pow(__A , __A , __A) if v != 1: _a = 0 while v != (num - 1): if i == t - 1: return False else: _a = i + 1 _a = (v**2) % num return True def lowerCAmelCase (__A): """simple docstring""" if num < 2: return False _a = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(__A) def lowerCAmelCase (__A = 1_024): """simple docstring""" while True: _a = random.randrange(2 ** (keysize - 1) , 2 ** (keysize)) if is_prime_low_num(__A): return num if __name__ == "__main__": lowercase_ = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
211
1
'''simple docstring''' import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel lowercase__ : Dict = { 'text_branch': 'text_model', 'audio_branch': 'audio_model.audio_encoder', 'attn': 'attention.self', 'self.proj': 'output.dense', 'attention.self_mask': 'attn_mask', 'mlp.fc1': 'intermediate.dense', 'mlp.fc2': 'output.dense', 'norm1': 'layernorm_before', 'norm2': 'layernorm_after', 'bn0': 'batch_norm', } lowercase__ : Optional[Any] = AutoFeatureExtractor.from_pretrained('laion/clap-htsat-unfused', truncation='rand_trunc') def a__ ( lowercase : List[str], lowercase : Any=False ) -> Tuple: """simple docstring""" _UpperCamelCase , _UpperCamelCase = create_model( '''HTSAT-tiny''', '''roberta''', lowercase, precision='''fp32''', device='''cuda:0''' if torch.cuda.is_available() else '''cpu''', enable_fusion=lowercase, fusion_type='''aff_2d''' if enable_fusion else None, ) return model, model_cfg def a__ ( lowercase : Tuple ) -> Tuple: """simple docstring""" _UpperCamelCase = {} _UpperCamelCase = r'''.*sequential.(\d+).*''' _UpperCamelCase = r'''.*_projection.(\d+).*''' for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: _UpperCamelCase = key.replace(lowercase, lowercase ) if re.match(lowercase, lowercase ): # replace sequential layers with list _UpperCamelCase = re.match(lowercase, lowercase ).group(1 ) _UpperCamelCase = key.replace(F"""sequential.{sequential_layer}.""", F"""layers.{int(lowercase )//3}.linear.""" ) elif re.match(lowercase, lowercase ): _UpperCamelCase = int(re.match(lowercase, lowercase ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... _UpperCamelCase = 1 if projecton_layer == 0 else 2 _UpperCamelCase = key.replace(F"""_projection.{projecton_layer}.""", F"""_projection.linear{transformers_projection_layer}.""" ) if "audio" and "qkv" in key: # split qkv into query key and value _UpperCamelCase = value _UpperCamelCase = mixed_qkv.size(0 ) // 3 _UpperCamelCase = mixed_qkv[:qkv_dim] _UpperCamelCase = mixed_qkv[qkv_dim : qkv_dim * 2] _UpperCamelCase = mixed_qkv[qkv_dim * 2 :] _UpperCamelCase = query_layer _UpperCamelCase = key_layer _UpperCamelCase = value_layer else: _UpperCamelCase = value return model_state_dict def a__ ( lowercase : int, lowercase : Dict, lowercase : Any, lowercase : Union[str, Any]=False ) -> Optional[Any]: """simple docstring""" _UpperCamelCase , _UpperCamelCase = init_clap(lowercase, enable_fusion=lowercase ) clap_model.eval() _UpperCamelCase = clap_model.state_dict() _UpperCamelCase = rename_state_dict(lowercase ) _UpperCamelCase = ClapConfig() _UpperCamelCase = enable_fusion _UpperCamelCase = ClapModel(lowercase ) # ignore the spectrogram embedding layer model.load_state_dict(lowercase, strict=lowercase ) model.save_pretrained(lowercase ) transformers_config.save_pretrained(lowercase ) if __name__ == "__main__": lowercase__ : List[Any] = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument('--enable_fusion', action='store_true', help='Whether to enable fusion or not') lowercase__ : int = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
287
'''simple docstring''' from cva import destroyAllWindows, imread, imshow, waitKey def a__ ( lowercase : str ) -> Optional[int]: """simple docstring""" _UpperCamelCase , _UpperCamelCase = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(lowercase ): for j in range(lowercase ): _UpperCamelCase = [255, 255, 255] - img[i][j] return img if __name__ == "__main__": # read original image lowercase__ : Optional[int] = imread('image_data/lena.jpg', 1) # convert to its negative lowercase__ : Union[str, Any] = convert_to_negative(img) # show result image imshow('negative of original image', img) waitKey(0) destroyAllWindows()
287
1
def UpperCAmelCase__ ( _A : list ): '''simple docstring''' if len(_A ) <= 1: return lst a__ =1 while i < len(_A ): if lst[i - 1] <= lst[i]: i += 1 else: a__, a__ =lst[i], lst[i - 1] i -= 1 if i == 0: a__ =1 return lst if __name__ == "__main__": lowerCamelCase = input('''Enter numbers separated by a comma:\n''').strip() lowerCamelCase = [int(item) for item in user_input.split(''',''')] print(gnome_sort(unsorted))
188
from __future__ import annotations def UpperCAmelCase__ ( _A : float , _A : float , _A : float , ): '''simple docstring''' if (stress, tangential_force, area).count(0 ) != 1: raise ValueError('''You cannot supply more or less than 2 values''' ) elif stress < 0: raise ValueError('''Stress cannot be negative''' ) elif tangential_force < 0: raise ValueError('''Tangential Force cannot be negative''' ) elif area < 0: raise ValueError('''Area cannot be negative''' ) elif stress == 0: return ( "stress", tangential_force / area, ) elif tangential_force == 0: return ( "tangential_force", stress * area, ) else: return ( "area", tangential_force / stress, ) if __name__ == "__main__": import doctest doctest.testmod()
188
1
import inspect import unittest from transformers import RegNetConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import RegNetForImageClassification, RegNetModel from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __UpperCAmelCase : def __init__( self: Tuple , UpperCAmelCase_: Optional[int] , UpperCAmelCase_: Union[str, Any]=3 , UpperCAmelCase_: Optional[int]=32 , UpperCAmelCase_: Tuple=3 , UpperCAmelCase_: int=10 , UpperCAmelCase_: int=[10, 20, 30, 40] , UpperCAmelCase_: Union[str, Any]=[1, 1, 2, 1] , UpperCAmelCase_: Dict=True , UpperCAmelCase_: Dict=True , UpperCAmelCase_: Optional[Any]="relu" , UpperCAmelCase_: int=3 , UpperCAmelCase_: List[str]=None , ): '''simple docstring''' _SCREAMING_SNAKE_CASE = parent _SCREAMING_SNAKE_CASE = batch_size _SCREAMING_SNAKE_CASE = image_size _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = embeddings_size _SCREAMING_SNAKE_CASE = hidden_sizes _SCREAMING_SNAKE_CASE = depths _SCREAMING_SNAKE_CASE = is_training _SCREAMING_SNAKE_CASE = use_labels _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = num_labels _SCREAMING_SNAKE_CASE = scope _SCREAMING_SNAKE_CASE = len(UpperCAmelCase_ ) def UpperCamelCase ( self: Dict ): '''simple docstring''' _SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _SCREAMING_SNAKE_CASE = None if self.use_labels: _SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels ) _SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def UpperCamelCase ( self: List[str] ): '''simple docstring''' return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def UpperCamelCase ( self: int , UpperCAmelCase_: int , UpperCAmelCase_: Optional[Any] , UpperCAmelCase_: Any ): '''simple docstring''' _SCREAMING_SNAKE_CASE = RegNetModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def UpperCamelCase ( self: int , UpperCAmelCase_: List[Any] , UpperCAmelCase_: Any , UpperCAmelCase_: str ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.num_labels _SCREAMING_SNAKE_CASE = RegNetForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase ( self: Tuple ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = config_and_inputs _SCREAMING_SNAKE_CASE = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __UpperCAmelCase (_UpperCAmelCase ,_UpperCAmelCase ,unittest.TestCase ): __snake_case : Dict =(RegNetModel, RegNetForImageClassification) if is_torch_available() else () __snake_case : Tuple =( {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification} if is_torch_available() else {} ) __snake_case : Optional[int] =False __snake_case : Optional[int] =False __snake_case : int =False __snake_case : Optional[Any] =False def UpperCamelCase ( self: Any ): '''simple docstring''' _SCREAMING_SNAKE_CASE = RegNetModelTester(self ) _SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ ) def UpperCamelCase ( self: Union[str, Any] ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCamelCase ( self: Optional[int] ): '''simple docstring''' return @unittest.skip(reason="""RegNet does not use inputs_embeds""" ) def UpperCamelCase ( self: Tuple ): '''simple docstring''' pass @unittest.skip(reason="""RegNet does not support input and output embeddings""" ) def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' pass def UpperCamelCase ( self: 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_ ) _SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] _SCREAMING_SNAKE_CASE = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def UpperCamelCase ( self: List[str] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def UpperCamelCase ( self: Optional[int] ): '''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(config=UpperCAmelCase_ ) for name, module in model.named_modules(): if isinstance(UpperCAmelCase_ , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=F'Parameter {name} of model {model_class} seems not properly initialized' , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=F'Parameter {name} of model {model_class} seems not properly initialized' , ) def UpperCamelCase ( self: Optional[int] ): '''simple docstring''' def check_hidden_states_output(UpperCAmelCase_: Optional[int] , UpperCAmelCase_: int , UpperCAmelCase_: Union[str, Any] ): _SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) _SCREAMING_SNAKE_CASE = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _SCREAMING_SNAKE_CASE = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE = ["""basic""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: _SCREAMING_SNAKE_CASE = layer_type _SCREAMING_SNAKE_CASE = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _SCREAMING_SNAKE_CASE = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def UpperCamelCase ( self: List[Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) @slow def UpperCamelCase ( self: int ): '''simple docstring''' for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE = RegNetModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def __lowerCamelCase ( ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __UpperCAmelCase (unittest.TestCase ): @cached_property def UpperCamelCase ( self: Tuple ): '''simple docstring''' return ( AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCamelCase ( self: int ): '''simple docstring''' _SCREAMING_SNAKE_CASE = RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = self.default_image_processor _SCREAMING_SNAKE_CASE = prepare_img() _SCREAMING_SNAKE_CASE = image_processor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE = model(**UpperCAmelCase_ ) # verify the logits _SCREAMING_SNAKE_CASE = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = torch.tensor([-0.41_80, -1.50_51, -3.48_36] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) )
367
UpperCamelCase = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} UpperCamelCase = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = [] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(snake_case__ ,snake_case__ ,snake_case__ ) order.append(snake_case__ ) return order def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = [vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(snake_case__ ,snake_case__ ,snake_case__ ) return component def __lowerCamelCase ( snake_case__ ) -> list[list[int]]: """simple docstring""" _SCREAMING_SNAKE_CASE = len(snake_case__ ) * [False] _SCREAMING_SNAKE_CASE = {vert: [] for vert in range(len(snake_case__ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(snake_case__ ) _SCREAMING_SNAKE_CASE = [] for i, was_visited in enumerate(snake_case__ ): if not was_visited: order += topology_sort(snake_case__ ,snake_case__ ,snake_case__ ) _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = len(snake_case__ ) * [False] for i in range(len(snake_case__ ) ): _SCREAMING_SNAKE_CASE = order[len(snake_case__ ) - i - 1] if not visited[vert]: _SCREAMING_SNAKE_CASE = find_components(snake_case__ ,snake_case__ ,snake_case__ ) components_list.append(snake_case__ ) return components_list
125
0
"""simple docstring""" from typing import Any def _snake_case ( lowercase__ ): if not input_list: return [] _lowerCamelCase : Dict = [input_list.count(__lowercase ) for value in input_list] _lowerCamelCase : int = max(__lowercase ) # Gets the maximum count in the input list. # Gets values of modes return sorted({input_list[i] for i, value in enumerate(__lowercase ) if value == y} ) if __name__ == "__main__": import doctest doctest.testmod()
96
import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' @slow def A ( self : int ): '''simple docstring''' _snake_case = FlaxXLMRobertaModel.from_pretrained('xlm-roberta-base' ) _snake_case = AutoTokenizer.from_pretrained('xlm-roberta-base' ) _snake_case = 'The dog is cute and lives in the garden house' _snake_case = jnp.array([tokenizer.encode(lowercase )] ) _snake_case = (1, 12, 768) # batch_size, sequence_length, embedding_vector_dim _snake_case = jnp.array( [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] ) _snake_case = model(lowercase )['last_hidden_state'] self.assertEqual(output.shape , lowercase ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] , lowercase , atol=1E-3 ) )
282
0
'''simple docstring''' def UpperCAmelCase ( a_ , a_ = " " ) -> list: """simple docstring""" A_ : List[str] = [] A_ : List[str] = 0 for index, char in enumerate(__lowerCAmelCase ): if char == separator: split_words.append(string[last_index:index] ) A_ : Union[str, Any] = index + 1 elif index + 1 == len(__lowerCAmelCase ): split_words.append(string[last_index : index + 1] ) return split_words if __name__ == "__main__": from doctest import testmod testmod()
362
'''simple docstring''' UpperCamelCase__ : int = {str(digit): digit**5 for digit in range(10)} def UpperCAmelCase ( a_ ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(a_ ) ) def UpperCAmelCase ( ) -> int: """simple docstring""" return sum( number for number in range(1_0_0_0 , 1_0_0_0_0_0_0 ) if number == digits_fifth_powers_sum(a_ ) ) if __name__ == "__main__": print(solution())
164
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = {'''vocab_file''': '''spiece.model'''} __lowerCAmelCase = { '''vocab_file''': { '''bert_for_seq_generation''': ( '''https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model''' ), } } __lowerCAmelCase = {'''bert_for_seq_generation''': 512} class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : Optional[int] = VOCAB_FILES_NAMES lowerCAmelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase : List[int] = [] lowerCAmelCase : Optional[Any] = ['input_ids', 'attention_mask'] def __init__( self : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Optional[int]="<s>" ,_UpperCAmelCase : Optional[Any]="</s>" ,_UpperCAmelCase : Optional[Any]="<unk>" ,_UpperCAmelCase : Dict="<pad>" ,_UpperCAmelCase : str="<::::>" ,_UpperCAmelCase : Optional[Dict[str, Any]] = None ,**_UpperCAmelCase : Any ,): _a : int = {} if sp_model_kwargs is None else sp_model_kwargs # Add extra_ids to the special token list super().__init__( bos_token=_UpperCAmelCase ,eos_token=_UpperCAmelCase ,unk_token=_UpperCAmelCase ,pad_token=_UpperCAmelCase ,sep_token=_UpperCAmelCase ,sp_model_kwargs=self.sp_model_kwargs ,**_UpperCAmelCase ,) _a : Dict = vocab_file _a : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_UpperCAmelCase ) @property def __lowercase ( self : Tuple ): return self.sp_model.get_piece_size() def __lowercase ( self : str ): _a : List[Any] = {self.convert_ids_to_tokens(_UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ): _a : Tuple = self.__dict__.copy() _a : str = None return state def __setstate__( self : Optional[Any] ,_UpperCAmelCase : Optional[int] ): _a : Optional[int] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): _a : Dict = {} _a : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowercase ( self : Any ,_UpperCAmelCase : str ): return self.sp_model.encode(_UpperCAmelCase ,out_type=_UpperCAmelCase ) def __lowercase ( self : Optional[int] ,_UpperCAmelCase : Tuple ): return self.sp_model.piece_to_id(_UpperCAmelCase ) def __lowercase ( self : Optional[int] ,_UpperCAmelCase : str ): _a : Union[str, Any] = self.sp_model.IdToPiece(_UpperCAmelCase ) return token def __lowercase ( self : str ,_UpperCAmelCase : Tuple ): _a : Any = [] _a : Any = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(_UpperCAmelCase ) + token _a : Any = [] else: current_sub_tokens.append(_UpperCAmelCase ) out_string += self.sp_model.decode(_UpperCAmelCase ) return out_string.strip() def __lowercase ( self : Any ,_UpperCAmelCase : str ,_UpperCAmelCase : Optional[str] = None ): if not os.path.isdir(_UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _a : List[Any] = os.path.join( _UpperCAmelCase ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,_UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(_UpperCAmelCase ,'wb' ) as fi: _a : Tuple = self.sp_model.serialized_model_proto() fi.write(_UpperCAmelCase ) return (out_vocab_file,)
89
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) a_ = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """encoder.layer_norm_for_extract""": """layer_norm_for_extract""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """label_embs_concat""": """label_embeddings_concat""", """mask_emb""": """masked_spec_embed""", """spk_proj""": """speaker_proj""", } a_ = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", """label_embeddings_concat""", """speaker_proj""", """layer_norm_for_extract""", ] def a__ ( _UpperCamelCase : str ,_UpperCamelCase : Tuple ,_UpperCamelCase : Optional[Any] ,_UpperCamelCase : Optional[Any] ,_UpperCamelCase : Dict ): for attribute in key.split('''.''' ): __lowerCamelCase = getattr(_UpperCamelCase ,_UpperCamelCase ) if weight_type is not None: __lowerCamelCase = getattr(_UpperCamelCase ,_UpperCamelCase ).shape else: __lowerCamelCase = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __lowerCamelCase = value elif weight_type == "weight_g": __lowerCamelCase = value elif weight_type == "weight_v": __lowerCamelCase = value elif weight_type == "bias": __lowerCamelCase = value else: __lowerCamelCase = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def a__ ( _UpperCamelCase : Any ,_UpperCamelCase : Any ): __lowerCamelCase = [] __lowerCamelCase = fairseq_model.state_dict() __lowerCamelCase = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): __lowerCamelCase = False if "conv_layers" in name: load_conv_layer( _UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,hf_model.config.feat_extract_norm == '''group''' ,) __lowerCamelCase = True else: for key, mapped_key in MAPPING.items(): __lowerCamelCase = '''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: if "layer_norm_for_extract" in name and (".".join(name.split('''.''' )[:-1] ) != key): # special case since naming is very similar continue __lowerCamelCase = True if "*" in mapped_key: __lowerCamelCase = name.split(_UpperCamelCase )[0].split('''.''' )[-2] __lowerCamelCase = mapped_key.replace('''*''' ,_UpperCamelCase ) if "weight_g" in name: __lowerCamelCase = '''weight_g''' elif "weight_v" in name: __lowerCamelCase = '''weight_v''' elif "bias" in name: __lowerCamelCase = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowerCamelCase = '''weight''' else: __lowerCamelCase = None set_recursively(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) continue if not is_used: unused_weights.append(_UpperCamelCase ) logger.warning(F"""Unused weights: {unused_weights}""" ) def a__ ( _UpperCamelCase : Union[str, Any] ,_UpperCamelCase : Union[str, Any] ,_UpperCamelCase : Dict ,_UpperCamelCase : Union[str, Any] ,_UpperCamelCase : Union[str, Any] ): __lowerCamelCase = full_name.split('''conv_layers.''' )[-1] __lowerCamelCase = name.split('''.''' ) __lowerCamelCase = int(items[0] ) __lowerCamelCase = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __lowerCamelCase = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __lowerCamelCase = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""" ) __lowerCamelCase = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) __lowerCamelCase = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_UpperCamelCase ) @torch.no_grad() def a__ ( _UpperCamelCase : List[Any] ,_UpperCamelCase : List[str] ,_UpperCamelCase : Tuple=None ,_UpperCamelCase : Tuple=None ,_UpperCamelCase : List[Any]=True ): if config_path is not None: __lowerCamelCase = UniSpeechSatConfig.from_pretrained(_UpperCamelCase ) else: __lowerCamelCase = UniSpeechSatConfig() __lowerCamelCase = '''''' if is_finetuned: __lowerCamelCase = UniSpeechSatForCTC(_UpperCamelCase ) else: __lowerCamelCase = UniSpeechSatForPreTraining(_UpperCamelCase ) __lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) __lowerCamelCase = model[0].eval() recursively_load_weights(_UpperCamelCase ,_UpperCamelCase ) hf_wavavec.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) a_ = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
330
0
"""simple docstring""" import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class _lowerCAmelCase ( lowercase ,lowercase ,unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = IFImgaImgSuperResolutionPipeline __UpperCAmelCase : str = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"width", "height"} __UpperCAmelCase : int = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"original_image"} ) __UpperCAmelCase : Optional[Any] = PipelineTesterMixin.required_optional_params - {"latents"} def _lowercase ( self : Tuple ): return self._get_superresolution_dummy_components() def _lowercase ( self : Optional[Any], UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : List[Any]=0 ): if str(UpperCAmelCase__ ).startswith("mps" ): __lowercase = torch.manual_seed(UpperCAmelCase__ ) else: __lowercase = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) __lowercase = floats_tensor((1, 3, 3_2, 3_2), rng=random.Random(UpperCAmelCase__ ) ).to(UpperCAmelCase__ ) __lowercase = floats_tensor((1, 3, 1_6, 1_6), rng=random.Random(UpperCAmelCase__ ) ).to(UpperCAmelCase__ ) __lowercase = { "prompt": "A painting of a squirrel eating a burger", "image": image, "original_image": original_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available(), reason="XFormers attention is only available with CUDA and `xformers` installed", ) def _lowercase ( self : Optional[Any] ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def _lowercase ( self : Union[str, Any] ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda", reason="float16 requires CUDA" ) def _lowercase ( self : List[str] ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1E-1 ) def _lowercase ( self : List[str] ): self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def _lowercase ( self : Optional[int] ): self._test_save_load_local() def _lowercase ( self : Union[str, Any] ): self._test_inference_batch_single_identical( expected_max_diff=1E-2, )
357
"""simple docstring""" import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration _a = pytest.mark.integration _a = {'comet'} _a = importlib.util.find_spec('fairseq') is not None _a = {'code_eval'} _a = os.name == 'nt' _a = {'bertscore', 'frugalscore', 'perplexity'} _a = importlib.util.find_spec('transformers') is not None def _A ( UpperCamelCase_ : Dict) -> Any: '''simple docstring''' @wraps(UpperCamelCase_) def wrapper(self : Dict, UpperCamelCase_ : Dict): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("\"test requires Fairseq\"") else: test_case(self, UpperCamelCase_) return wrapper def _A ( UpperCamelCase_ : Dict) -> int: '''simple docstring''' @wraps(UpperCamelCase_) def wrapper(self : int, UpperCamelCase_ : str): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("\"test requires transformers\"") else: test_case(self, UpperCamelCase_) return wrapper def _A ( UpperCamelCase_ : Tuple) -> str: '''simple docstring''' @wraps(UpperCamelCase_) def wrapper(self : Optional[int], UpperCamelCase_ : Optional[Any]): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("\"test not supported on Windows\"") else: test_case(self, UpperCamelCase_) return wrapper def _A ( ) -> str: '''simple docstring''' __lowercase = [metric_dir.split(os.sep)[-2] for metric_dir in glob.glob("./metrics/*/")] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( lowercase ,lowercase ,lowercase ) @local class _lowerCAmelCase ( parameterized.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[int] = {} __UpperCAmelCase : Tuple = None @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" ) @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning" ) def _lowercase ( self : Dict, UpperCAmelCase__ : int ): __lowercase = "[...]" __lowercase = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics", UpperCAmelCase__ ) ).module_path ) __lowercase = datasets.load.import_main_class(metric_module.__name__, dataset=UpperCAmelCase__ ) # check parameters __lowercase = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(UpperCAmelCase__, metric_module.__name__ ): with self.use_local_metrics(): try: __lowercase = doctest.testmod(UpperCAmelCase__, verbose=UpperCAmelCase__, raise_on_error=UpperCAmelCase__ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed, 0 ) self.assertGreater(results.attempted, 1 ) @slow def _lowercase ( self : List[Any], UpperCAmelCase__ : Optional[Any] ): __lowercase = "[...]" __lowercase = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics", UpperCAmelCase__ ) ).module_path ) # run doctest with self.use_local_metrics(): __lowercase = doctest.testmod(UpperCAmelCase__, verbose=UpperCAmelCase__, raise_on_error=UpperCAmelCase__ ) self.assertEqual(results.failed, 0 ) self.assertGreater(results.attempted, 1 ) @contextmanager def _lowercase ( self : List[Any], UpperCAmelCase__ : Any, UpperCAmelCase__ : Tuple ): if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](UpperCAmelCase__ ): yield else: yield @contextmanager def _lowercase ( self : List[Any] ): def load_local_metric(UpperCAmelCase__ : Any, *UpperCAmelCase__ : List[Any], **UpperCAmelCase__ : Any ): return load_metric(os.path.join("metrics", UpperCAmelCase__ ), *UpperCAmelCase__, **UpperCAmelCase__ ) with patch("datasets.load_metric" ) as mock_load_metric: __lowercase = load_local_metric yield @classmethod def _lowercase ( cls : Optional[Any], UpperCAmelCase__ : List[Any] ): def wrapper(UpperCAmelCase__ : Tuple ): __lowercase = contextmanager(UpperCAmelCase__ ) __lowercase = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("bleurt") def _A ( UpperCamelCase_ : Any) -> Optional[Any]: '''simple docstring''' import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("sv", "", "") # handle pytest cli flags class _lowerCAmelCase ( lowercase ): """simple docstring""" def _lowercase ( self : Tuple, UpperCAmelCase__ : Tuple ): assert len(input_dict["input_ids"] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("bleurt.score._create_predictor") as mock_create_predictor: __lowercase = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("bertscore") def _A ( UpperCamelCase_ : Tuple) -> int: '''simple docstring''' import torch def bert_cos_score_idf(UpperCamelCase_ : Tuple, UpperCamelCase_ : str, *UpperCamelCase_ : Optional[Any], **UpperCamelCase_ : Dict): return torch.tensor([[1.0, 1.0, 1.0]] * len(UpperCamelCase_)) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("bert_score.scorer.get_model"), patch( "bert_score.scorer.bert_cos_score_idf") as mock_bert_cos_score_idf: __lowercase = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("comet") def _A ( UpperCamelCase_ : Tuple) -> List[Any]: '''simple docstring''' def load_from_checkpoint(UpperCamelCase_ : Tuple): class _lowerCAmelCase : """simple docstring""" def _lowercase ( self : str, UpperCAmelCase__ : int, *UpperCAmelCase__ : Dict, **UpperCAmelCase__ : Dict ): assert len(UpperCAmelCase__ ) == 2 __lowercase = [0.19, 0.92] return scores, sum(UpperCAmelCase__ ) / len(UpperCAmelCase__ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("comet.download_model") as mock_download_model: __lowercase = None with patch("comet.load_from_checkpoint") as mock_load_from_checkpoint: __lowercase = load_from_checkpoint yield def _A ( ) -> Tuple: '''simple docstring''' __lowercase = load_metric(os.path.join("metrics", "seqeval")) __lowercase = "ERROR" __lowercase = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(UpperCamelCase_, match=re.escape(UpperCamelCase_)): metric.compute(predictions=[], references=[], scheme=UpperCamelCase_)
144
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase = logging.get_logger(__name__) __lowercase = { '''facebook/wav2vec2-base-960h''': '''https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json''', # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2 } class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' a__ : Union[str, Any] = """wav2vec2""" def __init__( self , __lowercase=32 , __lowercase=768 , __lowercase=12 , __lowercase=12 , __lowercase=3_072 , __lowercase="gelu" , __lowercase=0.1 , __lowercase=0.1 , __lowercase=0.1 , __lowercase=0.0 , __lowercase=0.0 , __lowercase=0.1 , __lowercase=0.1 , __lowercase=0.02 , __lowercase=1E-5 , __lowercase="group" , __lowercase="gelu" , __lowercase=(512, 512, 512, 512, 512, 512, 512) , __lowercase=(5, 2, 2, 2, 2, 2, 2) , __lowercase=(10, 3, 3, 3, 3, 2, 2) , __lowercase=False , __lowercase=128 , __lowercase=16 , __lowercase=False , __lowercase=True , __lowercase=0.05 , __lowercase=10 , __lowercase=2 , __lowercase=0.0 , __lowercase=10 , __lowercase=0 , __lowercase=320 , __lowercase=2 , __lowercase=0.1 , __lowercase=100 , __lowercase=256 , __lowercase=256 , __lowercase=0.1 , __lowercase="sum" , __lowercase=False , __lowercase=False , __lowercase=256 , __lowercase=(512, 512, 512, 512, 1_500) , __lowercase=(5, 3, 3, 1, 1) , __lowercase=(1, 2, 3, 1, 1) , __lowercase=512 , __lowercase=0 , __lowercase=1 , __lowercase=2 , __lowercase=False , __lowercase=3 , __lowercase=2 , __lowercase=3 , __lowercase=None , __lowercase=None , **__lowercase , ) -> int: super().__init__(**__lowercase , pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase) __UpperCamelCase :Any = hidden_size __UpperCamelCase :int = feat_extract_norm __UpperCamelCase :Tuple = feat_extract_activation __UpperCamelCase :Union[str, Any] = list(__lowercase) __UpperCamelCase :List[Any] = list(__lowercase) __UpperCamelCase :int = list(__lowercase) __UpperCamelCase :List[Any] = conv_bias __UpperCamelCase :Optional[int] = num_conv_pos_embeddings __UpperCamelCase :Dict = num_conv_pos_embedding_groups __UpperCamelCase :Any = len(self.conv_dim) __UpperCamelCase :List[str] = num_hidden_layers __UpperCamelCase :int = intermediate_size __UpperCamelCase :str = hidden_act __UpperCamelCase :Any = num_attention_heads __UpperCamelCase :int = hidden_dropout __UpperCamelCase :Tuple = attention_dropout __UpperCamelCase :List[str] = activation_dropout __UpperCamelCase :Optional[Any] = feat_proj_dropout __UpperCamelCase :Any = final_dropout __UpperCamelCase :Any = layerdrop __UpperCamelCase :str = layer_norm_eps __UpperCamelCase :Optional[Any] = initializer_range __UpperCamelCase :List[str] = vocab_size __UpperCamelCase :str = do_stable_layer_norm __UpperCamelCase :Union[str, Any] = use_weighted_layer_sum 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 __UpperCamelCase :List[Any] = apply_spec_augment __UpperCamelCase :Tuple = mask_time_prob __UpperCamelCase :int = mask_time_length __UpperCamelCase :Dict = mask_time_min_masks __UpperCamelCase :str = mask_feature_prob __UpperCamelCase :List[str] = mask_feature_length __UpperCamelCase :Union[str, Any] = mask_feature_min_masks # parameters for pretraining with codevector quantized representations __UpperCamelCase :Optional[Any] = num_codevectors_per_group __UpperCamelCase :List[Any] = num_codevector_groups __UpperCamelCase :Tuple = contrastive_logits_temperature __UpperCamelCase :Optional[int] = feat_quantizer_dropout __UpperCamelCase :Optional[int] = num_negatives __UpperCamelCase :List[Any] = codevector_dim __UpperCamelCase :str = proj_codevector_dim __UpperCamelCase :List[str] = diversity_loss_weight # ctc loss __UpperCamelCase :Tuple = ctc_loss_reduction __UpperCamelCase :Tuple = ctc_zero_infinity # adapter __UpperCamelCase :List[str] = add_adapter __UpperCamelCase :Tuple = adapter_kernel_size __UpperCamelCase :str = adapter_stride __UpperCamelCase :Tuple = num_adapter_layers __UpperCamelCase :Tuple = output_hidden_size or hidden_size __UpperCamelCase :Optional[Any] = adapter_attn_dim # SequenceClassification-specific parameter. Feel free to ignore for other classes. __UpperCamelCase :Optional[Any] = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __UpperCamelCase :Optional[int] = list(__lowercase) __UpperCamelCase :List[Any] = list(__lowercase) __UpperCamelCase :List[Any] = list(__lowercase) __UpperCamelCase :str = xvector_output_dim @property def UpperCamelCase__ ( self) -> List[str]: return functools.reduce(operator.mul , self.conv_stride , 1)
43
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json''' ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class lowerCAmelCase_ ( a__ ): UpperCAmelCase__ : Optional[Any] = "speech_to_text_2" UpperCAmelCase__ : List[Any] = ["past_key_values"] UpperCAmelCase__ : Any = {"num_attention_heads": "decoder_attention_heads", "hidden_size": "d_model"} def __init__( self, SCREAMING_SNAKE_CASE_=1_0000, SCREAMING_SNAKE_CASE_=6, SCREAMING_SNAKE_CASE_=2048, SCREAMING_SNAKE_CASE_=4, SCREAMING_SNAKE_CASE_=0.0, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_="relu", SCREAMING_SNAKE_CASE_=256, SCREAMING_SNAKE_CASE_=0.1, SCREAMING_SNAKE_CASE_=0.0, SCREAMING_SNAKE_CASE_=0.0, SCREAMING_SNAKE_CASE_=0.02, SCREAMING_SNAKE_CASE_=2, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=1, SCREAMING_SNAKE_CASE_=0, SCREAMING_SNAKE_CASE_=2, SCREAMING_SNAKE_CASE_=1024, **SCREAMING_SNAKE_CASE_, ) -> int: UpperCamelCase : Optional[int] = vocab_size UpperCamelCase : List[str] = d_model UpperCamelCase : List[str] = decoder_ffn_dim UpperCamelCase : Optional[Any] = decoder_layers UpperCamelCase : Any = decoder_attention_heads UpperCamelCase : Tuple = dropout UpperCamelCase : str = attention_dropout UpperCamelCase : str = activation_dropout UpperCamelCase : Union[str, Any] = activation_function UpperCamelCase : Optional[int] = init_std UpperCamelCase : Tuple = decoder_layerdrop UpperCamelCase : Dict = use_cache UpperCamelCase : Any = decoder_layers UpperCamelCase : Union[str, Any] = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase : Union[str, Any] = max_target_positions super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_, bos_token_id=SCREAMING_SNAKE_CASE_, eos_token_id=SCREAMING_SNAKE_CASE_, decoder_start_token_id=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_, )
119
0
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetrImageProcessor class UpperCamelCase_ (unittest.TestCase ): """simple docstring""" def __init__( self : int , _lowerCamelCase : Tuple , _lowerCamelCase : Any=7 , _lowerCamelCase : Optional[Any]=3 , _lowerCamelCase : Optional[Any]=30 , _lowerCamelCase : Dict=400 , _lowerCamelCase : Dict=True , _lowerCamelCase : str=None , _lowerCamelCase : List[Any]=True , _lowerCamelCase : List[str]=1 / 255 , _lowerCamelCase : Any=True , _lowerCamelCase : str=[0.5, 0.5, 0.5] , _lowerCamelCase : List[str]=[0.5, 0.5, 0.5] , _lowerCamelCase : Any=True , ): """simple docstring""" A_ : Any = size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 1333} A_ : Any = parent A_ : int = batch_size A_ : str = num_channels A_ : str = min_resolution A_ : Dict = max_resolution A_ : List[Any] = do_resize A_ : str = size A_ : str = do_rescale A_ : List[Any] = rescale_factor A_ : List[str] = do_normalize A_ : Dict = image_mean A_ : int = image_std A_ : int = do_pad def _a ( self : Optional[Any] ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def _a ( self : Optional[int] , _lowerCamelCase : Any , _lowerCamelCase : Union[str, Any]=False ): """simple docstring""" if not batched: A_ : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): A_ ,A_ : Optional[int] = image.size else: A_ ,A_ : int = image.shape[1], image.shape[2] if w < h: A_ : Optional[int] = int(self.size['''shortest_edge'''] * h / w ) A_ : Any = self.size['''shortest_edge'''] elif w > h: A_ : Dict = self.size['''shortest_edge'''] A_ : List[Any] = int(self.size['''shortest_edge'''] * w / h ) else: A_ : int = self.size['''shortest_edge'''] A_ : List[Any] = self.size['''shortest_edge'''] else: A_ : List[Any] = [] for image in image_inputs: A_ ,A_ : List[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A_ : Any = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] A_ : Any = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class UpperCamelCase_ (a__, unittest.TestCase ): """simple docstring""" _lowerCAmelCase = DetrImageProcessor if is_vision_available() else None def _a ( self : Optional[Any] ): """simple docstring""" A_ : Any = DetrImageProcessingTester(self ) @property def _a ( self : Tuple ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def _a ( self : Dict ): """simple docstring""" A_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_rescale''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''rescale_factor''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_pad''' ) ) def _a ( self : int ): """simple docstring""" A_ : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 18, '''longest_edge''': 1333} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) A_ : Any = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42, '''longest_edge''': 84} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def _a ( self : List[Any] ): """simple docstring""" pass def _a ( self : Dict ): """simple docstring""" A_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input A_ : Any = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values A_ ,A_ : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A_ ,A_ : int = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) A_ : Tuple = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _a ( self : Tuple ): """simple docstring""" A_ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A_ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input A_ : int = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values A_ ,A_ : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A_ : Optional[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values A_ ,A_ : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _a ( self : Optional[Any] ): """simple docstring""" A_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A_ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input A_ : Optional[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values A_ ,A_ : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A_ : Dict = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values A_ ,A_ : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def _a ( self : List[Any] ): """simple docstring""" A_ : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: A_ : Union[str, Any] = json.loads(f.read() ) A_ : Any = {'''image_id''': 39769, '''annotations''': target} # encode them A_ : Union[str, Any] = DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50''' ) A_ : List[str] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values A_ : Optional[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) A_ : int = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1E-4 ) ) # verify area A_ : Dict = torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes A_ : int = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) A_ : Dict = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1E-3 ) ) # verify image_id A_ : Union[str, Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd A_ : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels A_ : Tuple = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size A_ : List[Any] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size A_ : Optional[int] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def _a ( self : Any ): """simple docstring""" A_ : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: A_ : Tuple = json.loads(f.read() ) A_ : Union[str, Any] = {'''file_name''': '''000000039769.png''', '''image_id''': 39769, '''segments_info''': target} A_ : Optional[Any] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them A_ : str = DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50-panoptic''' ) A_ : Tuple = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values A_ : Dict = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) A_ : Optional[Any] = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1E-4 ) ) # verify area A_ : Dict = torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes A_ : Optional[Any] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) A_ : Any = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1E-3 ) ) # verify image_id A_ : Tuple = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd A_ : Dict = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels A_ : Union[str, Any] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks A_ : int = 822873 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size A_ : Dict = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size A_ : Any = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
4
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices snake_case__ = logging.get_logger(__name__) snake_case__ = { """microsoft/swin-tiny-patch4-window7-224""": ( """https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json""" ), # See all Swin models at https://huggingface.co/models?filter=swin } class UpperCamelCase_ (a__, a__ ): """simple docstring""" _lowerCAmelCase = 'swin' _lowerCAmelCase = { 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : Any , _lowerCamelCase : Optional[Any]=224 , _lowerCamelCase : List[str]=4 , _lowerCamelCase : Optional[Any]=3 , _lowerCamelCase : Tuple=96 , _lowerCamelCase : List[Any]=[2, 2, 6, 2] , _lowerCamelCase : List[str]=[3, 6, 12, 24] , _lowerCamelCase : List[Any]=7 , _lowerCamelCase : Optional[int]=4.0 , _lowerCamelCase : List[str]=True , _lowerCamelCase : List[str]=0.0 , _lowerCamelCase : Any=0.0 , _lowerCamelCase : Dict=0.1 , _lowerCamelCase : List[str]="gelu" , _lowerCamelCase : Tuple=False , _lowerCamelCase : Dict=0.02 , _lowerCamelCase : Optional[Any]=1E-5 , _lowerCamelCase : Any=32 , _lowerCamelCase : Tuple=None , _lowerCamelCase : Any=None , **_lowerCamelCase : str , ): """simple docstring""" super().__init__(**_lowerCamelCase ) A_ : Optional[int] = image_size A_ : Optional[int] = patch_size A_ : Optional[int] = num_channels A_ : Any = embed_dim A_ : List[Any] = depths A_ : Any = len(_lowerCamelCase ) A_ : List[Any] = num_heads A_ : Tuple = window_size A_ : Tuple = mlp_ratio A_ : Dict = qkv_bias A_ : List[str] = hidden_dropout_prob A_ : List[str] = attention_probs_dropout_prob A_ : Any = drop_path_rate A_ : List[Any] = hidden_act A_ : Tuple = use_absolute_embeddings A_ : int = layer_norm_eps A_ : Optional[Any] = initializer_range A_ : Union[str, Any] = encoder_stride # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model A_ : str = int(embed_dim * 2 ** (len(_lowerCamelCase ) - 1) ) A_ : str = ['''stem'''] + [f'stage{idx}' for idx in range(1 , len(_lowerCamelCase ) + 1 )] A_ ,A_ : Optional[Any] = get_aligned_output_features_output_indices( out_features=_lowerCamelCase , out_indices=_lowerCamelCase , stage_names=self.stage_names ) class UpperCamelCase_ (a__ ): """simple docstring""" _lowerCAmelCase = version.parse('1.11' ) @property def _a ( self : str ): """simple docstring""" return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def _a ( self : Union[str, Any] ): """simple docstring""" return 1E-4
4
1
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : Dict , _UpperCamelCase : Union[str, Any] ) -> Optional[int]: """simple docstring""" if exponent == 1: return base if exponent % 2 == 0: _SCREAMING_SNAKE_CASE =_modexpt(snake_case__ , exponent // 2 , snake_case__ ) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(snake_case__ , exponent - 1 , snake_case__ )) % modulo_value def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] = 17_77 , _UpperCamelCase : int = 18_55 , _UpperCamelCase : Any = 8 ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =base for _ in range(1 , snake_case__ ): _SCREAMING_SNAKE_CASE =_modexpt(snake_case__ , snake_case__ , 10**digits ) return result if __name__ == "__main__": print(f'''{solution() = }''')
47
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A_ : List[Any] = logging.get_logger(__name__) A_ : List[Any] = "▁" A_ : str = {"vocab_file": "sentencepiece.bpe.model"} A_ : Union[str, Any] = { "vocab_file": { "xlm-roberta-base": "https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model", "xlm-roberta-large": "https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model", "xlm-roberta-large-finetuned-conll02-dutch": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model" ), "xlm-roberta-large-finetuned-conll02-spanish": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model" ), "xlm-roberta-large-finetuned-conll03-english": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model" ), "xlm-roberta-large-finetuned-conll03-german": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model" ), } } A_ : List[str] = { "xlm-roberta-base": 512, "xlm-roberta-large": 512, "xlm-roberta-large-finetuned-conll02-dutch": 512, "xlm-roberta-large-finetuned-conll02-spanish": 512, "xlm-roberta-large-finetuned-conll03-english": 512, "xlm-roberta-large-finetuned-conll03-german": 512, } class lowerCamelCase (A__ ): lowerCamelCase__ : Optional[int] = VOCAB_FILES_NAMES lowerCamelCase__ : Any = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ : Tuple = ['input_ids', 'attention_mask'] def __init__( self : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Tuple="<s>" , __UpperCAmelCase : str="</s>" , __UpperCAmelCase : int="</s>" , __UpperCAmelCase : Tuple="<s>" , __UpperCAmelCase : Union[str, Any]="<unk>" , __UpperCAmelCase : List[str]="<pad>" , __UpperCAmelCase : Dict="<mask>" , __UpperCAmelCase : Optional[Dict[str, Any]] = None , **__UpperCAmelCase : Optional[int] , ) -> None: # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token SCREAMING_SNAKE_CASE__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCAmelCase , ) SCREAMING_SNAKE_CASE__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__UpperCAmelCase ) ) SCREAMING_SNAKE_CASE__ = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE__ = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = len(self.sp_model ) + self.fairseq_offset SCREAMING_SNAKE_CASE__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : List[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ = self.__dict__.copy() SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple , __UpperCAmelCase : Optional[int] ) -> List[str]: SCREAMING_SNAKE_CASE__ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE ( self : Dict , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] SCREAMING_SNAKE_CASE__ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self : Dict , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCAmelCase , token_ids_a=__UpperCAmelCase , already_has_special_tokens=__UpperCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(__UpperCAmelCase )) + [1] return [1] + ([0] * len(__UpperCAmelCase )) + [1, 1] + ([0] * len(__UpperCAmelCase )) + [1] def SCREAMING_SNAKE_CASE ( self : int , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: SCREAMING_SNAKE_CASE__ = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self : List[Any] , __UpperCAmelCase : str ) -> List[str]: return self.sp_model.encode(__UpperCAmelCase , out_type=__UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __UpperCAmelCase : List[str] ) -> Tuple: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE__ = self.sp_model.PieceToId(__UpperCAmelCase ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self : List[Any] , __UpperCAmelCase : int ) -> Any: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __UpperCAmelCase : List[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ = """""".join(__UpperCAmelCase ).replace(__UpperCAmelCase , """ """ ).strip() return out_string def SCREAMING_SNAKE_CASE ( self : int , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE__ = os.path.join( __UpperCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(__UpperCAmelCase , """wb""" ) as fi: SCREAMING_SNAKE_CASE__ = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase ) return (out_vocab_file,)
165
0
import argparse import torch from transformers import ( SpeechTaConfig, SpeechTaFeatureExtractor, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaProcessor, SpeechTaTokenizer, logging, ) from transformers.tokenization_utils import AddedToken logging.set_verbosity_info() _lowerCAmelCase : Tuple = logging.get_logger('''transformers.models.speecht5''') _lowerCAmelCase : int = { '''speech_encoder_prenet.layer_norm''': '''speecht5.encoder.prenet.feature_projection.layer_norm''', '''speech_encoder_prenet.post_extract_proj''': '''speecht5.encoder.prenet.feature_projection.projection''', '''speech_encoder_prenet.pos_conv.0''': '''speecht5.encoder.prenet.pos_conv_embed.conv''', '''speech_encoder_prenet.mask_emb''': '''speecht5.encoder.prenet.masked_spec_embed''', } _lowerCAmelCase : str = { '''text_encoder_prenet.encoder_prenet.0''': '''speecht5.encoder.prenet.embed_tokens''', '''text_encoder_prenet.encoder_prenet.1.alpha''': '''speecht5.encoder.prenet.encode_positions.alpha''', } _lowerCAmelCase : int = { '''speech_decoder_prenet.decoder_prenet.0.0.prenet.0.0''': '''speecht5.decoder.prenet.layers.0''', '''speech_decoder_prenet.decoder_prenet.0.0.prenet.1.0''': '''speecht5.decoder.prenet.layers.1''', '''speech_decoder_prenet.decoder_prenet.0.1''': '''speecht5.decoder.prenet.final_layer''', '''speech_decoder_prenet.decoder_prenet.1.alpha''': '''speecht5.decoder.prenet.encode_positions.alpha''', '''speech_decoder_prenet.spkembs_layer.0''': '''speecht5.decoder.prenet.speaker_embeds_layer''', } _lowerCAmelCase : Union[str, Any] = { '''speech_decoder_postnet.feat_out''': '''speech_decoder_postnet.feat_out''', '''speech_decoder_postnet.prob_out''': '''speech_decoder_postnet.prob_out''', '''speech_decoder_postnet.postnet.postnet.0.0''': '''speech_decoder_postnet.layers.0.conv''', '''speech_decoder_postnet.postnet.postnet.0.1''': '''speech_decoder_postnet.layers.0.batch_norm''', '''speech_decoder_postnet.postnet.postnet.1.0''': '''speech_decoder_postnet.layers.1.conv''', '''speech_decoder_postnet.postnet.postnet.1.1''': '''speech_decoder_postnet.layers.1.batch_norm''', '''speech_decoder_postnet.postnet.postnet.2.0''': '''speech_decoder_postnet.layers.2.conv''', '''speech_decoder_postnet.postnet.postnet.2.1''': '''speech_decoder_postnet.layers.2.batch_norm''', '''speech_decoder_postnet.postnet.postnet.3.0''': '''speech_decoder_postnet.layers.3.conv''', '''speech_decoder_postnet.postnet.postnet.3.1''': '''speech_decoder_postnet.layers.3.batch_norm''', '''speech_decoder_postnet.postnet.postnet.4.0''': '''speech_decoder_postnet.layers.4.conv''', '''speech_decoder_postnet.postnet.postnet.4.1''': '''speech_decoder_postnet.layers.4.batch_norm''', } _lowerCAmelCase : Union[str, Any] = { '''text_decoder_prenet.embed_tokens''': '''speecht5.decoder.prenet.embed_tokens''', } _lowerCAmelCase : int = { '''text_decoder_postnet.output_projection''': '''text_decoder_postnet.lm_head''', } _lowerCAmelCase : Any = { '''encoder.layers.*.self_attn.k_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.k_proj''', '''encoder.layers.*.self_attn.v_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.v_proj''', '''encoder.layers.*.self_attn.q_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.q_proj''', '''encoder.layers.*.self_attn.out_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.out_proj''', '''encoder.layers.*.self_attn_layer_norm''': '''speecht5.encoder.wrapped_encoder.layers.*.layer_norm''', '''encoder.layers.*.fc1''': '''speecht5.encoder.wrapped_encoder.layers.*.feed_forward.intermediate_dense''', '''encoder.layers.*.fc2''': '''speecht5.encoder.wrapped_encoder.layers.*.feed_forward.output_dense''', '''encoder.layers.*.final_layer_norm''': '''speecht5.encoder.wrapped_encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''speecht5.encoder.wrapped_encoder.layer_norm''', '''encoder.pos_emb.pe_k''': '''speecht5.encoder.wrapped_encoder.embed_positions.pe_k''', } _lowerCAmelCase : List[str] = { '''decoder.layers.*.self_attn.k_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.k_proj''', '''decoder.layers.*.self_attn.v_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.v_proj''', '''decoder.layers.*.self_attn.q_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.q_proj''', '''decoder.layers.*.self_attn.out_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.out_proj''', '''decoder.layers.*.self_attn_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn_layer_norm''', '''decoder.layers.*.encoder_attn.k_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.k_proj''', '''decoder.layers.*.encoder_attn.v_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.v_proj''', '''decoder.layers.*.encoder_attn.q_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.q_proj''', '''decoder.layers.*.encoder_attn.out_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.out_proj''', '''decoder.layers.*.encoder_attn_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn_layer_norm''', '''decoder.layers.*.fc1''': '''speecht5.decoder.wrapped_decoder.layers.*.feed_forward.intermediate_dense''', '''decoder.layers.*.fc2''': '''speecht5.decoder.wrapped_decoder.layers.*.feed_forward.output_dense''', '''decoder.layers.*.final_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.final_layer_norm''', } _lowerCAmelCase : Optional[Any] = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_TEXT_DECODER_PRENET, **MAPPING_TEXT_DECODER_POSTNET, } _lowerCAmelCase : Dict = { **MAPPING_TEXT_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } _lowerCAmelCase : Union[str, Any] = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } _lowerCAmelCase : Optional[Any] = [] _lowerCAmelCase : Tuple = [ '''encoder.version''', '''encoder.layers.*.norm_k.weight''', '''encoder.layers.*.norm_k.bias''', '''decoder.version''', '''decoder.layers.*.norm_k.weight''', '''decoder.layers.*.norm_k.bias''', '''decoder.pos_emb.pe_k''', '''speech_encoder_prenet.embed_positions._float_tensor''', '''text_decoder_prenet.embed_positions._float_tensor''', ] _lowerCAmelCase : Tuple = IGNORE_KEYS + [ '''encoder.proj''', '''text_encoder_prenet.*''', '''speech_decoder_prenet.*''', '''speech_decoder_postnet.*''', ] _lowerCAmelCase : int = IGNORE_KEYS + [ '''encoder.proj''', '''speech_encoder_prenet.*''', '''text_decoder_prenet.*''', '''text_decoder_postnet.*''', ] _lowerCAmelCase : Optional[int] = IGNORE_KEYS + [ '''encoder.proj''', '''text_encoder_prenet.*''', '''text_decoder_prenet.*''', '''text_decoder_postnet.*''', ] def __snake_case ( _lowerCAmelCase : int , _lowerCAmelCase : List[str] , _lowerCAmelCase : int , _lowerCAmelCase : Any , _lowerCAmelCase : List[str] ) -> Optional[Any]: for attribute in key.split("." ): A_ : List[Any] = getattr(_lowerCAmelCase , _lowerCAmelCase ) if weight_type is not None: A_ : Tuple = getattr(_lowerCAmelCase , _lowerCAmelCase ).shape else: A_ : List[Any] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" f" {value.shape} for {full_name}" ) if weight_type == "weight": A_ : Dict = value elif weight_type == "weight_g": A_ : int = value elif weight_type == "weight_v": A_ : str = value elif weight_type == "bias": A_ : int = value elif weight_type == "running_mean": A_ : str = value elif weight_type == "running_var": A_ : Any = value elif weight_type == "num_batches_tracked": A_ : str = value else: A_ : int = value logger.info(f"{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}." ) def __snake_case ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : int ) -> Union[str, Any]: for key in ignore_keys: if key.endswith(".*" ): if name.startswith(key[:-1] ): return True elif ".*." in key: A_ , A_ : Tuple = key.split(".*." ) if prefix in name and suffix in name: return True elif key in name: return True return False def __snake_case ( _lowerCAmelCase : int , _lowerCAmelCase : Tuple , _lowerCAmelCase : Optional[Any] ) -> Union[str, Any]: A_ : Tuple = [] if task == "s2t": A_ : Union[str, Any] = hf_model.speechta.encoder.prenet.feature_encoder A_ : str = MAPPING_S2T A_ : Union[str, Any] = IGNORE_KEYS_S2T elif task == "t2s": A_ : Optional[int] = None A_ : Dict = MAPPING_T2S A_ : Any = IGNORE_KEYS_T2S elif task == "s2s": A_ : Optional[int] = hf_model.speechta.encoder.prenet.feature_encoder A_ : Dict = MAPPING_S2S A_ : List[str] = IGNORE_KEYS_S2S else: raise ValueError(f"Unsupported task: {task}" ) for name, value in fairseq_dict.items(): if should_ignore(_lowerCAmelCase , _lowerCAmelCase ): logger.info(f"{name} was ignored" ) continue A_ : List[Any] = False if "conv_layers" in name: load_conv_layer( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , hf_model.config.feat_extract_norm == "group" , ) A_ : Tuple = True else: for key, mapped_key in MAPPING.items(): # mapped_key = "speecht5." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if "*" in key: A_ , A_ : Optional[Any] = key.split(".*." ) if prefix in name and suffix in name: A_ : int = suffix # if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]: if key in name: A_ : str = True if "*" in mapped_key: A_ : List[str] = name.split(_lowerCAmelCase )[0].split("." )[-2] A_ : Optional[int] = mapped_key.replace("*" , _lowerCAmelCase ) if "weight_g" in name: A_ : Union[str, Any] = "weight_g" elif "weight_v" in name: A_ : List[Any] = "weight_v" elif "bias" in name: A_ : Tuple = "bias" elif "weight" in name: A_ : List[Any] = "weight" elif "running_mean" in name: A_ : Union[str, Any] = "running_mean" elif "running_var" in name: A_ : Union[str, Any] = "running_var" elif "num_batches_tracked" in name: A_ : List[Any] = "num_batches_tracked" else: A_ : Optional[Any] = None set_recursively(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) continue if not is_used: unused_weights.append(_lowerCAmelCase ) logger.warning(f"Unused weights: {unused_weights}" ) def __snake_case ( _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Tuple , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Optional[int] ) -> List[Any]: A_ : int = full_name.split("conv_layers." )[-1] A_ : Optional[Any] = name.split("." ) A_ : List[Any] = int(items[0] ) A_ : int = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) A_ : Optional[int] = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) A_ : Optional[Any] = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found." ) A_ : Tuple = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found." ) A_ : Union[str, Any] = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(_lowerCAmelCase ) @torch.no_grad() def __snake_case ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : List[str] , _lowerCAmelCase : str=None , _lowerCAmelCase : List[str]=None , _lowerCAmelCase : int=None , ) -> Optional[Any]: if config_path is not None: A_ : Dict = SpeechTaConfig.from_pretrained(_lowerCAmelCase ) else: A_ : Optional[int] = SpeechTaConfig() if task == "s2t": A_ : Optional[Any] = config.max_text_positions A_ : Optional[int] = SpeechTaForSpeechToText(_lowerCAmelCase ) elif task == "t2s": A_ : str = 1876 A_ : List[str] = 600 A_ : List[str] = config.max_speech_positions A_ : Tuple = SpeechTaForTextToSpeech(_lowerCAmelCase ) elif task == "s2s": A_ : Optional[int] = 1876 A_ : int = config.max_speech_positions A_ : Union[str, Any] = SpeechTaForSpeechToSpeech(_lowerCAmelCase ) else: raise ValueError(f"Unknown task name: {task}" ) if vocab_path: A_ : int = SpeechTaTokenizer(_lowerCAmelCase , model_max_length=config.max_text_positions ) # Mask token behaves like a normal word, i.e. include the space before it A_ : str = AddedToken("<mask>" , lstrip=_lowerCAmelCase , rstrip=_lowerCAmelCase ) A_ : int = mask_token tokenizer.add_special_tokens({"mask_token": mask_token} ) tokenizer.add_tokens(["<ctc_blank>"] ) A_ : int = SpeechTaFeatureExtractor() A_ : Optional[Any] = SpeechTaProcessor(tokenizer=_lowerCAmelCase , feature_extractor=_lowerCAmelCase ) processor.save_pretrained(_lowerCAmelCase ) A_ : Union[str, Any] = torch.load(_lowerCAmelCase ) recursively_load_weights(fairseq_checkpoint["model"] , _lowerCAmelCase , _lowerCAmelCase ) model.save_pretrained(_lowerCAmelCase ) if repo_id: print("Pushing to the hub..." ) processor.push_to_hub(_lowerCAmelCase ) model.push_to_hub(_lowerCAmelCase ) if __name__ == "__main__": _lowerCAmelCase : Tuple = argparse.ArgumentParser() parser.add_argument( '''--task''', default='''s2t''', type=str, help='''Type of the SpeechT5 model you\'d like to convert. Should be one of \'s2t\', \'t2s\', \'s2s\'.''', ) parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--vocab_path''', default=None, type=str, help='''Path to SentencePiece model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) _lowerCAmelCase : Tuple = parser.parse_args() convert_speechta_checkpoint( args.task, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.vocab_path, args.push_to_hub, )
70
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) _lowerCAmelCase : Optional[int] = { '''tiiuae/falcon-40b''': '''https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json''', '''tiiuae/falcon-7b''': '''https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json''', } class __magic_name__ ( lowerCamelCase__ ): """simple docstring""" __UpperCamelCase = '''falcon''' __UpperCamelCase = ['''past_key_values'''] def __init__( self :List[Any] , snake_case :Optional[int]=65_024 , snake_case :Tuple=4_544 , snake_case :Dict=32 , snake_case :Union[str, Any]=71 , snake_case :List[Any]=1e-5 , snake_case :Union[str, Any]=0.02 , snake_case :List[Any]=True , snake_case :Union[str, Any]=0.0 , snake_case :int=0.0 , snake_case :Union[str, Any]=None , snake_case :Dict=False , snake_case :int=False , snake_case :Tuple=True , snake_case :str=True , snake_case :List[Any]=False , snake_case :Optional[Any]=11 , snake_case :Tuple=11 , **snake_case :List[Any] , ): '''simple docstring''' A_ : Optional[int] = vocab_size # Backward compatibility with n_embed kwarg A_ : Any = kwargs.pop("n_embed" , snake_case ) A_ : str = hidden_size if n_embed is None else n_embed A_ : List[str] = num_hidden_layers A_ : List[str] = num_attention_heads A_ : List[str] = layer_norm_epsilon A_ : Optional[Any] = initializer_range A_ : Optional[int] = use_cache A_ : str = hidden_dropout A_ : str = attention_dropout A_ : str = bos_token_id A_ : List[str] = eos_token_id A_ : Union[str, Any] = num_attention_heads if num_kv_heads is None else num_kv_heads A_ : int = alibi A_ : str = new_decoder_architecture A_ : Dict = multi_query # Ignored when new_decoder_architecture is True A_ : Any = parallel_attn A_ : Optional[Any] = bias super().__init__(bos_token_id=snake_case , eos_token_id=snake_case , **snake_case ) @property def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' return self.hidden_size // self.num_attention_heads @property def SCREAMING_SNAKE_CASE ( self :Optional[Any] ): '''simple docstring''' return not self.alibi
70
1
'''simple docstring''' import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient lowercase_ = WebClient(token=os.environ["""CI_SLACK_BOT_TOKEN"""]) def lowerCamelCase ( __lowerCamelCase : Optional[int] ) ->Optional[int]: _SCREAMING_SNAKE_CASE = test_results.split(""" """ ) _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. _SCREAMING_SNAKE_CASE = expressions[-2] if """=""" in expressions[-1] else expressions[-1] for i, expression in enumerate(_A ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def lowerCamelCase ( __lowerCamelCase : Union[str, Any] ) ->Dict: _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = False for line in failures_short_lines.split("""\n""" ): if re.search(R"""_ \[doctest\]""" , _A ): _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = line.split(""" """ )[2] elif in_error and not line.split(""" """ )[0].isdigit(): _SCREAMING_SNAKE_CASE = line _SCREAMING_SNAKE_CASE = False return failures class a_ : '''simple docstring''' def __init__( self , A , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = title _SCREAMING_SNAKE_CASE = doc_test_results["""time_spent"""].split(""",""" )[0] _SCREAMING_SNAKE_CASE = doc_test_results["""success"""] _SCREAMING_SNAKE_CASE = doc_test_results["""failures"""] _SCREAMING_SNAKE_CASE = self.n_success + self.n_failures # Failures and success of the modeling tests _SCREAMING_SNAKE_CASE = doc_test_results @property def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = [self._time_spent] _SCREAMING_SNAKE_CASE = 0 for time in time_spent: _SCREAMING_SNAKE_CASE = time.split(""":""" ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(UpperCAmelCase__ ) == 1: _SCREAMING_SNAKE_CASE = [0, 0, time_parts[0]] _SCREAMING_SNAKE_CASE = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 3600 + minutes * 60 + seconds _SCREAMING_SNAKE_CASE = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 return f'{int(UpperCAmelCase__ )}h{int(UpperCAmelCase__ )}m{int(UpperCAmelCase__ )}s' @property def snake_case_( self ) -> Dict: return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def snake_case_( self ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": f'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def snake_case_( self ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def snake_case_( self ) -> Dict: _SCREAMING_SNAKE_CASE = 40 _SCREAMING_SNAKE_CASE = {k: v["""failed"""] for k, v in doc_test_results.items() if isinstance(UpperCAmelCase__ , UpperCAmelCase__ )} _SCREAMING_SNAKE_CASE = """""" for category, failures in category_failures.items(): if len(UpperCAmelCase__ ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(UpperCAmelCase__ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(UpperCAmelCase__ ) @staticmethod def snake_case_( ) -> Tuple: _SCREAMING_SNAKE_CASE = [ { """type""": """section""", """text""": { """type""": """plain_text""", """text""": """There was an issue running the tests.""", }, """accessory""": { """type""": """button""", """text""": {"""type""": """plain_text""", """text""": """Check Action results""", """emoji""": True}, """url""": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print("""Sending the following payload""" ) print(json.dumps({"""blocks""": json.loads(UpperCAmelCase__ )} ) ) client.chat_postMessage( channel=os.environ["""CI_SLACK_CHANNEL_ID_DAILY"""] , text="""There was an issue running the tests.""" , blocks=UpperCAmelCase__ , ) def snake_case_( self ) -> Optional[int]: print("""Sending the following payload""" ) print(json.dumps({"""blocks""": json.loads(self.payload )} ) ) _SCREAMING_SNAKE_CASE = f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else """All tests passed.""" _SCREAMING_SNAKE_CASE = client.chat_postMessage( channel=os.environ["""CI_SLACK_CHANNEL_ID_DAILY"""] , blocks=self.payload , text=UpperCAmelCase__ , ) def snake_case_( self , A , A , A , A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = """""" for key, value in failures.items(): _SCREAMING_SNAKE_CASE = value[:200] + """ [Truncated]""" if len(UpperCAmelCase__ ) > 250 else value failures_text += f'*{key}*\n_{value}_\n\n' _SCREAMING_SNAKE_CASE = job_name _SCREAMING_SNAKE_CASE = {"""type""": """section""", """text""": {"""type""": """mrkdwn""", """text""": text}} if job_link is not None: _SCREAMING_SNAKE_CASE = { """type""": """button""", """text""": {"""type""": """plain_text""", """text""": """GitHub Action job""", """emoji""": True}, """url""": job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def snake_case_( self ) -> Tuple: if self.thread_ts is None: raise ValueError("""Can only post reply if a post has been made.""" ) _SCREAMING_SNAKE_CASE = self.doc_test_results.pop("""job_link""" ) self.doc_test_results.pop("""failures""" ) self.doc_test_results.pop("""success""" ) self.doc_test_results.pop("""time_spent""" ) _SCREAMING_SNAKE_CASE = sorted(self.doc_test_results.items() , key=lambda A : t[0] ) for job, job_result in sorted_dict: if len(job_result["""failures"""] ): _SCREAMING_SNAKE_CASE = f'*Num failures* :{len(job_result["failed"] )} \n' _SCREAMING_SNAKE_CASE = job_result["""failures"""] _SCREAMING_SNAKE_CASE = self.get_reply_blocks(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , text=UpperCAmelCase__ ) print("""Sending the following reply""" ) print(json.dumps({"""blocks""": blocks} ) ) client.chat_postMessage( channel=os.environ["""CI_SLACK_CHANNEL_ID_DAILY"""] , text=f'Results for {job}' , blocks=UpperCAmelCase__ , thread_ts=self.thread_ts["""ts"""] , ) time.sleep(1 ) def lowerCamelCase ( ) ->Union[str, Any]: _SCREAMING_SNAKE_CASE = os.environ["""GITHUB_RUN_ID"""] _SCREAMING_SNAKE_CASE = F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' _SCREAMING_SNAKE_CASE = requests.get(_A ).json() _SCREAMING_SNAKE_CASE = {} try: jobs.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) _SCREAMING_SNAKE_CASE = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(_A ): _SCREAMING_SNAKE_CASE = requests.get(url + F'&page={i + 2}' ).json() jobs.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return jobs except Exception as e: print("""Unknown error, could not fetch links.""" , _A ) return {} def lowerCamelCase ( __lowerCamelCase : List[str] ) ->Tuple: _SCREAMING_SNAKE_CASE = {} if os.path.exists(_A ): _SCREAMING_SNAKE_CASE = os.listdir(_A ) for file in files: try: with open(os.path.join(_A , _A ) , encoding="""utf-8""" ) as f: _SCREAMING_SNAKE_CASE = f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(_A , _A )}.' ) from e return _artifact def lowerCamelCase ( ) ->str: class a_ : '''simple docstring''' def __init__( self , A ) -> Tuple: _SCREAMING_SNAKE_CASE = name _SCREAMING_SNAKE_CASE = [] def __str__( self ) -> List[str]: return self.name def snake_case_( self , A ) -> int: self.paths.append({"""name""": self.name, """path""": path} ) _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE = filter(os.path.isdir , os.listdir() ) for directory in directories: _SCREAMING_SNAKE_CASE = directory if artifact_name not in _available_artifacts: _SCREAMING_SNAKE_CASE = Artifact(_A ) _available_artifacts[artifact_name].add_path(_A ) return _available_artifacts if __name__ == "__main__": lowercase_ = get_job_links() lowercase_ = retrieve_available_artifacts() lowercase_ = collections.OrderedDict( [ ("""*.py""", """API Examples"""), ("""*.md""", """MD Examples"""), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' lowercase_ = { v: { """failed""": [], """failures""": {}, } for v in docs.values() } # Link to the GitHub Action job lowercase_ = github_actions_job_links.get("""run_doctests""") lowercase_ = available_artifacts["""doc_tests_gpu_test_reports"""].paths[0] lowercase_ = retrieve_artifact(artifact_path["""name"""]) if "stats" in artifact: lowercase_ = handle_test_results(artifact["""stats"""]) lowercase_ = failed lowercase_ = success lowercase_ = time_spent[1:-1] + """, """ lowercase_ = extract_first_line_failure(artifact["""failures_short"""]) for line in artifact["summary_short"].split("""\n"""): if re.search("""FAILED""", line): lowercase_ = line.replace("""FAILED """, """""") lowercase_ = line.split()[0].replace("""\n""", """""") if "::" in line: lowercase_ = line.split("""::""") else: lowercase_ = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): lowercase_ = docs[file_regex] doc_test_results[category]["failed"].append(test) lowercase_ = all_failures[test] if test in all_failures else """N/A""" lowercase_ = failure break lowercase_ = Message("""🤗 Results of the doc tests.""", doc_test_results) message.post() message.post_reply()
58
# Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar UpperCAmelCase__ : Tuple = TypeVar("""T""") class a__ ( Generic[T] ): """simple docstring""" def __init__( self : str , UpperCAmelCase__ : bool = True ) ->None: """simple docstring""" SCREAMING_SNAKE_CASE : dict[T, list[T]] = {} # dictionary of lists SCREAMING_SNAKE_CASE : Dict = directed def _lowercase ( self : int , UpperCAmelCase__ : T , UpperCAmelCase__ : T ) ->GraphAdjacencyList[T]: """simple docstring""" if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(UpperCAmelCase__ ) self.adj_list[destination_vertex].append(UpperCAmelCase__ ) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : int = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : str = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: SCREAMING_SNAKE_CASE : Tuple = [destination_vertex] SCREAMING_SNAKE_CASE : str = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(UpperCAmelCase__ ) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : Any = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: SCREAMING_SNAKE_CASE : Optional[Any] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: SCREAMING_SNAKE_CASE : Dict = [destination_vertex] SCREAMING_SNAKE_CASE : List[Any] = [] return self def __repr__( self : Dict ) ->str: """simple docstring""" return pformat(self.adj_list )
245
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowercase : Tuple = logging.get_logger(__name__) lowercase : List[Any] = { "microsoft/table-transformer-detection": ( "https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json" ), } class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = """table-transformer""" __lowercase = ["""past_key_values"""] __lowercase = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , lowerCAmelCase_=True , lowerCAmelCase_=None , lowerCAmelCase_=3 , lowerCAmelCase_=1_00 , lowerCAmelCase_=6 , lowerCAmelCase_=20_48 , lowerCAmelCase_=8 , lowerCAmelCase_=6 , lowerCAmelCase_=20_48 , lowerCAmelCase_=8 , lowerCAmelCase_=0.0 , lowerCAmelCase_=0.0 , lowerCAmelCase_=True , lowerCAmelCase_="relu" , lowerCAmelCase_=2_56 , lowerCAmelCase_=0.1 , lowerCAmelCase_=0.0 , lowerCAmelCase_=0.0 , lowerCAmelCase_=0.02 , lowerCAmelCase_=1.0 , lowerCAmelCase_=False , lowerCAmelCase_="sine" , lowerCAmelCase_="resnet50" , lowerCAmelCase_=True , lowerCAmelCase_=False , lowerCAmelCase_=1 , lowerCAmelCase_=5 , lowerCAmelCase_=2 , lowerCAmelCase_=1 , lowerCAmelCase_=1 , lowerCAmelCase_=5 , lowerCAmelCase_=2 , lowerCAmelCase_=0.1 , **lowerCAmelCase_ , ): """simple docstring""" if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _snake_case = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): _snake_case = backbone_config.get('model_type' ) _snake_case = CONFIG_MAPPING[backbone_model_type] _snake_case = config_class.from_dict(lowerCAmelCase_ ) # set timm attributes to None _snake_case , _snake_case , _snake_case = None, None, None _snake_case = use_timm_backbone _snake_case = backbone_config _snake_case = num_channels _snake_case = num_queries _snake_case = d_model _snake_case = encoder_ffn_dim _snake_case = encoder_layers _snake_case = encoder_attention_heads _snake_case = decoder_ffn_dim _snake_case = decoder_layers _snake_case = decoder_attention_heads _snake_case = dropout _snake_case = attention_dropout _snake_case = activation_dropout _snake_case = activation_function _snake_case = init_std _snake_case = init_xavier_std _snake_case = encoder_layerdrop _snake_case = decoder_layerdrop _snake_case = encoder_layers _snake_case = auxiliary_loss _snake_case = position_embedding_type _snake_case = backbone _snake_case = use_pretrained_backbone _snake_case = dilation # Hungarian matcher _snake_case = class_cost _snake_case = bbox_cost _snake_case = giou_cost # Loss coefficients _snake_case = mask_loss_coefficient _snake_case = dice_loss_coefficient _snake_case = bbox_loss_coefficient _snake_case = giou_loss_coefficient _snake_case = eos_coefficient super().__init__(is_encoder_decoder=lowerCAmelCase_ , **lowerCAmelCase_ ) @property def lowerCamelCase ( self ): """simple docstring""" return self.encoder_attention_heads @property def lowerCamelCase ( self ): """simple docstring""" return self.d_model class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = version.parse("""1.11""" ) @property def lowerCamelCase ( self ): """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def lowerCamelCase ( self ): """simple docstring""" return 1E-5 @property def lowerCamelCase ( self ): """simple docstring""" return 12
369
'''simple docstring''' import uuid from typing import Any, Dict, List, Optional, Union from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch lowercase : Any = logging.get_logger(__name__) class __UpperCAmelCase : def __init__( self , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_=None , lowerCAmelCase_=None ): """simple docstring""" if not conversation_id: _snake_case = uuid.uuida() if past_user_inputs is None: _snake_case = [] if generated_responses is None: _snake_case = [] _snake_case = conversation_id _snake_case = past_user_inputs _snake_case = generated_responses _snake_case = text def __eq__( self , lowerCAmelCase_ ): """simple docstring""" if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return False if self.uuid == other.uuid: return True return ( self.new_user_input == other.new_user_input and self.past_user_inputs == other.past_user_inputs and self.generated_responses == other.generated_responses ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ = False ): """simple docstring""" if self.new_user_input: if overwrite: logger.warning( F'User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten ' F'with: "{text}".' ) _snake_case = text else: logger.warning( F'User input added while unprocessed input was existing: "{self.new_user_input}" new input ' F'ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input' ) else: _snake_case = text def lowerCamelCase ( self ): """simple docstring""" if self.new_user_input: self.past_user_inputs.append(self.new_user_input ) _snake_case = None def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" self.generated_responses.append(lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" for user_input, generated_response in zip(self.past_user_inputs , self.generated_responses ): yield True, user_input yield False, generated_response if self.new_user_input: yield True, self.new_user_input def __repr__( self ): """simple docstring""" _snake_case = F'Conversation id: {self.uuid} \n' for is_user, text in self.iter_texts(): _snake_case = 'user' if is_user else 'bot' output += F'{name} >> {text} \n' return output @add_end_docstrings( _lowerCamelCase , r""" min_length_for_response (`int`, *optional*, defaults to 32): The minimum length (in number of tokens) for a response. minimum_tokens (`int`, *optional*, defaults to 10): The minimum length of tokens to leave for a response. """ , ) class __UpperCAmelCase ( _lowerCamelCase ): def __init__( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" super().__init__(*lowerCAmelCase_ , **lowerCAmelCase_ ) if self.tokenizer.pad_token_id is None: _snake_case = self.tokenizer.eos_token def lowerCamelCase ( self , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None , **lowerCAmelCase_ ): """simple docstring""" _snake_case = {} _snake_case = {} _snake_case = {} if min_length_for_response is not None: _snake_case = min_length_for_response if minimum_tokens is not None: _snake_case = minimum_tokens if "max_length" in generate_kwargs: _snake_case = generate_kwargs['max_length'] # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length) if clean_up_tokenization_spaces is not None: _snake_case = clean_up_tokenization_spaces if generate_kwargs: forward_params.update(lowerCAmelCase_ ) return preprocess_params, forward_params, postprocess_params def __call__( self , lowerCAmelCase_ , lowerCAmelCase_=0 , **lowerCAmelCase_ ): """simple docstring""" _snake_case = super().__call__(lowerCAmelCase_ , num_workers=lowerCAmelCase_ , **lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and len(lowerCAmelCase_ ) == 1: return outputs[0] return outputs def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_=32 ): """simple docstring""" if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError('ConversationalPipeline, expects Conversation as inputs' ) if conversation.new_user_input is None: raise ValueError( F'Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. ' 'Add user inputs with the conversation\'s `add_user_input` method' ) if hasattr(self.tokenizer , '_build_conversation_input_ids' ): _snake_case = self.tokenizer._build_conversation_input_ids(lowerCAmelCase_ ) else: # If the tokenizer cannot handle conversations, we default to only the old version _snake_case = self._legacy_parse_and_tokenize(lowerCAmelCase_ ) if self.framework == "pt": _snake_case = torch.LongTensor([input_ids] ) elif self.framework == "tf": _snake_case = tf.constant([input_ids] ) return {"input_ids": input_ids, "conversation": conversation} def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_=10 , **lowerCAmelCase_ ): """simple docstring""" _snake_case = generate_kwargs.get('max_length' , self.model.config.max_length ) _snake_case = model_inputs['input_ids'].shape[1] if max_length - minimum_tokens < n: logger.warning(F'Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})' ) _snake_case = max_length - minimum_tokens _snake_case = model_inputs['input_ids'][:, -trim:] if "attention_mask" in model_inputs: _snake_case = model_inputs['attention_mask'][:, -trim:] _snake_case = model_inputs.pop('conversation' ) _snake_case = max_length _snake_case = self.model.generate(**lowerCAmelCase_ , **lowerCAmelCase_ ) if self.model.config.is_encoder_decoder: _snake_case = 1 else: _snake_case = n return {"output_ids": output_ids[:, start_position:], "conversation": conversation} def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_=True ): """simple docstring""" _snake_case = model_outputs['output_ids'] _snake_case = self.tokenizer.decode( output_ids[0] , skip_special_tokens=lowerCAmelCase_ , clean_up_tokenization_spaces=lowerCAmelCase_ , ) _snake_case = model_outputs['conversation'] conversation.mark_processed() conversation.append_response(lowerCAmelCase_ ) return conversation def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case = self.tokenizer.eos_token_id _snake_case = [] for is_user, text in conversation.iter_texts(): if eos_token_id is not None: input_ids.extend(self.tokenizer.encode(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ ) + [eos_token_id] ) else: input_ids.extend(self.tokenizer.encode(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ ) ) if len(lowerCAmelCase_ ) > self.tokenizer.model_max_length: _snake_case = input_ids[-self.tokenizer.model_max_length :] return input_ids
160
0
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class A_ : def __init__( self : List[str] ): _UpperCAmelCase = {} def lowercase ( self : int , snake_case_ : str ): _UpperCAmelCase = {} def lowercase ( self : Tuple , snake_case_ : str , snake_case_ : str , snake_case_ : float ): if nodea not in self.connections: self.add_node(snake_case_ ) if nodea not in self.connections: self.add_node(snake_case_ ) _UpperCAmelCase = probability def lowercase ( self : Tuple ): return list(self.connections ) def lowercase ( self : Dict , snake_case_ : str ): _UpperCAmelCase = 0 _UpperCAmelCase = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def UpperCAmelCase_ ( __lowercase : str , __lowercase : list[tuple[str, str, float]] , __lowercase : int ) -> dict[str, int]: '''simple docstring''' _UpperCAmelCase = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__lowercase , __lowercase , __lowercase ) _UpperCAmelCase = Counter(graph.get_nodes() ) _UpperCAmelCase = start for _ in range(__lowercase ): _UpperCAmelCase = graph.transition(__lowercase ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
22
'''simple docstring''' import re from filelock import FileLock try: import nltk __SCREAMING_SNAKE_CASE :Optional[int] = True except (ImportError, ModuleNotFoundError): __SCREAMING_SNAKE_CASE :str = False if NLTK_AVAILABLE: with FileLock('''.lock''') as lock: nltk.download('''punkt''', quiet=True) def UpperCAmelCase_ ( __lowercase : str ) -> str: '''simple docstring''' re.sub("<n>" , "" , __lowercase ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(__lowercase ) )
22
1
'''simple docstring''' import os import sys import unittest __snake_case =os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) __snake_case =os.path.join("""tests""", """models""", """bert""", """test_modeling_bert.py""") __snake_case =os.path.join("""tests""", """models""", """blip""", """test_modeling_blip.py""") class UpperCAmelCase_ ( unittest.TestCase ): def __UpperCAmelCase ( self : int ) -> Optional[int]: lowerCAmelCase = get_test_to_tester_mapping(UpperCAmelCase__ ) lowerCAmelCase = get_test_to_tester_mapping(UpperCAmelCase__ ) lowerCAmelCase = {'BertModelTest': 'BertModelTester'} lowerCAmelCase = { 'BlipModelTest': 'BlipModelTester', 'BlipTextImageModelTest': 'BlipTextImageModelsModelTester', 'BlipTextModelTest': 'BlipTextModelTester', 'BlipTextRetrievalModelTest': 'BlipTextRetrievalModelTester', 'BlipVQAModelTest': 'BlipVQAModelTester', 'BlipVisionModelTest': 'BlipVisionModelTester', } self.assertEqual(get_test_info.to_json(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(get_test_info.to_json(UpperCAmelCase__ ) , UpperCAmelCase__ ) def __UpperCAmelCase ( self : Optional[int] ) -> Tuple: lowerCAmelCase = get_model_to_test_mapping(UpperCAmelCase__ ) lowerCAmelCase = get_model_to_test_mapping(UpperCAmelCase__ ) lowerCAmelCase = { 'BertForMaskedLM': ['BertModelTest'], 'BertForMultipleChoice': ['BertModelTest'], 'BertForNextSentencePrediction': ['BertModelTest'], 'BertForPreTraining': ['BertModelTest'], 'BertForQuestionAnswering': ['BertModelTest'], 'BertForSequenceClassification': ['BertModelTest'], 'BertForTokenClassification': ['BertModelTest'], 'BertLMHeadModel': ['BertModelTest'], 'BertModel': ['BertModelTest'], } lowerCAmelCase = { 'BlipForConditionalGeneration': ['BlipTextImageModelTest'], 'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTest'], 'BlipForQuestionAnswering': ['BlipVQAModelTest'], 'BlipModel': ['BlipModelTest'], 'BlipTextModel': ['BlipTextModelTest'], 'BlipVisionModel': ['BlipVisionModelTest'], } self.assertEqual(get_test_info.to_json(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(get_test_info.to_json(UpperCAmelCase__ ) , UpperCAmelCase__ ) def __UpperCAmelCase ( self : Optional[Any] ) -> Any: lowerCAmelCase = get_model_to_tester_mapping(UpperCAmelCase__ ) lowerCAmelCase = get_model_to_tester_mapping(UpperCAmelCase__ ) lowerCAmelCase = { 'BertForMaskedLM': ['BertModelTester'], 'BertForMultipleChoice': ['BertModelTester'], 'BertForNextSentencePrediction': ['BertModelTester'], 'BertForPreTraining': ['BertModelTester'], 'BertForQuestionAnswering': ['BertModelTester'], 'BertForSequenceClassification': ['BertModelTester'], 'BertForTokenClassification': ['BertModelTester'], 'BertLMHeadModel': ['BertModelTester'], 'BertModel': ['BertModelTester'], } lowerCAmelCase = { 'BlipForConditionalGeneration': ['BlipTextImageModelsModelTester'], 'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTester'], 'BlipForQuestionAnswering': ['BlipVQAModelTester'], 'BlipModel': ['BlipModelTester'], 'BlipTextModel': ['BlipTextModelTester'], 'BlipVisionModel': ['BlipVisionModelTester'], } self.assertEqual(get_test_info.to_json(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(get_test_info.to_json(UpperCAmelCase__ ) , UpperCAmelCase__ )
55
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar __snake_case =TypeVar("""T""") class UpperCAmelCase_ ( Generic[T] ): def __init__( self : int , UpperCAmelCase__ : T ) -> List[str]: lowerCAmelCase = data lowerCAmelCase = None def __str__( self : Optional[int] ) -> str: return F'''{self.data}''' class UpperCAmelCase_ ( Generic[T] ): def __init__( self : Optional[Any] ) -> None: lowerCAmelCase = None def __iter__( self : Any ) -> Iterator[T]: lowerCAmelCase = self.top while node: yield node.data lowerCAmelCase = node.next def __str__( self : str ) -> str: return "->".join([str(UpperCAmelCase__ ) for item in self] ) def __len__( self : Optional[int] ) -> int: return len(tuple(iter(self ) ) ) def __UpperCAmelCase ( self : Optional[Any] ) -> bool: return self.top is None def __UpperCAmelCase ( self : Dict , UpperCAmelCase__ : T ) -> None: lowerCAmelCase = Node(UpperCAmelCase__ ) if not self.is_empty(): lowerCAmelCase = self.top lowerCAmelCase = node def __UpperCAmelCase ( self : str ) -> T: if self.is_empty(): raise IndexError('pop from empty stack' ) assert isinstance(self.top , UpperCAmelCase__ ) lowerCAmelCase = self.top lowerCAmelCase = self.top.next return pop_node.data def __UpperCAmelCase ( self : List[Any] ) -> T: if self.is_empty(): raise IndexError('peek from empty stack' ) assert self.top is not None return self.top.data def __UpperCAmelCase ( self : str ) -> None: lowerCAmelCase = None if __name__ == "__main__": from doctest import testmod testmod()
55
1
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class A__ ( __SCREAMING_SNAKE_CASE): _UpperCAmelCase : Union[str, Any] = """conditional_detr""" _UpperCAmelCase : Optional[int] = ["""past_key_values"""] _UpperCAmelCase : Optional[Any] = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , __magic_name__=True , __magic_name__=None , __magic_name__=3 , __magic_name__=3_0_0 , __magic_name__=6 , __magic_name__=2_0_4_8 , __magic_name__=8 , __magic_name__=6 , __magic_name__=2_0_4_8 , __magic_name__=8 , __magic_name__=0.0 , __magic_name__=0.0 , __magic_name__=True , __magic_name__="relu" , __magic_name__=2_5_6 , __magic_name__=0.1 , __magic_name__=0.0 , __magic_name__=0.0 , __magic_name__=0.02 , __magic_name__=1.0 , __magic_name__=False , __magic_name__="sine" , __magic_name__="resnet50" , __magic_name__=True , __magic_name__=False , __magic_name__=2 , __magic_name__=5 , __magic_name__=2 , __magic_name__=1 , __magic_name__=1 , __magic_name__=2 , __magic_name__=5 , __magic_name__=2 , __magic_name__=0.25 , **__magic_name__ , ): if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) lowerCamelCase : Optional[int] = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(__magic_name__ , __magic_name__ ): lowerCamelCase : List[Any] = backbone_config.get("""model_type""" ) lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] lowerCamelCase : str = config_class.from_dict(__magic_name__ ) lowerCamelCase : Dict = use_timm_backbone lowerCamelCase : str = backbone_config lowerCamelCase : Tuple = num_channels lowerCamelCase : Dict = num_queries lowerCamelCase : Any = d_model lowerCamelCase : Optional[Any] = encoder_ffn_dim lowerCamelCase : List[str] = encoder_layers lowerCamelCase : Union[str, Any] = encoder_attention_heads lowerCamelCase : Any = decoder_ffn_dim lowerCamelCase : Dict = decoder_layers lowerCamelCase : Union[str, Any] = decoder_attention_heads lowerCamelCase : Dict = dropout lowerCamelCase : List[str] = attention_dropout lowerCamelCase : Union[str, Any] = activation_dropout lowerCamelCase : Optional[int] = activation_function lowerCamelCase : int = init_std lowerCamelCase : str = init_xavier_std lowerCamelCase : Tuple = encoder_layerdrop lowerCamelCase : str = decoder_layerdrop lowerCamelCase : Tuple = encoder_layers lowerCamelCase : Optional[int] = auxiliary_loss lowerCamelCase : Optional[Any] = position_embedding_type lowerCamelCase : Optional[int] = backbone lowerCamelCase : Union[str, Any] = use_pretrained_backbone lowerCamelCase : str = dilation # Hungarian matcher lowerCamelCase : Optional[Any] = class_cost lowerCamelCase : Dict = bbox_cost lowerCamelCase : Tuple = giou_cost # Loss coefficients lowerCamelCase : Union[str, Any] = mask_loss_coefficient lowerCamelCase : Dict = dice_loss_coefficient lowerCamelCase : Optional[int] = cls_loss_coefficient lowerCamelCase : Optional[int] = bbox_loss_coefficient lowerCamelCase : Optional[int] = giou_loss_coefficient lowerCamelCase : Optional[int] = focal_alpha super().__init__(is_encoder_decoder=__magic_name__ , **__magic_name__ ) @property def UpperCamelCase__ ( self ): return self.encoder_attention_heads @property def UpperCamelCase__ ( self ): return self.d_model def UpperCamelCase__ ( self ): lowerCamelCase : Optional[int] = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: lowerCamelCase : Optional[int] = self.backbone_config.to_dict() lowerCamelCase : Optional[Any] = self.__class__.model_type return output class A__ ( __SCREAMING_SNAKE_CASE): _UpperCAmelCase : Any = version.parse("""1.11""") @property def UpperCamelCase__ ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def UpperCamelCase__ ( self ): return 1e-5 @property def UpperCamelCase__ ( self ): return 1_2
287
import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger _lowerCamelCase =get_logger(__name__) class A__ : def __init__( self , __magic_name__ = None ): lowerCamelCase : Dict = ( os.path.join(__magic_name__ , config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH ) lowerCamelCase : List[str] = Extractor def UpperCamelCase__ ( self , __magic_name__ ): from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" lowerCamelCase : int = os.path.abspath(__magic_name__ ) return os.path.join(self.extract_dir , hash_url_to_filename(__magic_name__ ) ) def UpperCamelCase__ ( self , __magic_name__ , __magic_name__ ): return force_extract or ( not os.path.isfile(__magic_name__ ) and not (os.path.isdir(__magic_name__ ) and os.listdir(__magic_name__ )) ) def UpperCamelCase__ ( self , __magic_name__ , __magic_name__ = False ): lowerCamelCase : Union[str, Any] = self.extractor.infer_extractor_format(__magic_name__ ) if not extractor_format: return input_path lowerCamelCase : int = self._get_output_path(__magic_name__ ) if self._do_extract(__magic_name__ , __magic_name__ ): self.extractor.extract(__magic_name__ , __magic_name__ , __magic_name__ ) return output_path class A__ ( __SCREAMING_SNAKE_CASE): @classmethod @abstractmethod def UpperCamelCase__ ( cls , __magic_name__ , **__magic_name__ ): ... @staticmethod @abstractmethod def UpperCamelCase__ ( __magic_name__ , __magic_name__ ): ... class A__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): _UpperCAmelCase : List[bytes] = [] @staticmethod def UpperCamelCase__ ( __magic_name__ , __magic_name__ ): with open(__magic_name__ , """rb""" ) as f: return f.read(__magic_name__ ) @classmethod def UpperCamelCase__ ( cls , __magic_name__ , __magic_name__ = b"" ): if not magic_number: lowerCamelCase : Optional[Any] = max(len(__magic_name__ ) for cls_magic_number in cls.magic_numbers ) try: lowerCamelCase : Tuple = cls.read_magic_number(__magic_name__ , __magic_name__ ) except OSError: return False return any(magic_number.startswith(__magic_name__ ) for cls_magic_number in cls.magic_numbers ) class A__ ( __SCREAMING_SNAKE_CASE): @classmethod def UpperCamelCase__ ( cls , __magic_name__ , **__magic_name__ ): return tarfile.is_tarfile(__magic_name__ ) @staticmethod def UpperCamelCase__ ( __magic_name__ , __magic_name__ ): def resolved(__magic_name__ ) -> str: return os.path.realpath(os.path.abspath(__magic_name__ ) ) def badpath(__magic_name__ , __magic_name__ ) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(__magic_name__ , __magic_name__ ) ).startswith(__magic_name__ ) def badlink(__magic_name__ , __magic_name__ ) -> bool: # Links are interpreted relative to the directory containing the link lowerCamelCase : List[str] = resolved(os.path.join(__magic_name__ , os.path.dirname(info.name ) ) ) return badpath(info.linkname , base=__magic_name__ ) lowerCamelCase : Optional[Any] = resolved(__magic_name__ ) for finfo in members: if badpath(finfo.name , __magic_name__ ): logger.error(F'''Extraction of {finfo.name} is blocked (illegal path)''' ) elif finfo.issym() and badlink(__magic_name__ , __magic_name__ ): logger.error(F'''Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}''' ) elif finfo.islnk() and badlink(__magic_name__ , __magic_name__ ): logger.error(F'''Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}''' ) else: yield finfo @staticmethod def UpperCamelCase__ ( __magic_name__ , __magic_name__ ): os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) lowerCamelCase : Dict = tarfile.open(__magic_name__ ) tar_file.extractall(__magic_name__ , members=TarExtractor.safemembers(__magic_name__ , __magic_name__ ) ) tar_file.close() class A__ ( __SCREAMING_SNAKE_CASE): _UpperCAmelCase : str = [B"""\x1F\x8B"""] @staticmethod def UpperCamelCase__ ( __magic_name__ , __magic_name__ ): with gzip.open(__magic_name__ , """rb""" ) as gzip_file: with open(__magic_name__ , """wb""" ) as extracted_file: shutil.copyfileobj(__magic_name__ , __magic_name__ ) class A__ ( __SCREAMING_SNAKE_CASE): _UpperCAmelCase : Optional[int] = [ B"""PK\x03\x04""", B"""PK\x05\x06""", # empty archive B"""PK\x07\x08""", # spanned archive ] @classmethod def UpperCamelCase__ ( cls , __magic_name__ , __magic_name__ = b"" ): if super().is_extractable(__magic_name__ , magic_number=__magic_name__ ): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(__magic_name__ , """rb""" ) as fp: lowerCamelCase : List[str] = _EndRecData(__magic_name__ ) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET] ) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: lowerCamelCase : List[Any] = fp.read(__magic_name__ ) # CD is where we expect it to be if len(__magic_name__ ) == sizeCentralDir: lowerCamelCase : str = struct.unpack(__magic_name__ , __magic_name__ ) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def UpperCamelCase__ ( __magic_name__ , __magic_name__ ): os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) with zipfile.ZipFile(__magic_name__ , """r""" ) as zip_file: zip_file.extractall(__magic_name__ ) zip_file.close() class A__ ( __SCREAMING_SNAKE_CASE): _UpperCAmelCase : List[str] = [B"""\xFD\x37\x7A\x58\x5A\x00"""] @staticmethod def UpperCamelCase__ ( __magic_name__ , __magic_name__ ): with lzma.open(__magic_name__ ) as compressed_file: with open(__magic_name__ , """wb""" ) as extracted_file: shutil.copyfileobj(__magic_name__ , __magic_name__ ) class A__ ( __SCREAMING_SNAKE_CASE): _UpperCAmelCase : Any = [B"""Rar!\x1a\x07\x00""", B"""Rar!\x1a\x07\x01\x00"""] # RAR_ID # RAR5_ID @staticmethod def UpperCamelCase__ ( __magic_name__ , __magic_name__ ): if not config.RARFILE_AVAILABLE: raise ImportError("""Please pip install rarfile""" ) import rarfile os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) lowerCamelCase : Union[str, Any] = rarfile.RarFile(__magic_name__ ) rf.extractall(__magic_name__ ) rf.close() class A__ ( __SCREAMING_SNAKE_CASE): _UpperCAmelCase : Tuple = [B"""\x28\xb5\x2F\xFD"""] @staticmethod def UpperCamelCase__ ( __magic_name__ , __magic_name__ ): if not config.ZSTANDARD_AVAILABLE: raise ImportError("""Please pip install zstandard""" ) import zstandard as zstd lowerCamelCase : int = zstd.ZstdDecompressor() with open(__magic_name__ , """rb""" ) as ifh, open(__magic_name__ , """wb""" ) as ofh: dctx.copy_stream(__magic_name__ , __magic_name__ ) class A__ ( __SCREAMING_SNAKE_CASE): _UpperCAmelCase : Any = [B"""\x42\x5A\x68"""] @staticmethod def UpperCamelCase__ ( __magic_name__ , __magic_name__ ): with bza.open(__magic_name__ , """rb""" ) as compressed_file: with open(__magic_name__ , """wb""" ) as extracted_file: shutil.copyfileobj(__magic_name__ , __magic_name__ ) class A__ ( __SCREAMING_SNAKE_CASE): _UpperCAmelCase : List[Any] = [B"""\x37\x7A\xBC\xAF\x27\x1C"""] @staticmethod def UpperCamelCase__ ( __magic_name__ , __magic_name__ ): if not config.PY7ZR_AVAILABLE: raise ImportError("""Please pip install py7zr""" ) import pyazr os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) with pyazr.SevenZipFile(__magic_name__ , """r""" ) as archive: archive.extractall(__magic_name__ ) class A__ ( __SCREAMING_SNAKE_CASE): _UpperCAmelCase : List[Any] = [B"""\x04\x22\x4D\x18"""] @staticmethod def UpperCamelCase__ ( __magic_name__ , __magic_name__ ): if not config.LZ4_AVAILABLE: raise ImportError("""Please pip install lz4""" ) import lza.frame with lza.frame.open(__magic_name__ , """rb""" ) as compressed_file: with open(__magic_name__ , """wb""" ) as extracted_file: shutil.copyfileobj(__magic_name__ , __magic_name__ ) class A__ : # Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip) _UpperCAmelCase : Dict[str, Type[BaseExtractor]] = { "tar": TarExtractor, "gzip": GzipExtractor, "zip": ZipExtractor, "xz": XzExtractor, "rar": RarExtractor, "zstd": ZstdExtractor, "bz2": BzipaExtractor, "7z": SevenZipExtractor, # <Added version="2.4.0"/> "lz4": LzaExtractor, # <Added version="2.4.0"/> } @classmethod def UpperCamelCase__ ( cls ): return max( len(__magic_name__ ) for extractor in cls.extractors.values() if issubclass(__magic_name__ , __magic_name__ ) for extractor_magic_number in extractor.magic_numbers ) @staticmethod def UpperCamelCase__ ( __magic_name__ , __magic_name__ ): try: return MagicNumberBaseExtractor.read_magic_number(__magic_name__ , magic_number_length=__magic_name__ ) except OSError: return b"" @classmethod def UpperCamelCase__ ( cls , __magic_name__ , __magic_name__ = False ): warnings.warn( """Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'infer_extractor_format' instead.""" , category=__magic_name__ , ) lowerCamelCase : int = cls.infer_extractor_format(__magic_name__ ) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def UpperCamelCase__ ( cls , __magic_name__ ): # <Added version="2.4.0"/> lowerCamelCase : Dict = cls._get_magic_number_max_length() lowerCamelCase : Optional[Any] = cls._read_magic_number(__magic_name__ , __magic_name__ ) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(__magic_name__ , magic_number=__magic_name__ ): return extractor_format @classmethod def UpperCamelCase__ ( cls , __magic_name__ , __magic_name__ , __magic_name__ = None , __magic_name__ = "deprecated" , ): os.makedirs(os.path.dirname(__magic_name__ ) , exist_ok=__magic_name__ ) # Prevent parallel extractions lowerCamelCase : Tuple = str(Path(__magic_name__ ).with_suffix(""".lock""" ) ) with FileLock(__magic_name__ ): shutil.rmtree(__magic_name__ , ignore_errors=__magic_name__ ) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(__magic_name__ , __magic_name__ ): # passed as positional arg warnings.warn( """Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'extractor_format' instead.""" , category=__magic_name__ , ) lowerCamelCase : int = extractor if extractor != """deprecated""" else extractor_format else: lowerCamelCase : Optional[int] = cls.extractors[extractor_format] return extractor.extract(__magic_name__ , __magic_name__ ) else: warnings.warn( """Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an """ """exception in 3.0.0.""" , category=__magic_name__ , ) for extractor in cls.extractors.values(): if extractor.is_extractable(__magic_name__ ): return extractor.extract(__magic_name__ , __magic_name__ )
287
1
import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('0.12.2'): raise Exception('requires fairseq >= 0.12.2') if version.parse(fairseq.__version__) > version.parse('2'): raise Exception('requires fairseq < v2') logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = 'Hello, World!' lowercase_ = 'en_XX' def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = Path('data_bin' ) __lowerCamelCase : Union[str, Any] = FairseqXmodModel.from_pretrained( model_name_or_path=str(Path(SCREAMING_SNAKE_CASE__ ).parent ) , checkpoint_file=Path(SCREAMING_SNAKE_CASE__ ).name , _name='xmod_base' , arch='xmod_base' , task='multilingual_masked_lm' , data_name_or_path=str(SCREAMING_SNAKE_CASE__ ) , bpe='sentencepiece' , sentencepiece_model=str(Path(SCREAMING_SNAKE_CASE__ ).parent / 'sentencepiece.bpe.model' ) , src_dict=str(data_dir / 'dict.txt' ) , ) xmod.eval() # disable dropout print(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Dict = xmod.model.encoder.sentence_encoder __lowerCamelCase : List[Any] = XmodConfig( vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1e-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , 'bottleneck' , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , ) if classification_head: __lowerCamelCase : List[Any] = xmod.model.classification_heads['mnli'].out_proj.weight.shape[0] print('Our X-MOD config:' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = XmodForSequenceClassification(SCREAMING_SNAKE_CASE__ ) if classification_head else XmodForMaskedLM(SCREAMING_SNAKE_CASE__ ) model.eval() # Now let's copy all the weights. # Embeddings __lowerCamelCase : Optional[int] = xmod_sent_encoder.embed_tokens.weight __lowerCamelCase : Dict = xmod_sent_encoder.embed_positions.weight __lowerCamelCase : List[str] = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them. __lowerCamelCase : Union[str, Any] = xmod_sent_encoder.layernorm_embedding.weight __lowerCamelCase : Union[str, Any] = xmod_sent_encoder.layernorm_embedding.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer __lowerCamelCase : Union[str, Any] = model.roberta.encoder.layer[i] __lowerCamelCase : List[Any] = xmod_sent_encoder.layers[i] # self attention __lowerCamelCase : Optional[Any] = layer.attention.self if not ( xmod_layer.self_attn.k_proj.weight.data.shape == xmod_layer.self_attn.q_proj.weight.data.shape == xmod_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ): raise AssertionError('Dimensions of self-attention weights do not match.' ) __lowerCamelCase : int = xmod_layer.self_attn.q_proj.weight __lowerCamelCase : Any = xmod_layer.self_attn.q_proj.bias __lowerCamelCase : Tuple = xmod_layer.self_attn.k_proj.weight __lowerCamelCase : Optional[int] = xmod_layer.self_attn.k_proj.bias __lowerCamelCase : List[Any] = xmod_layer.self_attn.v_proj.weight __lowerCamelCase : Dict = xmod_layer.self_attn.v_proj.bias # self-attention output __lowerCamelCase : List[str] = layer.attention.output if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape: raise AssertionError('Dimensions of self-attention output weights do not match.' ) __lowerCamelCase : Any = xmod_layer.self_attn.out_proj.weight __lowerCamelCase : int = xmod_layer.self_attn.out_proj.bias __lowerCamelCase : Optional[Any] = xmod_layer.self_attn_layer_norm.weight __lowerCamelCase : Optional[int] = xmod_layer.self_attn_layer_norm.bias # intermediate __lowerCamelCase : List[Any] = layer.intermediate if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('Dimensions of intermediate weights do not match.' ) __lowerCamelCase : Union[str, Any] = xmod_layer.fca.weight __lowerCamelCase : Optional[Any] = xmod_layer.fca.bias # output __lowerCamelCase : Dict = layer.output if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('Dimensions of feed-forward weights do not match.' ) __lowerCamelCase : Dict = xmod_layer.fca.weight __lowerCamelCase : Tuple = xmod_layer.fca.bias __lowerCamelCase : Union[str, Any] = xmod_layer.final_layer_norm.weight __lowerCamelCase : str = xmod_layer.final_layer_norm.bias if bert_output.adapter_layer_norm is not None: __lowerCamelCase : Optional[Any] = xmod_layer.adapter_layer_norm.weight __lowerCamelCase : Optional[int] = xmod_layer.adapter_layer_norm.bias if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ): raise AssertionError('Lists of language adapters do not match.' ) for lang_code, adapter in xmod_layer.adapter_modules.items(): __lowerCamelCase : Tuple = bert_output.adapter_modules[lang_code] __lowerCamelCase : Optional[int] = xmod_layer.adapter_modules[lang_code] __lowerCamelCase : List[Any] = from_adapter.fca.weight __lowerCamelCase : int = from_adapter.fca.bias __lowerCamelCase : Tuple = from_adapter.fca.weight __lowerCamelCase : int = from_adapter.fca.bias # end of layer if xmod_sent_encoder.layer_norm is not None: __lowerCamelCase : Optional[int] = xmod_sent_encoder.layer_norm.weight __lowerCamelCase : Optional[int] = xmod_sent_encoder.layer_norm.bias if classification_head: __lowerCamelCase : Any = xmod.model.classification_heads['mnli'].dense.weight __lowerCamelCase : Dict = xmod.model.classification_heads['mnli'].dense.bias __lowerCamelCase : Tuple = xmod.model.classification_heads['mnli'].out_proj.weight __lowerCamelCase : Any = xmod.model.classification_heads['mnli'].out_proj.bias else: # LM Head __lowerCamelCase : Any = xmod.model.encoder.lm_head.dense.weight __lowerCamelCase : Optional[Any] = xmod.model.encoder.lm_head.dense.bias __lowerCamelCase : Union[str, Any] = xmod.model.encoder.lm_head.layer_norm.weight __lowerCamelCase : Tuple = xmod.model.encoder.lm_head.layer_norm.bias __lowerCamelCase : List[Any] = xmod.model.encoder.lm_head.weight __lowerCamelCase : Union[str, Any] = xmod.model.encoder.lm_head.bias # Let's check that we get the same results. __lowerCamelCase : int = xmod.encode(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) # batch of size 1 model.roberta.set_default_language(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ )[0] if classification_head: __lowerCamelCase : Tuple = xmod.model.classification_heads['mnli'](xmod.extract_features(SCREAMING_SNAKE_CASE__ ) ) else: __lowerCamelCase : Any = xmod.model(SCREAMING_SNAKE_CASE__ , lang_id=[SAMPLE_LANGUAGE] )[0] print(our_output.shape , their_output.shape ) __lowerCamelCase : str = torch.max(torch.abs(our_output - their_output ) ).item() print(f'max_absolute_diff = {max_absolute_diff}' ) # ~ 1e-7 __lowerCamelCase : Optional[int] = torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) print('Do both models output the same tensors?' , '🔥' if success else '💩' ) if not success: raise Exception('Something went wRoNg' ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(parents=SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) print(f'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--xmod_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.' ) parser.add_argument( '--classification_head', action='store_true', help='Whether to convert a final classification head.' ) lowercase_ = parser.parse_args() convert_xmod_checkpoint_to_pytorch( args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
194
import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration lowercase_ = 5_0_0_0_0 lowercase_ = 5_0_0_0 lowercase_ ,lowercase_ = os.path.split(__file__) lowercase_ = os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json')) @get_duration def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for i in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = dataset[i] @get_duration def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[Any] = dataset[i : i + batch_size] @get_duration def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): with dataset.formatted_as(type=SCREAMING_SNAKE_CASE__ ): for i in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = dataset[i] @get_duration def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): with dataset.formatted_as(type=SCREAMING_SNAKE_CASE__ ): for i in range(0 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = dataset[i : i + batch_size] def UpperCamelCase__ ( ): __lowerCamelCase : Union[str, Any] = {'num examples': SPEED_TEST_N_EXAMPLES} __lowerCamelCase : Optional[Any] = [ (read, {'length': SMALL_TEST}), (read, {'length': SPEED_TEST_N_EXAMPLES}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 100}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 1_000}), (read_formatted, {'type': 'numpy', 'length': SMALL_TEST}), (read_formatted, {'type': 'pandas', 'length': SMALL_TEST}), (read_formatted, {'type': 'torch', 'length': SMALL_TEST}), (read_formatted, {'type': 'tensorflow', 'length': SMALL_TEST}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 1_000}), ] __lowerCamelCase : Any = [ (read, {'length': SMALL_TEST}), (read, {'length': SPEED_TEST_N_EXAMPLES}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 100}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 1_000}), (read_formatted, {'type': 'numpy', 'length': SMALL_TEST}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 1_000}), ] with tempfile.TemporaryDirectory() as tmp_dir: print('generating dataset' ) __lowerCamelCase : Optional[int] = datasets.Features( {'list': datasets.Sequence(datasets.Value('float32' ) ), 'numbers': datasets.Value('float32' )} ) __lowerCamelCase : str = generate_example_dataset( os.path.join(SCREAMING_SNAKE_CASE__ , 'dataset.arrow' ) , SCREAMING_SNAKE_CASE__ , num_examples=SCREAMING_SNAKE_CASE__ , seq_shapes={'list': (100,)} , ) print('first set of iterations' ) for func, kwargs in functions: print(func.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : Optional[int] = func(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) print('shuffling dataset' ) __lowerCamelCase : str = dataset.shuffle() print('Second set of iterations (after shuffling' ) for func, kwargs in functions_shuffled: print('shuffled ' , func.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : int = func( SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as f: f.write(json.dumps(SCREAMING_SNAKE_CASE__ ).encode('utf-8' ) ) if __name__ == "__main__": # useful to run the profiler benchmark_iterating()
194
1
import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __lowerCamelCase ( UpperCAmelCase_ : Dict ): """simple docstring""" return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def __lowerCamelCase ( UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int] ): """simple docstring""" a :List[Any] = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue a :List[str] = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) a :Any = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) a :Optional[Any] = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) a :int = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) a :Optional[int] = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) a :List[str] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) a :Any = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) a :Dict = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) a :Union[str, Any] = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) a :Tuple = key.replace('''image_encoder.module''' , '''flava.image_model''' ) a :int = key.replace('''text_encoder.module''' , '''flava.text_model''' ) a :Tuple = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) a :Any = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) a :Union[str, Any] = key.replace('''text_projection''' , '''flava.text_projection''' ) a :Tuple = key.replace('''image_projection''' , '''flava.image_projection''' ) a :List[str] = value.float() for key, value in codebook_state_dict.items(): a :List[Any] = value return upgrade @torch.no_grad() def __lowerCamelCase ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Dict=None ): """simple docstring""" if config_path is not None: a :List[str] = FlavaConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) else: a :Tuple = FlavaConfig() a :List[str] = FlavaForPreTraining(SCREAMING_SNAKE_CASE__ ).eval() a :List[Any] = convert_dalle_checkpoint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , save_checkpoint=SCREAMING_SNAKE_CASE__ ) if os.path.exists(SCREAMING_SNAKE_CASE__ ): a :Tuple = torch.load(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' ) else: a :Any = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' ) a :str = upgrade_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) hf_model.load_state_dict(SCREAMING_SNAKE_CASE__ ) a :Optional[Any] = hf_model.state_dict() a :List[Any] = count_parameters(SCREAMING_SNAKE_CASE__ ) a :Tuple = count_parameters(SCREAMING_SNAKE_CASE__ ) + count_parameters(SCREAMING_SNAKE_CASE__ ) assert torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": snake_case : int = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to flava checkpoint''') parser.add_argument('''--codebook_path''', default=None, type=str, help='''Path to flava codebook checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') snake_case : Dict = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
94
'''simple docstring''' import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSequenceClassification, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, TapexTokenizer, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.17.0.dev0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") snake_case_ : List[str] = logging.getLogger(__name__) @dataclass class __a : __a : Optional[str] = field( default="tab_fact" , metadata={"help": "The name of the dataset to use (via the datasets library)."} ) __a : Optional[str] = field( default="tab_fact" , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} , ) __a : int = field( default=1_024 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __a : bool = field( default=lowerCamelCase , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) __a : bool = field( default=lowerCamelCase , metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } , ) __a : Optional[int] = field( default=lowerCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) __a : Optional[int] = field( default=lowerCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) __a : Optional[int] = field( default=lowerCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } , ) __a : Optional[str] = field( default=lowerCamelCase , metadata={"help": "A csv or a json file containing the training data."} ) __a : Optional[str] = field( default=lowerCamelCase , metadata={"help": "A csv or a json file containing the validation data."} ) __a : Optional[str] = field(default=lowerCamelCase , metadata={"help": "A csv or a json file containing the test data."} ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" if self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError('''Need either a GLUE task, a training/validation file or a dataset name.''' ) else: UpperCAmelCase_ : Dict = self.train_file.split('''.''' )[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." UpperCAmelCase_ : Union[str, Any] = self.validation_file.split('''.''' )[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class __a : __a : str = field( default=lowerCamelCase , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __a : Optional[str] = field( default=lowerCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __a : Optional[str] = field( default=lowerCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) __a : Optional[str] = field( default=lowerCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) __a : bool = field( default=lowerCamelCase , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) __a : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) __a : bool = field( default=lowerCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) def lowerCamelCase_ ( ) -> List[Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. UpperCAmelCase_ : Dict = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Tuple = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : int = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', handlers=[logging.StreamHandler(sys.stdout )], ) UpperCAmelCase_ : List[str] = training_args.get_process_log_level() logger.setLevel(SCREAMING_SNAKE_CASE__ ) datasets.utils.logging.set_verbosity(SCREAMING_SNAKE_CASE__ ) transformers.utils.logging.set_verbosity(SCREAMING_SNAKE_CASE__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(F"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. UpperCAmelCase_ : Tuple = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: UpperCAmelCase_ : Optional[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. UpperCAmelCase_ : List[Any] = load_dataset( data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. UpperCAmelCase_ : Dict = {'''train''': data_args.train_file, '''validation''': data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: UpperCAmelCase_ : Dict = data_args.train_file.split('''.''' )[-1] UpperCAmelCase_ : Union[str, Any] = data_args.test_file.split('''.''' )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." UpperCAmelCase_ : int = data_args.test_file else: raise ValueError('''Need either a GLUE task or a test file for `do_predict`.''' ) for key in data_files.keys(): logger.info(F"""load a local file for {key}: {data_files[key]}""" ) if data_args.train_file.endswith('''.csv''' ): # Loading a dataset from local csv files UpperCAmelCase_ : List[Any] = load_dataset('''csv''', data_files=SCREAMING_SNAKE_CASE__, cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files UpperCAmelCase_ : int = load_dataset('''json''', data_files=SCREAMING_SNAKE_CASE__, cache_dir=model_args.cache_dir ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels UpperCAmelCase_ : Optional[Any] = raw_datasets['''train'''].features['''label'''].names UpperCAmelCase_ : List[str] = len(SCREAMING_SNAKE_CASE__ ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCAmelCase_ : Tuple = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=SCREAMING_SNAKE_CASE__, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) # load tapex tokenizer UpperCAmelCase_ : str = TapexTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, add_prefix_space=SCREAMING_SNAKE_CASE__, ) UpperCAmelCase_ : Union[str, Any] = BartForSequenceClassification.from_pretrained( model_args.model_name_or_path, from_tf=bool('''.ckpt''' in model_args.model_name_or_path ), config=SCREAMING_SNAKE_CASE__, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) # Padding strategy if data_args.pad_to_max_length: UpperCAmelCase_ : Optional[int] = '''max_length''' else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch UpperCAmelCase_ : Dict = False # Some models have set the order of the labels to use, so let's make sure we do use it. UpperCAmelCase_ : Tuple = {'''Refused''': 0, '''Entailed''': 1} UpperCAmelCase_ : Tuple = {0: '''Refused''', 1: '''Entailed'''} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( F"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) UpperCAmelCase_ : int = min(data_args.max_seq_length, tokenizer.model_max_length ) def preprocess_tabfact_function(SCREAMING_SNAKE_CASE__ : Optional[int] ): # Tokenize the texts def _convert_table_text_to_pandas(SCREAMING_SNAKE_CASE__ : Tuple ): UpperCAmelCase_ : List[str] = [_table_row.split('''#''' ) for _table_row in _table_text.strip('''\n''' ).split('''\n''' )] UpperCAmelCase_ : Any = pd.DataFrame.from_records(_table_content[1:], columns=_table_content[0] ) return _table_pd UpperCAmelCase_ : Optional[Any] = examples['''statement'''] UpperCAmelCase_ : Union[str, Any] = list(map(_convert_table_text_to_pandas, examples['''table_text'''] ) ) UpperCAmelCase_ : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, padding=SCREAMING_SNAKE_CASE__, max_length=SCREAMING_SNAKE_CASE__, truncation=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = examples['''label'''] return result with training_args.main_process_first(desc='''dataset map pre-processing''' ): UpperCAmelCase_ : List[str] = raw_datasets.map( SCREAMING_SNAKE_CASE__, batched=SCREAMING_SNAKE_CASE__, load_from_cache_file=not data_args.overwrite_cache, desc='''Running tokenizer on dataset''', ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError('''--do_train requires a train dataset''' ) UpperCAmelCase_ : Any = raw_datasets['''train'''] if data_args.max_train_samples is not None: UpperCAmelCase_ : Dict = train_dataset.select(range(data_args.max_train_samples ) ) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError('''--do_eval requires a validation dataset''' ) UpperCAmelCase_ : str = raw_datasets['''validation'''] if data_args.max_eval_samples is not None: UpperCAmelCase_ : Any = eval_dataset.select(range(data_args.max_eval_samples ) ) if training_args.do_predict or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError('''--do_predict requires a test dataset''' ) UpperCAmelCase_ : Dict = raw_datasets['''test'''] if data_args.max_predict_samples is not None: UpperCAmelCase_ : List[str] = predict_dataset.select(range(data_args.max_predict_samples ) ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(SCREAMING_SNAKE_CASE__ ) ), 3 ): logger.info(F"""Sample {index} of the training set: {train_dataset[index]}.""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(SCREAMING_SNAKE_CASE__ : EvalPrediction ): UpperCAmelCase_ : Any = p.predictions[0] if isinstance(p.predictions, SCREAMING_SNAKE_CASE__ ) else p.predictions UpperCAmelCase_ : Optional[int] = np.argmax(SCREAMING_SNAKE_CASE__, axis=1 ) return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: UpperCAmelCase_ : Optional[Any] = default_data_collator elif training_args.fpaa: UpperCAmelCase_ : str = DataCollatorWithPadding(SCREAMING_SNAKE_CASE__, pad_to_multiple_of=8 ) else: UpperCAmelCase_ : List[Any] = None # Initialize our Trainer UpperCAmelCase_ : int = Trainer( model=SCREAMING_SNAKE_CASE__, args=SCREAMING_SNAKE_CASE__, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, compute_metrics=SCREAMING_SNAKE_CASE__, tokenizer=SCREAMING_SNAKE_CASE__, data_collator=SCREAMING_SNAKE_CASE__, ) # Training if training_args.do_train: UpperCAmelCase_ : Dict = None if training_args.resume_from_checkpoint is not None: UpperCAmelCase_ : Union[str, Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: UpperCAmelCase_ : Optional[int] = last_checkpoint UpperCAmelCase_ : Dict = trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Any = train_result.metrics UpperCAmelCase_ : Tuple = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(SCREAMING_SNAKE_CASE__ ) ) UpperCAmelCase_ : List[Any] = min(SCREAMING_SNAKE_CASE__, len(SCREAMING_SNAKE_CASE__ ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics('''train''', SCREAMING_SNAKE_CASE__ ) trainer.save_metrics('''train''', SCREAMING_SNAKE_CASE__ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) UpperCAmelCase_ : Union[str, Any] = trainer.evaluate(eval_dataset=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Tuple = min(SCREAMING_SNAKE_CASE__, len(SCREAMING_SNAKE_CASE__ ) ) trainer.log_metrics('''eval''', SCREAMING_SNAKE_CASE__ ) trainer.save_metrics('''eval''', SCREAMING_SNAKE_CASE__ ) if training_args.do_predict: logger.info('''*** Predict ***''' ) # Removing the `label` columns because it contains -1 and Trainer won't like that. UpperCAmelCase_ : Optional[int] = predict_dataset.remove_columns('''label''' ) UpperCAmelCase_ : Union[str, Any] = trainer.predict(SCREAMING_SNAKE_CASE__, metric_key_prefix='''predict''' ).predictions UpperCAmelCase_ : Any = np.argmax(SCREAMING_SNAKE_CASE__, axis=1 ) UpperCAmelCase_ : int = os.path.join(training_args.output_dir, '''predict_results_tabfact.txt''' ) if trainer.is_world_process_zero(): with open(SCREAMING_SNAKE_CASE__, '''w''' ) as writer: logger.info('''***** Predict Results *****''' ) writer.write('''index\tprediction\n''' ) for index, item in enumerate(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : Dict = label_list[item] writer.write(F"""{index}\t{item}\n""" ) UpperCAmelCase_ : Optional[int] = {'''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''text-classification'''} if training_args.push_to_hub: trainer.push_to_hub(**SCREAMING_SNAKE_CASE__ ) else: trainer.create_model_card(**SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
125
0
def SCREAMING_SNAKE_CASE__ ( __a , __a ): if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive' ) snake_case_ : str = str(bin(lowercase__ ) )[2:] # remove the leading "0b" snake_case_ : Union[str, Any] = str(bin(lowercase__ ) )[2:] # remove the leading "0b" snake_case_ : str = max(len(lowercase__ ) , len(lowercase__ ) ) return "0b" + "".join( str(int(char_a == '1' and char_b == '1' ) ) for char_a, char_b in zip(a_binary.zfill(lowercase__ ) , b_binary.zfill(lowercase__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
356
def SCREAMING_SNAKE_CASE__ ( __a , __a = False ): if not isinstance(__a , __a ): snake_case_ : str = f"""Expected string as input, found {type(__a )}""" raise ValueError(__a ) if not isinstance(__a , __a ): snake_case_ : int = f"""Expected boolean as use_pascal parameter, found {type(__a )}""" raise ValueError(__a ) snake_case_ : Union[str, Any] = input_str.split('_' ) snake_case_ : int = 0 if use_pascal else 1 snake_case_ : List[Any] = words[start_index:] snake_case_ : str = [word[0].upper() + word[1:] for word in words_to_capitalize] snake_case_ : Optional[Any] = '' if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
88
0
'''simple docstring''' import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class __UpperCamelCase ( lowerCamelCase__ ): @require_torch def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =''' from transformers import BertConfig, BertModel, BertTokenizer, pipeline ''' lowerCamelCase_ =''' mname = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task="fill-mask", model=mname) print("success") ''' lowerCamelCase_ =''' import socket def offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet") socket.socket = offline_socket ''' # Force fetching the files so that we can use the cache lowerCamelCase_ ='''hf-internal-testing/tiny-random-bert''' BertConfig.from_pretrained(lowerCAmelCase ) BertModel.from_pretrained(lowerCAmelCase ) BertTokenizer.from_pretrained(lowerCAmelCase ) pipeline(task='''fill-mask''', model=lowerCAmelCase ) # baseline - just load from_pretrained with normal network lowerCamelCase_ =[sys.executable, '''-c''', '''\n'''.join([load, run, mock] )] # should succeed lowerCamelCase_ =self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files lowerCamelCase_ ='''1''' lowerCamelCase_ =subprocess.run(lowerCAmelCase, env=lowerCAmelCase, check=lowerCAmelCase, capture_output=lowerCAmelCase ) self.assertEqual(result.returncode, 0, result.stderr ) self.assertIn('''success''', result.stdout.decode() ) @require_torch def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =''' from transformers import BertConfig, BertModel, BertTokenizer, pipeline ''' lowerCamelCase_ =''' mname = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task="fill-mask", model=mname) print("success") ''' lowerCamelCase_ =''' import socket def offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet") socket.socket = offline_socket ''' # Force fetching the files so that we can use the cache lowerCamelCase_ ='''hf-internal-testing/tiny-random-bert''' BertConfig.from_pretrained(lowerCAmelCase ) BertModel.from_pretrained(lowerCAmelCase ) BertTokenizer.from_pretrained(lowerCAmelCase ) pipeline(task='''fill-mask''', model=lowerCAmelCase ) # baseline - just load from_pretrained with normal network lowerCamelCase_ =[sys.executable, '''-c''', '''\n'''.join([load, run, mock] )] # should succeed lowerCamelCase_ =self.get_env() lowerCamelCase_ =subprocess.run(lowerCAmelCase, env=lowerCAmelCase, check=lowerCAmelCase, capture_output=lowerCAmelCase ) self.assertEqual(result.returncode, 0, result.stderr ) self.assertIn('''success''', result.stdout.decode() ) @require_torch def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =''' from transformers import BertConfig, BertModel, BertTokenizer ''' lowerCamelCase_ =''' mname = "hf-internal-testing/tiny-random-bert-sharded" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) print("success") ''' lowerCamelCase_ =''' import socket def offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled") socket.socket = offline_socket ''' # baseline - just load from_pretrained with normal network lowerCamelCase_ =[sys.executable, '''-c''', '''\n'''.join([load, run] )] # should succeed lowerCamelCase_ =self.get_env() lowerCamelCase_ =subprocess.run(lowerCAmelCase, env=lowerCAmelCase, check=lowerCAmelCase, capture_output=lowerCAmelCase ) self.assertEqual(result.returncode, 0, result.stderr ) self.assertIn('''success''', result.stdout.decode() ) # next emulate no network lowerCamelCase_ =[sys.executable, '''-c''', '''\n'''.join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files lowerCamelCase_ ='''1''' lowerCamelCase_ =subprocess.run(lowerCAmelCase, env=lowerCAmelCase, check=lowerCAmelCase, capture_output=lowerCAmelCase ) self.assertEqual(result.returncode, 0, result.stderr ) self.assertIn('''success''', result.stdout.decode() ) @require_torch def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =''' from transformers import pipeline ''' lowerCamelCase_ =''' mname = "hf-internal-testing/tiny-random-bert" pipe = pipeline(model=mname) ''' lowerCamelCase_ =''' import socket def offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled") socket.socket = offline_socket ''' lowerCamelCase_ =self.get_env() lowerCamelCase_ ='''1''' lowerCamelCase_ =[sys.executable, '''-c''', '''\n'''.join([load, mock, run] )] lowerCamelCase_ =subprocess.run(lowerCAmelCase, env=lowerCAmelCase, check=lowerCAmelCase, capture_output=lowerCAmelCase ) self.assertEqual(result.returncode, 1, result.stderr ) self.assertIn( '''You cannot infer task automatically within `pipeline` when using offline mode''', result.stderr.decode().replace('''\n''', '''''' ), ) @require_torch def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =''' from transformers import AutoModel ''' lowerCamelCase_ =''' mname = "hf-internal-testing/test_dynamic_model" AutoModel.from_pretrained(mname, trust_remote_code=True) print("success") ''' # baseline - just load from_pretrained with normal network lowerCamelCase_ =[sys.executable, '''-c''', '''\n'''.join([load, run] )] # should succeed lowerCamelCase_ =self.get_env() lowerCamelCase_ =subprocess.run(lowerCAmelCase, env=lowerCAmelCase, check=lowerCAmelCase, capture_output=lowerCAmelCase ) self.assertEqual(result.returncode, 0, result.stderr ) self.assertIn('''success''', result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files lowerCamelCase_ ='''1''' lowerCamelCase_ =subprocess.run(lowerCAmelCase, env=lowerCAmelCase, check=lowerCAmelCase, capture_output=lowerCAmelCase ) self.assertEqual(result.returncode, 0, result.stderr ) self.assertIn('''success''', result.stdout.decode() )
75
'''simple docstring''' 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 , lowerCamelCase__ , lowerCamelCase__=13 , lowerCamelCase__=30 , lowerCamelCase__=2 , lowerCamelCase__=3 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=32 , lowerCamelCase__=5 , lowerCamelCase__=4 , lowerCamelCase__=37 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=10 , lowerCamelCase__=0.02 , lowerCamelCase__=3 , lowerCamelCase__=None , lowerCamelCase__=2 , ) -> Optional[int]: '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = image_size lowercase__ = patch_size lowercase__ = num_channels lowercase__ = is_training lowercase__ = use_labels 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__ = type_sequence_label_size lowercase__ = initializer_range lowercase__ = scope lowercase__ = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) lowercase__ = (image_size // patch_size) ** 2 lowercase__ = num_patches + 2 def A__ ( self ) -> Any: '''simple docstring''' 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.type_sequence_label_size ) lowercase__ = self.get_config() return config, pixel_values, labels def A__ ( self ) -> Optional[Any]: '''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=lowerCamelCase__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def A__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Dict: '''simple docstring''' lowercase__ = DeiTModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() lowercase__ = model(lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: '''simple docstring''' lowercase__ = DeiTForMaskedImageModeling(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() lowercase__ = model(lowerCamelCase__ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images lowercase__ = 1 lowercase__ = DeiTForMaskedImageModeling(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() lowercase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowercase__ = model(lowerCamelCase__ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def A__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> str: '''simple docstring''' lowercase__ = self.type_sequence_label_size lowercase__ = DeiTForImageClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() lowercase__ = model(lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowercase__ = 1 lowercase__ = DeiTForImageClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() lowercase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowercase__ = model(lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def A__ ( self ) -> List[str]: '''simple docstring''' 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 ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase : int = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowerCamelCase : Tuple = ( { """feature-extraction""": DeiTModel, """image-classification""": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowerCamelCase : Any = False lowerCamelCase : str = False lowerCamelCase : str = False def A__ ( self ) -> List[str]: '''simple docstring''' lowercase__ = DeiTModelTester(self ) lowercase__ = ConfigTester(self , config_class=lowerCamelCase__ , has_text_modality=lowerCamelCase__ , hidden_size=37 ) def A__ ( self ) -> str: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""DeiT does not use inputs_embeds""" ) def A__ ( self ) -> Union[str, Any]: '''simple docstring''' pass def A__ ( self ) -> Any: '''simple docstring''' lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(lowerCamelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowercase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase__ , nn.Linear ) ) def A__ ( self ) -> Union[str, Any]: '''simple docstring''' lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(lowerCamelCase__ ) 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] , lowerCamelCase__ ) def A__ ( self ) -> int: '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def A__ ( self ) -> List[Any]: '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase__ ) def A__ ( self ) -> Union[str, Any]: '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__ ) def A__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=False ) -> Dict: '''simple docstring''' lowercase__ = super()._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ , return_labels=lowerCamelCase__ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def A__ ( self ) -> Any: '''simple docstring''' 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: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowerCamelCase__ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue lowercase__ = model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.train() lowercase__ = self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ , return_labels=lowerCamelCase__ ) lowercase__ = model(**lowerCamelCase__ ).loss loss.backward() def A__ ( self ) -> int: '''simple docstring''' 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(lowerCamelCase__ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue lowercase__ = model_class(lowerCamelCase__ ) model.gradient_checkpointing_enable() model.to(lowerCamelCase__ ) model.train() lowercase__ = self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ , return_labels=lowerCamelCase__ ) lowercase__ = model(**lowerCamelCase__ ).loss loss.backward() def A__ ( self ) -> int: '''simple docstring''' 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(lowerCamelCase__ ), *get_values(lowerCamelCase__ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): 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(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.train() lowercase__ = self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ , return_labels=lowerCamelCase__ ) 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=lowerCamelCase__ ) as warning_list: lowercase__ = model(**lowerCamelCase__ ).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 A__ ( self ) -> Any: '''simple docstring''' for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ = DeiTModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) def _A ( ): lowercase__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class A ( unittest.TestCase ): @cached_property def A__ ( self ) -> int: '''simple docstring''' return ( DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224""" ) if is_vision_available() else None ) @slow def A__ ( self ) -> Optional[int]: '''simple docstring''' lowercase__ = DeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224""" ).to( lowerCamelCase__ ) lowercase__ = self.default_image_processor lowercase__ = prepare_img() lowercase__ = image_processor(images=lowerCamelCase__ , return_tensors="""pt""" ).to(lowerCamelCase__ ) # forward pass with torch.no_grad(): lowercase__ = model(**lowerCamelCase__ ) # verify the logits lowercase__ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase__ ) lowercase__ = torch.tensor([-1.02_66, 0.19_12, -1.28_61] ).to(lowerCamelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase__ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def A__ ( self ) -> List[Any]: '''simple docstring''' lowercase__ = DeiTModel.from_pretrained( """facebook/deit-base-distilled-patch16-224""" , torch_dtype=torch.floataa , device_map="""auto""" ) lowercase__ = self.default_image_processor lowercase__ = prepare_img() lowercase__ = image_processor(images=lowerCamelCase__ , return_tensors="""pt""" ) lowercase__ = inputs.pixel_values.to(lowerCamelCase__ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): lowercase__ = model(lowerCamelCase__ )
164
0
"""simple docstring""" from ....utils import logging A_ : List[str] = logging.get_logger(__name__) class a_ ( snake_case_ ): '''simple docstring''' def __init__(self, lowerCamelCase_, lowerCamelCase_=None, lowerCamelCase_=2_0_4_8 ): '''simple docstring''' lowerCamelCase__ : Optional[Any] = config.__dict__ lowerCamelCase__ : str = modal_hidden_size if num_labels: lowerCamelCase__ : List[str] = num_labels
316
"""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
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, 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 _a ( snake_case__ , unittest.TestCase ): __a : Union[str, Any] = KandinskyVaaControlnetImgaImgPipeline __a : List[Any] = ["image_embeds", "negative_image_embeds", "image", "hint"] __a : List[str] = ["image_embeds", "negative_image_embeds", "image", "hint"] __a : Dict = [ "generator", "height", "width", "strength", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] __a : str = False @property def A ( self : Tuple ): '''simple docstring''' return 32 @property def A ( self : List[Any] ): '''simple docstring''' return 32 @property def A ( self : Dict ): '''simple docstring''' return self.time_input_dim @property def A ( self : int ): '''simple docstring''' return self.time_input_dim * 4 @property def A ( self : Optional[int] ): '''simple docstring''' return 100 @property def A ( self : int ): '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase = { "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 = UNetaDConditionModel(**snake_case__ ) return model @property def A ( self : 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 A ( self : int ): '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase = VQModel(**self.dummy_movq_kwargs ) return model def A ( self : Dict ): '''simple docstring''' UpperCAmelCase = self.dummy_unet UpperCAmelCase = self.dummy_movq UpperCAmelCase = { "num_train_timesteps": 1_000, "beta_schedule": "linear", "beta_start": 0.0_0085, "beta_end": 0.012, "clip_sample": False, "set_alpha_to_one": False, "steps_offset": 0, "prediction_type": "epsilon", "thresholding": False, } UpperCAmelCase = DDIMScheduler(**snake_case__ ) UpperCAmelCase = { "unet": unet, "scheduler": scheduler, "movq": movq, } return components def A ( self : Union[str, Any] , lowercase : str , lowercase : str=0 ): '''simple docstring''' UpperCAmelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(snake_case__ ) ).to(snake_case__ ) UpperCAmelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( snake_case__ ) # create init_image UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(snake_case__ ) ).to(snake_case__ ) UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCAmelCase = Image.fromarray(np.uinta(snake_case__ ) ).convert('''RGB''' ).resize((256, 256) ) # create hint UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(snake_case__ ) ).to(snake_case__ ) if str(snake_case__ ).startswith('''mps''' ): UpperCAmelCase = torch.manual_seed(snake_case__ ) else: UpperCAmelCase = torch.Generator(device=snake_case__ ).manual_seed(snake_case__ ) UpperCAmelCase = { "image": init_image, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "hint": hint, "generator": generator, "height": 64, "width": 64, "num_inference_steps": 10, "guidance_scale": 7.0, "strength": 0.2, "output_type": "np", } return inputs def A ( self : Optional[Any] ): '''simple docstring''' UpperCAmelCase = "cpu" UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = self.pipeline_class(**snake_case__ ) UpperCAmelCase = pipe.to(snake_case__ ) pipe.set_progress_bar_config(disable=snake_case__ ) UpperCAmelCase = pipe(**self.get_dummy_inputs(snake_case__ ) ) UpperCAmelCase = output.images UpperCAmelCase = pipe( **self.get_dummy_inputs(snake_case__ ) , return_dict=snake_case__ , )[0] UpperCAmelCase = image[0, -3:, -3:, -1] UpperCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase = np.array( [0.5498_5034, 0.5550_9365, 0.5256_1504, 0.557_0494, 0.559_3818, 0.526_3979, 0.5028_5643, 0.506_9846, 0.5119_6736] ) 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 _a ( unittest.TestCase ): def A ( self : str ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def A ( self : int ): '''simple docstring''' UpperCAmelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy''' ) UpperCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) UpperCAmelCase = init_image.resize((512, 512) ) UpperCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/hint_image_cat.png''' ) UpperCAmelCase = torch.from_numpy(np.array(snake_case__ ) ).float() / 255.0 UpperCAmelCase = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) UpperCAmelCase = "A robot, 4k photo" UpperCAmelCase = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(snake_case__ ) UpperCAmelCase = KandinskyVaaControlnetImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-controlnet-depth''' , torch_dtype=torch.floataa ) UpperCAmelCase = pipeline.to(snake_case__ ) pipeline.set_progress_bar_config(disable=snake_case__ ) UpperCAmelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) UpperCAmelCase = pipe_prior( snake_case__ , image=snake_case__ , strength=0.85 , generator=snake_case__ , negative_prompt='''''' , ).to_tuple() UpperCAmelCase = pipeline( image=snake_case__ , image_embeds=snake_case__ , negative_image_embeds=snake_case__ , hint=snake_case__ , generator=snake_case__ , num_inference_steps=100 , height=512 , width=512 , strength=0.5 , output_type='''np''' , ) UpperCAmelCase = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(snake_case__ , snake_case__ )
34
"""simple docstring""" import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class lowercase__ ( unittest.TestCase ): _UpperCAmelCase :Union[str, Any] = JukeboxTokenizer _UpperCAmelCase :List[Any] = { "artist": "Zac Brown Band", "genres": "Country", "lyrics": "I met a traveller from an antique land,\n Who said \"Two vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away\n ", } @require_torch def UpperCAmelCase__ ( self : Dict ): import torch lowerCamelCase_ : Any =JukeboxTokenizer.from_pretrained("openai/jukebox-1b-lyrics" ) lowerCamelCase_ : List[Any] =tokenizer(**self.metas )["input_ids"] # fmt: off lowerCamelCase_ : Union[str, Any] =[ torch.tensor([[ 0, 0, 0, 7169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def UpperCAmelCase__ ( self : str ): import torch lowerCamelCase_ : Any =JukeboxTokenizer.from_pretrained("openai/jukebox-5b-lyrics" ) lowerCamelCase_ : Optional[int] =tokenizer(**self.metas )["input_ids"] # fmt: off lowerCamelCase_ : Union[str, Any] =[ torch.tensor([[ 0, 0, 0, 1069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
144
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.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input A : Union[str, Any] = "Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine" def a__ ( ): SCREAMING_SNAKE_CASE_ = _ask_options( "In which compute environment are you running?" , ["This machine", "AWS (Amazon SageMaker)"] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: SCREAMING_SNAKE_CASE_ = get_sagemaker_input() else: SCREAMING_SNAKE_CASE_ = get_cluster_input() return config def a__ ( __UpperCamelCase=None ): if subparsers is not None: SCREAMING_SNAKE_CASE_ = subparsers.add_parser("config" , description=__UpperCamelCase ) else: SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser("Accelerate config command" , description=__UpperCamelCase ) parser.add_argument( "--config_file" , default=__UpperCamelCase , 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=__UpperCamelCase ) return parser def a__ ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = get_user_input() if args.config_file is not None: SCREAMING_SNAKE_CASE_ = args.config_file else: if not os.path.isdir(__UpperCamelCase ): os.makedirs(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = default_yaml_config_file if config_file.endswith(".json" ): config.to_json_file(__UpperCamelCase ) else: config.to_yaml_file(__UpperCamelCase ) print(F'''accelerate configuration saved at {config_file}''' ) def a__ ( ): SCREAMING_SNAKE_CASE_ = config_command_parser() SCREAMING_SNAKE_CASE_ = parser.parse_args() config_command(__UpperCamelCase ) if __name__ == "__main__": main()
305
import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import os from flax.core.frozen_dict import unfreeze from flax.traverse_util import flatten_dict from transformers import FlaxBertModel A : Union[str, Any] = "0.12" # assumed parallelism: 8 @require_flax @is_staging_test class lowerCamelCase (unittest.TestCase ): """simple docstring""" @classmethod def __A ( cls : Any ) -> Dict: SCREAMING_SNAKE_CASE_ = TOKEN HfFolder.save_token(__magic_name__ ) @classmethod def __A ( cls : Optional[int] ) -> Tuple: try: delete_repo(token=cls._token , repo_id="test-model-flax" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-model-flax-org" ) except HTTPError: pass def __A ( self : str ) -> str: SCREAMING_SNAKE_CASE_ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) SCREAMING_SNAKE_CASE_ = FlaxBertModel(__magic_name__ ) model.push_to_hub("test-model-flax" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE_ = FlaxBertModel.from_pretrained(F'''{USER}/test-model-flax''' ) SCREAMING_SNAKE_CASE_ = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE_ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE_ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__magic_name__ , 1e-3 , msg=F'''{key} not identical''' ) # Reset repo delete_repo(token=self._token , repo_id="test-model-flax" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(__magic_name__ , repo_id="test-model-flax" , push_to_hub=__magic_name__ , use_auth_token=self._token ) SCREAMING_SNAKE_CASE_ = FlaxBertModel.from_pretrained(F'''{USER}/test-model-flax''' ) SCREAMING_SNAKE_CASE_ = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE_ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE_ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__magic_name__ , 1e-3 , msg=F'''{key} not identical''' ) def __A ( self : int ) -> Tuple: SCREAMING_SNAKE_CASE_ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) SCREAMING_SNAKE_CASE_ = FlaxBertModel(__magic_name__ ) model.push_to_hub("valid_org/test-model-flax-org" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE_ = FlaxBertModel.from_pretrained("valid_org/test-model-flax-org" ) SCREAMING_SNAKE_CASE_ = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE_ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE_ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__magic_name__ , 1e-3 , msg=F'''{key} not identical''' ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-model-flax-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained( __magic_name__ , repo_id="valid_org/test-model-flax-org" , push_to_hub=__magic_name__ , use_auth_token=self._token ) SCREAMING_SNAKE_CASE_ = FlaxBertModel.from_pretrained("valid_org/test-model-flax-org" ) SCREAMING_SNAKE_CASE_ = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE_ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE_ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__magic_name__ , 1e-3 , msg=F'''{key} not identical''' ) def a__ ( __UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = flatten_dict(modela.params ) SCREAMING_SNAKE_CASE_ = flatten_dict(modela.params ) for key in flat_params_a.keys(): if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1E-4: SCREAMING_SNAKE_CASE_ = False return models_are_equal @require_flax class lowerCamelCase (unittest.TestCase ): """simple docstring""" def __A ( self : str ) -> Dict: SCREAMING_SNAKE_CASE_ = BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only" ) SCREAMING_SNAKE_CASE_ = FlaxBertModel(__magic_name__ ) SCREAMING_SNAKE_CASE_ = "bert" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(__magic_name__ , __magic_name__ ) ) with self.assertRaises(__magic_name__ ): SCREAMING_SNAKE_CASE_ = FlaxBertModel.from_pretrained(__magic_name__ ) SCREAMING_SNAKE_CASE_ = FlaxBertModel.from_pretrained(__magic_name__ , subfolder=__magic_name__ ) self.assertTrue(check_models_equal(__magic_name__ , __magic_name__ ) ) def __A ( self : Optional[Any] ) -> Tuple: SCREAMING_SNAKE_CASE_ = BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only" ) SCREAMING_SNAKE_CASE_ = FlaxBertModel(__magic_name__ ) SCREAMING_SNAKE_CASE_ = "bert" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(__magic_name__ , __magic_name__ ) , max_shard_size="10KB" ) with self.assertRaises(__magic_name__ ): SCREAMING_SNAKE_CASE_ = FlaxBertModel.from_pretrained(__magic_name__ ) SCREAMING_SNAKE_CASE_ = FlaxBertModel.from_pretrained(__magic_name__ , subfolder=__magic_name__ ) self.assertTrue(check_models_equal(__magic_name__ , __magic_name__ ) ) def __A ( self : Optional[int] ) -> Dict: SCREAMING_SNAKE_CASE_ = "bert" SCREAMING_SNAKE_CASE_ = "hf-internal-testing/tiny-random-bert-subfolder" with self.assertRaises(__magic_name__ ): SCREAMING_SNAKE_CASE_ = FlaxBertModel.from_pretrained(__magic_name__ ) SCREAMING_SNAKE_CASE_ = FlaxBertModel.from_pretrained(__magic_name__ , subfolder=__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def __A ( self : List[str] ) -> Dict: SCREAMING_SNAKE_CASE_ = "bert" SCREAMING_SNAKE_CASE_ = "hf-internal-testing/tiny-random-bert-sharded-subfolder" with self.assertRaises(__magic_name__ ): SCREAMING_SNAKE_CASE_ = FlaxBertModel.from_pretrained(__magic_name__ ) SCREAMING_SNAKE_CASE_ = FlaxBertModel.from_pretrained(__magic_name__ , subfolder=__magic_name__ ) self.assertIsNotNone(__magic_name__ )
305
1
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetrImageProcessor class UpperCAmelCase_ ( unittest.TestCase ): def __init__( self : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : Any=3_0 , UpperCAmelCase__ : str=4_0_0 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[int]=1 / 2_5_5 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : List[Any]=[0.5, 0.5, 0.5] , UpperCAmelCase__ : Any=[0.5, 0.5, 0.5] , UpperCAmelCase__ : Optional[int]=True , ) -> Any: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p lowerCAmelCase = size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3} lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = num_channels lowerCAmelCase = min_resolution lowerCAmelCase = max_resolution lowerCAmelCase = do_resize lowerCAmelCase = size lowerCAmelCase = do_rescale lowerCAmelCase = rescale_factor lowerCAmelCase = do_normalize lowerCAmelCase = image_mean lowerCAmelCase = image_std lowerCAmelCase = do_pad def __UpperCAmelCase ( self : int ) -> Dict: return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def __UpperCAmelCase ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict=False ) -> str: if not batched: lowerCAmelCase = image_inputs[0] if isinstance(UpperCAmelCase__ , Image.Image ): lowerCAmelCase , lowerCAmelCase = image.size else: lowerCAmelCase , lowerCAmelCase = image.shape[1], image.shape[2] if w < h: lowerCAmelCase = int(self.size['shortest_edge'] * h / w ) lowerCAmelCase = self.size['shortest_edge'] elif w > h: lowerCAmelCase = self.size['shortest_edge'] lowerCAmelCase = int(self.size['shortest_edge'] * w / h ) else: lowerCAmelCase = self.size['shortest_edge'] lowerCAmelCase = self.size['shortest_edge'] else: lowerCAmelCase = [] for image in image_inputs: lowerCAmelCase , lowerCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) lowerCAmelCase = max(UpperCAmelCase__ , key=lambda UpperCAmelCase__ : item[0] )[0] lowerCAmelCase = max(UpperCAmelCase__ , key=lambda UpperCAmelCase__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class UpperCAmelCase_ ( __lowercase , unittest.TestCase ): lowerCamelCase : List[str] = DetrImageProcessor if is_vision_available() else None def __UpperCAmelCase ( self : Tuple ) -> List[Any]: lowerCAmelCase = DetrImageProcessingTester(self ) @property def __UpperCAmelCase ( self : Optional[int] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self : str ) -> str: lowerCAmelCase = 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_rescale' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , 'rescale_factor' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , 'do_resize' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , 'size' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , 'do_pad' ) ) def __UpperCAmelCase ( self : Optional[int] ) -> List[str]: lowerCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , UpperCAmelCase__ ) lowerCAmelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=UpperCAmelCase__ ) self.assertEqual(image_processor.size , {'shortest_edge': 4_2, 'longest_edge': 8_4} ) self.assertEqual(image_processor.do_pad , UpperCAmelCase__ ) def __UpperCAmelCase ( self : Union[str, Any] ) -> Any: pass def __UpperCAmelCase ( self : Dict ) -> str: # Initialize image_processing lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase = 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 = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values lowerCAmelCase , lowerCAmelCase = self.image_processor_tester.get_expected_values(UpperCAmelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase , lowerCAmelCase = self.image_processor_tester.get_expected_values(UpperCAmelCase__ , batched=UpperCAmelCase__ ) lowerCAmelCase = 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, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self : int ) -> Tuple: # Initialize image_processing lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase = 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 = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values lowerCAmelCase , lowerCAmelCase = self.image_processor_tester.get_expected_values(UpperCAmelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase = image_processing(UpperCAmelCase__ , return_tensors='pt' ).pixel_values lowerCAmelCase , lowerCAmelCase = self.image_processor_tester.get_expected_values(UpperCAmelCase__ , batched=UpperCAmelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self : List[Any] ) -> Any: # Initialize image_processing lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase = 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 = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values lowerCAmelCase , lowerCAmelCase = self.image_processor_tester.get_expected_values(UpperCAmelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase = image_processing(UpperCAmelCase__ , return_tensors='pt' ).pixel_values lowerCAmelCase , lowerCAmelCase = self.image_processor_tester.get_expected_values(UpperCAmelCase__ , batched=UpperCAmelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __UpperCAmelCase ( self : Optional[Any] ) -> Any: # prepare image and target lowerCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: lowerCAmelCase = json.loads(f.read() ) lowerCAmelCase = {'image_id': 3_9_7_6_9, 'annotations': target} # encode them lowerCAmelCase = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50' ) lowerCAmelCase = image_processing(images=UpperCAmelCase__ , annotations=UpperCAmelCase__ , return_tensors='pt' ) # verify pixel values lowerCAmelCase = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['pixel_values'].shape , UpperCAmelCase__ ) lowerCAmelCase = torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , UpperCAmelCase__ , atol=1E-4 ) ) # verify area lowerCAmelCase = torch.tensor([5_887.9_600, 11_250.2_061, 489_353.8_438, 837_122.7_500, 147_967.5_156, 165_732.3_438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , UpperCAmelCase__ ) ) # verify boxes lowerCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , UpperCAmelCase__ ) lowerCAmelCase = torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , UpperCAmelCase__ , atol=1E-3 ) ) # verify image_id lowerCAmelCase = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , UpperCAmelCase__ ) ) # verify is_crowd lowerCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , UpperCAmelCase__ ) ) # verify class_labels lowerCAmelCase = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , UpperCAmelCase__ ) ) # verify orig_size lowerCAmelCase = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , UpperCAmelCase__ ) ) # verify size lowerCAmelCase = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , UpperCAmelCase__ ) ) @slow def __UpperCAmelCase ( self : str ) -> str: # prepare image, target and masks_path lowerCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: lowerCAmelCase = json.loads(f.read() ) lowerCAmelCase = {'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target} lowerCAmelCase = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them lowerCAmelCase = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic' ) lowerCAmelCase = image_processing(images=UpperCAmelCase__ , annotations=UpperCAmelCase__ , masks_path=UpperCAmelCase__ , return_tensors='pt' ) # verify pixel values lowerCAmelCase = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['pixel_values'].shape , UpperCAmelCase__ ) lowerCAmelCase = torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , UpperCAmelCase__ , atol=1E-4 ) ) # verify area lowerCAmelCase = torch.tensor([147_979.6_875, 165_527.0_469, 484_638.5_938, 11_292.9_375, 5_879.6_562, 7_634.1_147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , UpperCAmelCase__ ) ) # verify boxes lowerCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , UpperCAmelCase__ ) lowerCAmelCase = torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , UpperCAmelCase__ , atol=1E-3 ) ) # verify image_id lowerCAmelCase = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , UpperCAmelCase__ ) ) # verify is_crowd lowerCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , UpperCAmelCase__ ) ) # verify class_labels lowerCAmelCase = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , UpperCAmelCase__ ) ) # verify masks lowerCAmelCase = 8_2_2_8_7_3 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , UpperCAmelCase__ ) # verify orig_size lowerCAmelCase = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , UpperCAmelCase__ ) ) # verify size lowerCAmelCase = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , UpperCAmelCase__ ) )
4
'''simple docstring''' from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __snake_case ="""\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } """ __snake_case ="""\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. """ __snake_case =""" Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for 'record': list of question-answer dictionaries with the following keys: - 'idx': index of the question as specified by the dataset - 'prediction_text': the predicted answer text - for 'multirc': list of question-answer dictionaries with the following keys: - 'idx': index of the question-answer pair as specified by the dataset - 'prediction': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for 'record': list of question-answers dictionaries with the following keys: - 'idx': index of the question as specified by the dataset - 'answers': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for 'record': - 'exact_match': Exact match between answer and gold answer - 'f1': F1 score - for 'multirc': - 'exact_match': Exact match between answer and gold answer - 'f1_m': Per-question macro-F1 score - 'f1_a': Average F1 score over all answers - for 'axb': 'matthews_correlation': Matthew Correlation - for 'cb': - 'accuracy': Accuracy - 'f1': F1 score - for all others: - 'accuracy': Accuracy Examples: >>> super_glue_metric = datasets.load_metric('super_glue', 'copa') # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'cb') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'record') >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}] >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 1.0, 'f1': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc') >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'axb') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'matthews_correlation': 1.0} """ def a_ ( lowerCamelCase : str , lowerCamelCase : Union[str, Any] ): return float((preds == labels).mean() ) def a_ ( lowerCamelCase : Union[str, Any] , lowerCamelCase : Dict , lowerCamelCase : str="binary" ): lowerCAmelCase = simple_accuracy(lowerCamelCase , lowerCamelCase ) lowerCAmelCase = float(fa_score(y_true=lowerCamelCase , y_pred=lowerCamelCase , average=lowerCamelCase ) ) return { "accuracy": acc, "f1": fa, } def a_ ( lowerCamelCase : List[Any] , lowerCamelCase : List[Any] ): lowerCAmelCase = {} for id_pred, label in zip(lowerCamelCase , lowerCamelCase ): lowerCAmelCase = f'''{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}''' lowerCAmelCase = id_pred['prediction'] if question_id in question_map: question_map[question_id].append((pred, label) ) else: lowerCAmelCase = [(pred, label)] lowerCAmelCase , lowerCAmelCase = [], [] for question, preds_labels in question_map.items(): lowerCAmelCase , lowerCAmelCase = zip(*lowerCamelCase ) lowerCAmelCase = fa_score(y_true=lowerCamelCase , y_pred=lowerCamelCase , average='macro' ) fas.append(lowerCamelCase ) lowerCAmelCase = int(sum(pred == label for pred, label in preds_labels ) == len(lowerCamelCase ) ) ems.append(lowerCamelCase ) lowerCAmelCase = float(sum(lowerCamelCase ) / len(lowerCamelCase ) ) lowerCAmelCase = sum(lowerCamelCase ) / len(lowerCamelCase ) lowerCAmelCase = float(fa_score(y_true=lowerCamelCase , y_pred=[id_pred['prediction'] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): def __UpperCAmelCase ( self : List[str] ) -> List[Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( 'You should supply a configuration name selected in ' '["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format='numpy' if not self.config_name == 'record' and not self.config_name == 'multirc' else None , ) def __UpperCAmelCase ( self : Union[str, Any] ) -> str: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value('int64' ), "query": datasets.Value('int64' ), }, "prediction_text": datasets.Value('string' ), }, "references": { "idx": { "passage": datasets.Value('int64' ), "query": datasets.Value('int64' ), }, "answers": datasets.Sequence(datasets.Value('string' ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value('int64' ), "paragraph": datasets.Value('int64' ), "question": datasets.Value('int64' ), }, "prediction": datasets.Value('int64' ), }, "references": datasets.Value('int64' ), } else: return { "predictions": datasets.Value('int64' ), "references": datasets.Value('int64' ), } def __UpperCAmelCase ( self : List[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] ) -> Any: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(UpperCAmelCase__ , UpperCAmelCase__ )} elif self.config_name == "cb": return acc_and_fa(UpperCAmelCase__ , UpperCAmelCase__ , fa_avg='macro' ) elif self.config_name == "record": lowerCAmelCase = [ { 'qas': [ {'id': ref['idx']['query'], 'answers': [{'text': ans} for ans in ref['answers']]} for ref in references ] } ] lowerCAmelCase = {pred['idx']['query']: pred['prediction_text'] for pred in predictions} return evaluate_record(UpperCAmelCase__ , UpperCAmelCase__ )[0] elif self.config_name == "multirc": return evaluate_multirc(UpperCAmelCase__ , UpperCAmelCase__ ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(UpperCAmelCase__ , UpperCAmelCase__ )} else: raise KeyError( 'You should supply a configuration name selected in ' '["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]' )
4
1
'''simple docstring''' import itertools import math def a__ ( _SCREAMING_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(_SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def a__ ( ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = 2 while True: if is_prime(_SCREAMING_SNAKE_CASE ): yield num num += 1 def a__ ( _SCREAMING_SNAKE_CASE : int = 1_00_01 ) -> int: """simple docstring""" return next(itertools.islice(prime_generator() , nth - 1 , _SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": print(f"""{solution() = }""")
67
'''simple docstring''' from collections import Counter from timeit import timeit def a__ ( _SCREAMING_SNAKE_CASE : str = "" , ) -> bool: """simple docstring""" return sum(c % 2 for c in Counter(input_str.replace(" " , "" ).lower() ).values() ) < 2 def a__ ( _SCREAMING_SNAKE_CASE : str = "" ) -> bool: """simple docstring""" if len(_SCREAMING_SNAKE_CASE ) == 0: return True UpperCAmelCase_ : List[str] = input_str.replace(" " , "" ).lower() # character_freq_dict: Stores the frequency of every character in the input string UpperCAmelCase_ : dict[str, int] = {} for character in lower_case_input_str: UpperCAmelCase_ : Any = character_freq_dict.get(_SCREAMING_SNAKE_CASE , 0 ) + 1 UpperCAmelCase_ : Union[str, Any] = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def a__ ( _SCREAMING_SNAKE_CASE : str = "" ) -> None: """simple docstring""" print("\nFor string = " , _SCREAMING_SNAKE_CASE , ":" ) print( "> can_string_be_rearranged_as_palindrome_counter()" , "\tans =" , can_string_be_rearranged_as_palindrome_counter(_SCREAMING_SNAKE_CASE ) , "\ttime =" , timeit( "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)" , setup="import __main__ as z" , ) , "seconds" , ) print( "> can_string_be_rearranged_as_palindrome()" , "\tans =" , can_string_be_rearranged_as_palindrome(_SCREAMING_SNAKE_CASE ) , "\ttime =" , timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)" , setup="import __main__ as z" , ) , "seconds" , ) if __name__ == "__main__": _lowerCamelCase = input( """Enter string to determine if it can be rearranged as a palindrome or not: """ ).strip() benchmark(check_str) _lowerCamelCase = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"""{check_str} can {'' if status else 'not '}be rearranged as a palindrome""")
67
1
'''simple docstring''' def UpperCamelCase__ ( lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = current_set.copy() for row_index, row in enumerate(lowerCAmelCase ): _lowerCAmelCase = row[0] for column_index, column in enumerate(lowerCAmelCase ): if magnitude == 0: _lowerCAmelCase = column continue _lowerCAmelCase = column / magnitude # Subtract to cancel term _lowerCAmelCase = current_set[0] _lowerCAmelCase = [first_row] _lowerCAmelCase = current_set[1::] for row in current_set: _lowerCAmelCase = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(lowerCAmelCase ) continue for column_index in range(len(lowerCAmelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(lowerCAmelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: _lowerCAmelCase = final_set[0] _lowerCAmelCase = [] _lowerCAmelCase = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) _lowerCAmelCase = simplify(lowerCAmelCase ) for i in range(len(lowerCAmelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , lowerCAmelCase ) _lowerCAmelCase = resultant return final_set def UpperCamelCase__ ( lowerCAmelCase ): """simple docstring""" if len(lowerCAmelCase ) == 0: raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) _lowerCAmelCase = len(lowerCAmelCase ) + 1 if any(len(lowerCAmelCase ) != _length for item in equations ): raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) for row in equations: if any(not isinstance(lowerCAmelCase , (int, float) ) for column in row ): raise ValueError("""solve_simultaneous() requires lists of integers""" ) if len(lowerCAmelCase ) == 1: return [equations[0][-1] / equations[0][0]] _lowerCAmelCase = equations.copy() if any(0 in row for row in data_set ): _lowerCAmelCase = data_set.copy() _lowerCAmelCase = [] for row_index, row in enumerate(lowerCAmelCase ): if 0 not in row: _lowerCAmelCase = data_set.pop(lowerCAmelCase ) break if not full_row: raise ValueError("""solve_simultaneous() requires at least 1 full equation""" ) data_set.insert(0 , lowerCAmelCase ) _lowerCAmelCase = data_set.copy() _lowerCAmelCase = simplify(lowerCAmelCase ) _lowerCAmelCase = simplified[::-1] _lowerCAmelCase = [] for row in simplified: _lowerCAmelCase = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue _lowerCAmelCase = row.copy()[: len(lowerCAmelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(lowerCAmelCase ) == 0: solutions.append(0 ) continue _lowerCAmelCase = temp_row[1::] _lowerCAmelCase = temp_row[::-1] for column_index, column in enumerate(lowerCAmelCase ): current_solution -= column * solutions[column_index] solutions.append(lowerCAmelCase ) _lowerCAmelCase = [] for item in solutions: final.append(float(round(lowerCAmelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() A__ : Optional[Any] =[ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
70
'''simple docstring''' from torch import nn def UpperCamelCase__ ( lowerCAmelCase ): """simple docstring""" if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f"Unsupported activation function: {act_fn}" )
70
1
from functools import lru_cache def __lowerCamelCase ( __a :int ) -> set: """simple docstring""" A__ = 2 A__ = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(__lowerCAmelCase ) if n > 1: factors.add(__lowerCAmelCase ) return factors @lru_cache def __lowerCamelCase ( __a :Optional[int] ) -> int: """simple docstring""" return len(unique_prime_factors(__lowerCAmelCase ) ) def __lowerCamelCase ( __a :Optional[Any] ) -> bool: """simple docstring""" return len(set(__lowerCAmelCase ) ) in (0, 1) def __lowerCamelCase ( __a :Optional[int] ) -> list: """simple docstring""" A__ = 2 while True: # Increment each value of a generated range A__ = [base + i for i in range(__lowerCAmelCase )] # Run elements through out unique_prime_factors function # Append our target number to the end. A__ = [upf_len(__lowerCAmelCase ) for x in group] checker.append(__lowerCAmelCase ) # If all numbers in the list are equal, return the group variable. if equality(__lowerCAmelCase ): return group # Increment our base variable by 1 base += 1 def __lowerCamelCase ( __a :List[str] = 4 ) -> int: """simple docstring""" A__ = run(__lowerCAmelCase ) return results[0] if len(__lowerCAmelCase ) else None if __name__ == "__main__": print(solution())
350
import math def __lowerCamelCase ( ) -> None: """simple docstring""" A__ = input("""Enter message: """ ) A__ = int(input(F'Enter key [2-{len(__a ) - 1}]: ' ) ) A__ = input("""Encryption/Decryption [e/d]: """ ) if mode.lower().startswith("""e""" ): A__ = encrypt_message(__a , __a ) elif mode.lower().startswith("""d""" ): A__ = decrypt_message(__a , __a ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(F'Output:\n{text + "|"}' ) def __lowerCamelCase ( __a :int , __a :str ) -> str: """simple docstring""" A__ = [""""""] * key for col in range(__a ): A__ = col while pointer < len(__a ): cipher_text[col] += message[pointer] pointer += key return "".join(__a ) def __lowerCamelCase ( __a :int , __a :str ) -> str: """simple docstring""" A__ = math.ceil(len(__a ) / key ) A__ = key A__ = (num_cols * num_rows) - len(__a ) A__ = [""""""] * num_cols A__ = 0 A__ = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): A__ = 0 row += 1 return "".join(__a ) if __name__ == "__main__": import doctest doctest.testmod() main()
276
0
import inspect import unittest from transformers import DecisionTransformerConfig, 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, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class lowercase__ : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=13 , __UpperCAmelCase=7 , __UpperCAmelCase=6 , __UpperCAmelCase=17 , __UpperCAmelCase=23 , __UpperCAmelCase=11 , __UpperCAmelCase=True , )-> Optional[int]: '''simple docstring''' lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = act_dim lowerCAmelCase__ = state_dim lowerCAmelCase__ = hidden_size lowerCAmelCase__ = max_length lowerCAmelCase__ = is_training def UpperCAmelCase ( self )-> List[str]: '''simple docstring''' lowerCAmelCase__ = floats_tensor((self.batch_size, self.seq_length, self.state_dim) ) lowerCAmelCase__ = floats_tensor((self.batch_size, self.seq_length, self.act_dim) ) lowerCAmelCase__ = floats_tensor((self.batch_size, self.seq_length, 1) ) lowerCAmelCase__ = floats_tensor((self.batch_size, self.seq_length, 1) ) lowerCAmelCase__ = ids_tensor((self.batch_size, self.seq_length) , vocab_size=1000 ) lowerCAmelCase__ = random_attention_mask((self.batch_size, self.seq_length) ) lowerCAmelCase__ = self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def UpperCAmelCase ( self )-> str: '''simple docstring''' return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , )-> Dict: '''simple docstring''' lowerCAmelCase__ = DecisionTransformerModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() lowerCAmelCase__ = model(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) self.parent.assertEqual(result.state_preds.shape , states.shape ) self.parent.assertEqual(result.action_preds.shape , actions.shape ) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions def UpperCAmelCase ( self )-> int: '''simple docstring''' lowerCAmelCase__ = self.prepare_config_and_inputs() ( lowerCAmelCase__ ) = config_and_inputs lowerCAmelCase__ = { '''states''': states, '''actions''': actions, '''rewards''': rewards, '''returns_to_go''': returns_to_go, '''timesteps''': timesteps, '''attention_mask''': attention_mask, } return config, inputs_dict @require_torch class lowercase__ ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, unittest.TestCase ): a_ =(DecisionTransformerModel,) if is_torch_available() else () a_ =() a_ ={"""feature-extraction""": DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids a_ =False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features a_ =False a_ =False a_ =False a_ =False a_ =False a_ =False a_ =False a_ =False a_ =False def UpperCAmelCase ( self )-> List[Any]: '''simple docstring''' lowerCAmelCase__ = DecisionTransformerModelTester(self ) lowerCAmelCase__ = ConfigTester(self , config_class=_UpperCAmelCase , hidden_size=37 ) def UpperCAmelCase ( self )-> Tuple: '''simple docstring''' self.config_tester.run_common_tests() def UpperCAmelCase ( self )-> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) @slow def UpperCAmelCase ( self )-> Any: '''simple docstring''' for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = DecisionTransformerModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def UpperCAmelCase ( self )-> Dict: '''simple docstring''' lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(_UpperCAmelCase ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = [ '''states''', '''actions''', '''rewards''', '''returns_to_go''', '''timesteps''', '''attention_mask''', ] self.assertListEqual(arg_names[: len(_UpperCAmelCase )] , _UpperCAmelCase ) @require_torch class lowercase__ ( unittest.TestCase ): @slow def UpperCAmelCase ( self )-> Dict: '''simple docstring''' lowerCAmelCase__ = 2 # number of steps of autoregressive prediction we will perform lowerCAmelCase__ = 10 # defined by the RL environment, may be normalized lowerCAmelCase__ = DecisionTransformerModel.from_pretrained("edbeeching/decision-transformer-gym-hopper-expert" ) lowerCAmelCase__ = model.to(_UpperCAmelCase ) lowerCAmelCase__ = model.config torch.manual_seed(0 ) lowerCAmelCase__ = torch.randn(1 , 1 , config.state_dim ).to(device=_UpperCAmelCase , dtype=torch.floataa ) # env.reset() lowerCAmelCase__ = torch.tensor( [[0.242_793, -0.28_693_074, 0.8_742_613], [0.67_815_274, -0.08_101_085, -0.12_952_147]] , device=_UpperCAmelCase ) lowerCAmelCase__ = torch.tensor(_UpperCAmelCase , device=_UpperCAmelCase , dtype=torch.floataa ).reshape(1 , 1 , 1 ) lowerCAmelCase__ = state lowerCAmelCase__ = torch.zeros(1 , 0 , config.act_dim , device=_UpperCAmelCase , dtype=torch.floataa ) lowerCAmelCase__ = torch.zeros(1 , 0 , device=_UpperCAmelCase , dtype=torch.floataa ) lowerCAmelCase__ = torch.tensor(0 , device=_UpperCAmelCase , dtype=torch.long ).reshape(1 , 1 ) for step in range(_UpperCAmelCase ): lowerCAmelCase__ = torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=_UpperCAmelCase )] , dim=1 ) lowerCAmelCase__ = torch.cat([rewards, torch.zeros(1 , 1 , device=_UpperCAmelCase )] , dim=1 ) lowerCAmelCase__ = torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device ) with torch.no_grad(): lowerCAmelCase__ = model( states=_UpperCAmelCase , actions=_UpperCAmelCase , rewards=_UpperCAmelCase , returns_to_go=_UpperCAmelCase , timesteps=_UpperCAmelCase , attention_mask=_UpperCAmelCase , return_dict=_UpperCAmelCase , ) self.assertEqual(action_pred.shape , actions.shape ) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1E-4 ) ) lowerCAmelCase__ = ( # env.step(action) torch.randn(1 , 1 , config.state_dim ).to(device=_UpperCAmelCase , dtype=torch.floataa ), 1.0, False, {}, ) lowerCAmelCase__ = action_pred[0, -1] lowerCAmelCase__ = torch.cat([states, state] , dim=1 ) lowerCAmelCase__ = returns_to_go[0, -1] - reward lowerCAmelCase__ = torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 ) lowerCAmelCase__ = torch.cat( [timesteps, torch.ones((1, 1) , device=_UpperCAmelCase , dtype=torch.long ) * (step + 1)] , dim=1 )
340
"""simple docstring""" def __A ( a_ :int = 60_08_51_47_51_43) -> int: try: __a : List[Any] = int(a_) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''') if n <= 0: raise ValueError('''Parameter n must be greater than or equal to one.''') __a : int = 1 __a : List[Any] = 2 while i * i <= n: while n % i == 0: __a : List[str] = i n //= i i += 1 if n > 1: __a : Optional[int] = n return int(a_) if __name__ == "__main__": print(F'{solution() = }')
160
0
def __lowerCAmelCase ( a__ , a__ , a__ ) -> float: __a = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def __lowerCAmelCase ( ) -> Union[str, Any]: print(sum_of_series(1 , 1 , 10 ) ) if __name__ == "__main__": import doctest doctest.testmod()
370
from __future__ import annotations def __lowerCAmelCase ( a__ , a__ = None ) -> list[list[str]]: __a = word_bank or [] # create a table __a = len(a__ ) + 1 __a = [] for _ in range(a__ ): table.append([] ) # seed value __a = [[]] # because empty string has empty combination # iterate through the indices for i in range(a__ ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(a__ )] == word: __a = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(a__ )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(a__ )]: combination.reverse() return table[len(a__ )] if __name__ == "__main__": print(all_construct('jwajalapa', ['jwa', 'j', 'w', 'a', 'la', 'lapa'])) print(all_construct('rajamati', ['s', 'raj', 'amat', 'raja', 'ma', 'i', 't'])) print( all_construct( 'hexagonosaurus', ['h', 'ex', 'hex', 'ag', 'ago', 'ru', 'auru', 'rus', 'go', 'no', 'o', 's'], ) )
33
0
'''simple docstring''' 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 a_ : Union[str, 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 } a_ : Tuple = logging.get_logger(__name__) class snake_case ( lowercase ): """simple docstring""" _lowerCamelCase = "maskformer" _lowerCamelCase = {"hidden_size": "mask_feature_size"} _lowerCamelCase = ["resnet", "swin"] _lowerCamelCase = ["detr"] def __init__( self , UpperCamelCase = 256 , UpperCamelCase = 256 , UpperCamelCase = 0.1 , UpperCamelCase = False , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = 0.02 , UpperCamelCase = 1.0 , UpperCamelCase = 1.0 , UpperCamelCase = 1.0 , UpperCamelCase = 20.0 , UpperCamelCase = None , **UpperCamelCase , ): """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 snake_case ( cls , UpperCamelCase , UpperCamelCase , **UpperCamelCase ): """simple docstring""" return cls( backbone_config=UpperCamelCase , decoder_config=UpperCamelCase , **UpperCamelCase , ) def snake_case ( self ): """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
55
'''simple docstring''' 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 snake_case : """simple docstring""" def __init__( self , UpperCamelCase , ): """simple docstring""" lowerCamelCase_ = parent lowerCamelCase_ = 13 lowerCamelCase_ = 7 lowerCamelCase_ = True lowerCamelCase_ = True lowerCamelCase_ = True lowerCamelCase_ = 99 lowerCamelCase_ = 32 lowerCamelCase_ = 2 lowerCamelCase_ = 4 lowerCamelCase_ = 37 lowerCamelCase_ = "gelu" lowerCamelCase_ = 0.1 lowerCamelCase_ = 0.1 lowerCamelCase_ = 512 lowerCamelCase_ = 16 lowerCamelCase_ = 2 lowerCamelCase_ = 0.02 lowerCamelCase_ = 3 lowerCamelCase_ = 4 lowerCamelCase_ = None def snake_case ( self ): """simple docstring""" lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase_ = None if self.use_input_mask: lowerCamelCase_ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase_ = None lowerCamelCase_ = None lowerCamelCase_ = None if self.use_labels: lowerCamelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase_ = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase_ = 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 snake_case ( self ): """simple docstring""" ( ( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) , ) = self.prepare_config_and_inputs() lowerCamelCase_ = True lowerCamelCase_ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCamelCase_ = 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 snake_case ( self , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = TFEsmModel(config=UpperCamelCase ) lowerCamelCase_ = {"input_ids": input_ids, "attention_mask": input_mask} lowerCamelCase_ = model(UpperCamelCase ) lowerCamelCase_ = [input_ids, input_mask] lowerCamelCase_ = model(UpperCamelCase ) lowerCamelCase_ = model(UpperCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case ( self , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , ): """simple docstring""" lowerCamelCase_ = True lowerCamelCase_ = TFEsmModel(config=UpperCamelCase ) lowerCamelCase_ = { "input_ids": input_ids, "attention_mask": input_mask, "encoder_hidden_states": encoder_hidden_states, "encoder_attention_mask": encoder_attention_mask, } lowerCamelCase_ = model(UpperCamelCase ) lowerCamelCase_ = [input_ids, input_mask] lowerCamelCase_ = model(UpperCamelCase , encoder_hidden_states=UpperCamelCase ) # Also check the case where encoder outputs are not passed lowerCamelCase_ = model(UpperCamelCase , attention_mask=UpperCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case ( self , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = TFEsmForMaskedLM(config=UpperCamelCase ) lowerCamelCase_ = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def snake_case ( self , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = self.num_labels lowerCamelCase_ = TFEsmForTokenClassification(config=UpperCamelCase ) lowerCamelCase_ = {"input_ids": input_ids, "attention_mask": input_mask} lowerCamelCase_ = model(UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def snake_case ( self ): """simple docstring""" lowerCamelCase_ = self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) , ) = config_and_inputs lowerCamelCase_ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class snake_case ( lowercase , lowercase , unittest.TestCase ): """simple docstring""" _lowerCamelCase = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) _lowerCamelCase = ( { "feature-extraction": TFEsmModel, "fill-mask": TFEsmForMaskedLM, "text-classification": TFEsmForSequenceClassification, "token-classification": TFEsmForTokenClassification, "zero-shot": TFEsmForSequenceClassification, } if is_tf_available() else {} ) _lowerCamelCase = False _lowerCamelCase = False def snake_case ( self ): """simple docstring""" lowerCamelCase_ = TFEsmModelTester(self ) lowerCamelCase_ = ConfigTester(self , config_class=UpperCamelCase , hidden_size=37 ) def snake_case ( self ): """simple docstring""" self.config_tester.run_common_tests() def snake_case ( self ): """simple docstring""" lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase ) def snake_case ( self ): """simple docstring""" lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCamelCase ) def snake_case ( self ): """simple docstring""" lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase ) def snake_case ( self ): """simple docstring""" lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCamelCase ) @slow def snake_case ( self ): """simple docstring""" for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ = TFEsmModel.from_pretrained(UpperCamelCase ) self.assertIsNotNone(UpperCamelCase ) @unittest.skip("Protein models do not support embedding resizing." ) def snake_case ( self ): """simple docstring""" pass @unittest.skip("Protein models do not support embedding resizing." ) def snake_case ( self ): """simple docstring""" pass def 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(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 lowerCamelCase_ = model.get_bias() assert isinstance(UpperCamelCase , UpperCamelCase ) for k, v in name.items(): assert isinstance(UpperCamelCase , tf.Variable ) else: lowerCamelCase_ = model.get_output_embeddings() assert x is None lowerCamelCase_ = model.get_bias() assert name is None @require_tf class snake_case ( unittest.TestCase ): """simple docstring""" @slow def snake_case ( self ): """simple docstring""" lowerCamelCase_ = TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D" ) lowerCamelCase_ = tf.constant([[0, 1, 2, 3, 4, 5]] ) lowerCamelCase_ = model(UpperCamelCase )[0] lowerCamelCase_ = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , UpperCamelCase ) # compare the actual values for a slice. lowerCamelCase_ = tf.constant( [ [ [8.921_518, -10.589_814, -6.4_671_307], [-6.3_967_156, -13.911_377, -1.1_211_915], [-7.781_247, -13.951_557, -3.740_592], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-2 ) ) @slow def snake_case ( self ): """simple docstring""" lowerCamelCase_ = TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D" ) lowerCamelCase_ = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) lowerCamelCase_ = model(UpperCamelCase )[0] # compare the actual values for a slice. lowerCamelCase_ = tf.constant( [ [ [0.14_443_092, 0.54_125_327, 0.3_247_739], [0.30_340_484, 0.00_526_676, 0.31_077_722], [0.32_278_043, -0.24_987_096, 0.3_414_628], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
55
1
"""simple docstring""" from abc import ABC, abstractmethod from typing import List, Optional class UpperCAmelCase_ ( a_): def __init__( self : Optional[int] ) -> Tuple: # test for the above condition self.test() def _UpperCamelCase ( self : Dict ) -> Optional[int]: _UpperCamelCase = 0 _UpperCamelCase = False while not completed: if counter == 1: self.reset() _UpperCamelCase = self.advance() if not self.does_advance(lowercase_ ): raise Exception( '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.''' ) _UpperCamelCase = self.update(lowercase_ ) counter += 1 if counter > 1_0000: 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 ) -> List[str]: raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _UpperCamelCase ( self : int , __UpperCamelCase : int ) -> int: raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _UpperCamelCase ( self : List[Any] , __UpperCamelCase : int ) -> List[Any]: raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _UpperCamelCase ( self : int ) -> Any: raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _UpperCamelCase ( self : List[str] ) -> Optional[Any]: raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _UpperCamelCase ( self : Dict , __UpperCamelCase : Any=False ) -> List[str]: raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class UpperCAmelCase_ ( a_): def __init__( self : Optional[int] , __UpperCamelCase : List[int] ) -> Tuple: super(lowercase_ , self ).__init__() if not isinstance(lowercase_ , lowercase_ ) or len(lowercase_ ) == 0: raise ValueError(F'''`token_ids` has to be a non-empty list, but is {token_ids}.''' ) if any((not isinstance(lowercase_ , lowercase_ ) 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}.''' ) _UpperCamelCase = token_ids _UpperCamelCase = len(self.token_ids ) _UpperCamelCase = -1 # the index of the currently fulfilled step _UpperCamelCase = False def _UpperCamelCase ( self : Union[str, Any] ) -> int: if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def _UpperCamelCase ( self : Dict , __UpperCamelCase : int ) -> Dict: if not isinstance(lowercase_ , lowercase_ ): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(lowercase_ )}''' ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def _UpperCamelCase ( self : List[str] , __UpperCamelCase : int ) -> int: if not isinstance(lowercase_ , lowercase_ ): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(lowercase_ )}''' ) _UpperCamelCase = False _UpperCamelCase = False _UpperCamelCase = False if self.does_advance(lowercase_ ): self.fulfilled_idx += 1 _UpperCamelCase = True if self.fulfilled_idx == (self.seqlen - 1): _UpperCamelCase = True _UpperCamelCase = completed else: # failed to make progress. _UpperCamelCase = True self.reset() return stepped, completed, reset def _UpperCamelCase ( self : Optional[int] ) -> Tuple: _UpperCamelCase = False _UpperCamelCase = 0 def _UpperCamelCase ( self : Optional[int] ) -> Dict: return self.seqlen - (self.fulfilled_idx + 1) def _UpperCamelCase ( self : Optional[int] , __UpperCamelCase : Optional[Any]=False ) -> Optional[int]: _UpperCamelCase = PhrasalConstraint(self.token_ids ) if stateful: _UpperCamelCase = self.seqlen _UpperCamelCase = self.fulfilled_idx _UpperCamelCase = self.completed return new_constraint class UpperCAmelCase_ : def __init__( self : str , __UpperCamelCase : List[List[int]] , __UpperCamelCase : int=True ) -> Dict: _UpperCamelCase = max([len(lowercase_ ) for one in nested_token_ids] ) _UpperCamelCase = {} for token_ids in nested_token_ids: _UpperCamelCase = root for tidx, token_id in enumerate(lowercase_ ): if token_id not in level: _UpperCamelCase = {} _UpperCamelCase = level[token_id] if no_subsets and self.has_subsets(lowercase_ , lowercase_ ): raise ValueError( '''Each list in `nested_token_ids` can\'t be a complete subset of another list, but is''' F''' {nested_token_ids}.''' ) _UpperCamelCase = root def _UpperCamelCase ( self : Union[str, Any] , __UpperCamelCase : List[str] ) -> Dict: _UpperCamelCase = self.trie for current_token in current_seq: _UpperCamelCase = start[current_token] _UpperCamelCase = list(start.keys() ) return next_tokens def _UpperCamelCase ( self : Union[str, Any] , __UpperCamelCase : List[str] ) -> Any: _UpperCamelCase = self.next_tokens(lowercase_ ) return len(lowercase_ ) == 0 def _UpperCamelCase ( self : Dict , __UpperCamelCase : List[Any] ) -> List[Any]: _UpperCamelCase = list(root.values() ) if len(lowercase_ ) == 0: return 1 else: return sum([self.count_leaves(lowercase_ ) for nn in next_nodes] ) def _UpperCamelCase ( self : Tuple , __UpperCamelCase : Tuple , __UpperCamelCase : Tuple ) -> Any: _UpperCamelCase = self.count_leaves(lowercase_ ) return len(lowercase_ ) != leaf_count class UpperCAmelCase_ ( a_): def __init__( self : Dict , __UpperCamelCase : List[List[int]] ) -> int: super(lowercase_ , self ).__init__() if not isinstance(lowercase_ , lowercase_ ) or len(lowercase_ ) == 0: raise ValueError(F'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.''' ) if any(not isinstance(lowercase_ , lowercase_ ) 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(lowercase_ , lowercase_ ) 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}.''' ) _UpperCamelCase = DisjunctiveTrie(lowercase_ ) _UpperCamelCase = nested_token_ids _UpperCamelCase = self.trie.max_height _UpperCamelCase = [] _UpperCamelCase = False def _UpperCamelCase ( self : Dict ) -> Dict: _UpperCamelCase = self.trie.next_tokens(self.current_seq ) if len(lowercase_ ) == 0: return None else: return token_list def _UpperCamelCase ( self : str , __UpperCamelCase : int ) -> int: if not isinstance(lowercase_ , lowercase_ ): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(lowercase_ )}''' ) _UpperCamelCase = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def _UpperCamelCase ( self : Any , __UpperCamelCase : int ) -> str: if not isinstance(lowercase_ , lowercase_ ): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(lowercase_ )}''' ) _UpperCamelCase = False _UpperCamelCase = False _UpperCamelCase = False if self.does_advance(lowercase_ ): self.current_seq.append(lowercase_ ) _UpperCamelCase = True else: _UpperCamelCase = True self.reset() _UpperCamelCase = self.trie.reached_leaf(self.current_seq ) _UpperCamelCase = completed return stepped, completed, reset def _UpperCamelCase ( self : Dict ) -> List[Any]: _UpperCamelCase = False _UpperCamelCase = [] def _UpperCamelCase ( self : Any ) -> List[str]: 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 : Any , __UpperCamelCase : Union[str, Any]=False ) -> Optional[Any]: _UpperCamelCase = DisjunctiveConstraint(self.token_ids ) if stateful: _UpperCamelCase = self.seqlen _UpperCamelCase = self.current_seq _UpperCamelCase = self.completed return new_constraint class UpperCAmelCase_ : def __init__( self : Optional[Any] , __UpperCamelCase : List[Constraint] ) -> int: _UpperCamelCase = constraints # max # of steps required to fulfill a given constraint _UpperCamelCase = max([c.seqlen for c in constraints] ) _UpperCamelCase = len(lowercase_ ) _UpperCamelCase = False self.init_state() def _UpperCamelCase ( self : str ) -> Optional[Any]: _UpperCamelCase = [] _UpperCamelCase = None _UpperCamelCase = [constraint.copy(stateful=lowercase_ ) for constraint in self.constraints] def _UpperCamelCase ( self : Any ) -> Optional[int]: _UpperCamelCase = 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 : Optional[Any] ) -> Optional[Any]: _UpperCamelCase = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" _UpperCamelCase = constraint.advance() if isinstance(lowercase_ , lowercase_ ): token_list.append(lowercase_ ) elif isinstance(lowercase_ , lowercase_ ): token_list.extend(lowercase_ ) else: _UpperCamelCase = self.inprogress_constraint.advance() if isinstance(lowercase_ , lowercase_ ): token_list.append(lowercase_ ) elif isinstance(lowercase_ , lowercase_ ): token_list.extend(lowercase_ ) if len(lowercase_ ) == 0: return None else: return token_list def _UpperCamelCase ( self : Optional[int] , __UpperCamelCase : Optional[List[int]] ) -> Dict: self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint _UpperCamelCase = self.add(lowercase_ ) # the entire list of constraints are fulfilled if self.completed: break def _UpperCamelCase ( self : Tuple , __UpperCamelCase : int ) -> Dict: if not isinstance(lowercase_ , lowercase_ ): raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.''' ) _UpperCamelCase = False, False if self.completed: _UpperCamelCase = True _UpperCamelCase = 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 _UpperCamelCase = self.inprogress_constraint.update(lowercase_ ) 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=lowercase_ ) ) _UpperCamelCase = 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 ) _UpperCamelCase = None if len(self.pending_constraints ) == 0: # we're done! _UpperCamelCase = 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(lowercase_ ): _UpperCamelCase = pending_constraint.update(lowercase_ ) 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(lowercase_ ) _UpperCamelCase = None if not complete and stepped: _UpperCamelCase = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". _UpperCamelCase = ( 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. _UpperCamelCase = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def _UpperCamelCase ( self : List[Any] , __UpperCamelCase : Optional[Any]=True ) -> Union[str, Any]: _UpperCamelCase = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: _UpperCamelCase = [ constraint.copy(stateful=lowercase_ ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: _UpperCamelCase = self.inprogress_constraint.copy(stateful=lowercase_ ) _UpperCamelCase = [constraint.copy() for constraint in self.pending_constraints] return new_state
357
"""simple docstring""" from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCAmelCase_ ( _lowercase , _lowercase): @register_to_config def __init__( self : Tuple , __UpperCamelCase : bool , __UpperCamelCase : Optional[int] = None , __UpperCamelCase : Optional[int] = None ) -> int: super().__init__() _UpperCamelCase = learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" _UpperCamelCase = torch.zeros(__UpperCamelCase , __UpperCamelCase ) else: _UpperCamelCase = None _UpperCamelCase = torch.nn.Parameter(__UpperCamelCase ) class UpperCAmelCase_ ( _lowercase): snake_case__ = 42 snake_case__ = 42 snake_case__ = 42 snake_case__ = 42 snake_case__ = 42 snake_case__ = 42 def __init__( self : List[str] , __UpperCamelCase : VQModel , __UpperCamelCase : CLIPTextModel , __UpperCamelCase : CLIPTokenizer , __UpperCamelCase : TransformeraDModel , __UpperCamelCase : VQDiffusionScheduler , __UpperCamelCase : LearnedClassifierFreeSamplingEmbeddings , ) -> Optional[int]: super().__init__() self.register_modules( vqvae=__UpperCamelCase , transformer=__UpperCamelCase , text_encoder=__UpperCamelCase , tokenizer=__UpperCamelCase , scheduler=__UpperCamelCase , learned_classifier_free_sampling_embeddings=__UpperCamelCase , ) def _UpperCamelCase ( self : Optional[Any] , __UpperCamelCase : Dict , __UpperCamelCase : Dict , __UpperCamelCase : List[str] ) -> str: _UpperCamelCase = len(__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else 1 # get prompt text embeddings _UpperCamelCase = self.tokenizer( __UpperCamelCase , padding='''max_length''' , max_length=self.tokenizer.model_max_length , return_tensors='''pt''' , ) _UpperCamelCase = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: _UpperCamelCase = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( '''The following part of your input was truncated because CLIP can only handle sequences up to''' F''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) _UpperCamelCase = text_input_ids[:, : self.tokenizer.model_max_length] _UpperCamelCase = self.text_encoder(text_input_ids.to(self.device ) )[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 _UpperCamelCase = prompt_embeds / prompt_embeds.norm(dim=-1 , keepdim=__UpperCamelCase ) # duplicate text embeddings for each generation per prompt _UpperCamelCase = prompt_embeds.repeat_interleave(__UpperCamelCase , dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: _UpperCamelCase = self.learned_classifier_free_sampling_embeddings.embeddings _UpperCamelCase = negative_prompt_embeds.unsqueeze(0 ).repeat(__UpperCamelCase , 1 , 1 ) else: _UpperCamelCase = [''''''] * batch_size _UpperCamelCase = text_input_ids.shape[-1] _UpperCamelCase = self.tokenizer( __UpperCamelCase , padding='''max_length''' , max_length=__UpperCamelCase , truncation=__UpperCamelCase , return_tensors='''pt''' , ) _UpperCamelCase = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings _UpperCamelCase = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 , keepdim=__UpperCamelCase ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method _UpperCamelCase = negative_prompt_embeds.shape[1] _UpperCamelCase = negative_prompt_embeds.repeat(1 , __UpperCamelCase , 1 ) _UpperCamelCase = negative_prompt_embeds.view(batch_size * num_images_per_prompt , __UpperCamelCase , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _UpperCamelCase = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self : List[str] , __UpperCamelCase : Union[str, List[str]] , __UpperCamelCase : int = 100 , __UpperCamelCase : float = 5.0 , __UpperCamelCase : float = 1.0 , __UpperCamelCase : int = 1 , __UpperCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __UpperCamelCase : Optional[torch.FloatTensor] = None , __UpperCamelCase : Optional[str] = "pil" , __UpperCamelCase : bool = True , __UpperCamelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __UpperCamelCase : int = 1 , ) -> Union[ImagePipelineOutput, Tuple]: if isinstance(__UpperCamelCase , __UpperCamelCase ): _UpperCamelCase = 1 elif isinstance(__UpperCamelCase , __UpperCamelCase ): _UpperCamelCase = len(__UpperCamelCase ) else: raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(__UpperCamelCase )}''' ) _UpperCamelCase = batch_size * num_images_per_prompt _UpperCamelCase = guidance_scale > 1.0 _UpperCamelCase = self._encode_prompt(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(__UpperCamelCase , __UpperCamelCase ) or callback_steps <= 0) ): raise ValueError( F'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' F''' {type(__UpperCamelCase )}.''' ) # get the initial completely masked latents unless the user supplied it _UpperCamelCase = (batch_size, self.transformer.num_latent_pixels) if latents is None: _UpperCamelCase = self.transformer.num_vector_embeds - 1 _UpperCamelCase = torch.full(__UpperCamelCase , __UpperCamelCase ).to(self.device ) else: if latents.shape != latents_shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( '''Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,''' F''' {self.transformer.num_vector_embeds - 1} (inclusive).''' ) _UpperCamelCase = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(__UpperCamelCase , device=self.device ) _UpperCamelCase = self.scheduler.timesteps.to(self.device ) _UpperCamelCase = latents for i, t in enumerate(self.progress_bar(__UpperCamelCase ) ): # expand the sample if we are doing classifier free guidance _UpperCamelCase = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` _UpperCamelCase = self.transformer(__UpperCamelCase , encoder_hidden_states=__UpperCamelCase , timestep=__UpperCamelCase ).sample if do_classifier_free_guidance: _UpperCamelCase , _UpperCamelCase = model_output.chunk(2 ) _UpperCamelCase = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(__UpperCamelCase , dim=1 , keepdim=__UpperCamelCase ) _UpperCamelCase = self.truncate(__UpperCamelCase , __UpperCamelCase ) # remove `log(0)`'s (`-inf`s) _UpperCamelCase = model_output.clamp(-70 ) # compute the previous noisy sample x_t -> x_t-1 _UpperCamelCase = self.scheduler.step(__UpperCamelCase , timestep=__UpperCamelCase , sample=__UpperCamelCase , generator=__UpperCamelCase ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) _UpperCamelCase = self.vqvae.config.vq_embed_dim _UpperCamelCase = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) _UpperCamelCase = self.vqvae.quantize.get_codebook_entry(__UpperCamelCase , shape=__UpperCamelCase ) _UpperCamelCase = self.vqvae.decode(__UpperCamelCase , force_not_quantize=__UpperCamelCase ).sample _UpperCamelCase = (image / 2 + 0.5).clamp(0 , 1 ) _UpperCamelCase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _UpperCamelCase = self.numpy_to_pil(__UpperCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__UpperCamelCase ) def _UpperCamelCase ( self : Optional[Any] , __UpperCamelCase : torch.FloatTensor , __UpperCamelCase : float ) -> torch.FloatTensor: _UpperCamelCase , _UpperCamelCase = torch.sort(__UpperCamelCase , 1 , descending=__UpperCamelCase ) _UpperCamelCase = torch.exp(__UpperCamelCase ) _UpperCamelCase = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out _UpperCamelCase = torch.full_like(keep_mask[:, 0:1, :] , __UpperCamelCase ) _UpperCamelCase = torch.cat((all_true, keep_mask) , dim=1 ) _UpperCamelCase = keep_mask[:, :-1, :] _UpperCamelCase = keep_mask.gather(1 , indices.argsort(1 ) ) _UpperCamelCase = log_p_x_0.clone() _UpperCamelCase = -torch.inf # -inf = log(0) return rv
54
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _a = {"""configuration_mbart""": ["""MBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MBartConfig""", """MBartOnnxConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = ["""MBartTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = ["""MBartTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ """MBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """MBartForCausalLM""", """MBartForConditionalGeneration""", """MBartForQuestionAnswering""", """MBartForSequenceClassification""", """MBartModel""", """MBartPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ """TFMBartForConditionalGeneration""", """TFMBartModel""", """TFMBartPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ """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 _a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
194
"""simple docstring""" import argparse import json import os import torch from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case, __snake_case ) -> str: """simple docstring""" with open(__snake_case ) as metadata_file: _UpperCamelCase = json.load(__snake_case ) _UpperCamelCase = LukeConfig(use_entity_aware_attention=__snake_case, **metadata['''model_config'''] ) # Load in the weights from the checkpoint_path _UpperCamelCase = torch.load(__snake_case, map_location='''cpu''' ) # Load the entity vocab file _UpperCamelCase = load_entity_vocab(__snake_case ) _UpperCamelCase = RobertaTokenizer.from_pretrained(metadata['''model_config''']['''bert_model_name'''] ) # Add special tokens to the token vocabulary for downstream tasks _UpperCamelCase = AddedToken('''<ent>''', lstrip=__snake_case, rstrip=__snake_case ) _UpperCamelCase = AddedToken('''<ent2>''', lstrip=__snake_case, rstrip=__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(__snake_case ) with open(os.path.join(__snake_case, LukeTokenizer.vocab_files_names['''entity_vocab_file'''] ), '''w''' ) as f: json.dump(__snake_case, __snake_case ) _UpperCamelCase = LukeTokenizer.from_pretrained(__snake_case ) # Initialize the embeddings of the special tokens _UpperCamelCase = state_dict['''embeddings.word_embeddings.weight'''] _UpperCamelCase = word_emb[tokenizer.convert_tokens_to_ids(['''@'''] )[0]].unsqueeze(0 ) _UpperCamelCase = word_emb[tokenizer.convert_tokens_to_ids(['''#'''] )[0]].unsqueeze(0 ) _UpperCamelCase = torch.cat([word_emb, ent_emb, enta_emb] ) # 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"]: _UpperCamelCase = F'''encoder.layer.{layer_index}.attention.self.''' _UpperCamelCase = state_dict[prefix + matrix_name] _UpperCamelCase = state_dict[prefix + matrix_name] _UpperCamelCase = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks _UpperCamelCase = state_dict['''entity_embeddings.entity_embeddings.weight'''] _UpperCamelCase = entity_emb[entity_vocab['''[MASK]''']] _UpperCamelCase = LukeModel(config=__snake_case ).eval() _UpperCamelCase , _UpperCamelCase = model.load_state_dict(__snake_case, strict=__snake_case ) if not (len(__snake_case ) == 1 and missing_keys[0] == "embeddings.position_ids"): raise ValueError(F'''Missing keys {", ".join(__snake_case )}. Expected only missing embeddings.position_ids''' ) if not (all(key.startswith('''entity_predictions''' ) or key.startswith('''lm_head''' ) for key in unexpected_keys )): raise ValueError( '''Unexpected keys''' F''' {", ".join([key for key in unexpected_keys if not (key.startswith("entity_predictions" ) or key.startswith("lm_head" ))] )}''' ) # Check outputs _UpperCamelCase = LukeTokenizer.from_pretrained(__snake_case, task='''entity_classification''' ) _UpperCamelCase = ( '''Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped the''' ''' new world number one avoid a humiliating second- round exit at Wimbledon .''' ) _UpperCamelCase = (39, 42) _UpperCamelCase = tokenizer(__snake_case, entity_spans=[span], add_prefix_space=__snake_case, return_tensors='''pt''' ) _UpperCamelCase = model(**__snake_case ) # Verify word hidden states if model_size == "large": _UpperCamelCase = torch.Size((1, 42, 10_24) ) _UpperCamelCase = torch.tensor( [[0.0133, 0.0865, 0.0095], [0.3093, -0.2576, -0.7418], [-0.1720, -0.2117, -0.2869]] ) else: # base _UpperCamelCase = torch.Size((1, 42, 7_68) ) _UpperCamelCase = torch.tensor([[0.0037, 0.1368, -0.0091], [0.1099, 0.3329, -0.1095], [0.0765, 0.5335, 0.1179]] ) 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], __snake_case, atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": _UpperCamelCase = torch.Size((1, 1, 10_24) ) _UpperCamelCase = torch.tensor([[0.0466, -0.0106, -0.0179]] ) else: # base _UpperCamelCase = torch.Size((1, 1, 7_68) ) _UpperCamelCase = torch.tensor([[0.1457, 0.1044, 0.0174]] ) 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], __snake_case, atol=1e-4 ): raise ValueError # Finally, save our PyTorch model and tokenizer print('''Saving PyTorch model to {}'''.format(__snake_case ) ) model.save_pretrained(__snake_case ) def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase = {} with open(__snake_case, '''r''', encoding='''utf-8''' ) as f: for index, line in enumerate(__snake_case ): _UpperCamelCase , _UpperCamelCase = line.rstrip().split('''\t''' ) _UpperCamelCase = index return entity_vocab if __name__ == "__main__": _a = 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.""" ) _a = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
194
1
"""simple docstring""" import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, 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 UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Optional[Any] = MobileBertTokenizer snake_case__ : List[str] = MobileBertTokenizerFast snake_case__ : Tuple = True snake_case__ : Optional[int] = True snake_case__ : Union[str, Any] = filter_non_english snake_case__ : Optional[int] = "google/mobilebert-uncased" def UpperCAmelCase_ ( self : Dict ) -> int: super().setUp() __SCREAMING_SNAKE_CASE = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] __SCREAMING_SNAKE_CASE = 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] ) ) __SCREAMING_SNAKE_CASE = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] ) -> str: __SCREAMING_SNAKE_CASE = "UNwant\u00E9d,running" __SCREAMING_SNAKE_CASE = "unwanted, running" return input_text, output_text def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(UpperCAmelCase__ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [9, 6, 7, 1_2, 1_0, 1_1] ) def UpperCAmelCase_ ( self : str ) -> List[Any]: if not self.test_rust_tokenizer: return __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = "UNwant\u00E9d,running" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = tokenizer.encode(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) # With lower casing __SCREAMING_SNAKE_CASE = self.get_tokenizer(do_lower_case=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer(do_lower_case=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "UNwant\u00E9d,running" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = tokenizer.encode(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: __SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) 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 : Optional[int] ) -> Any: __SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) 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] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : str ) -> Tuple: __SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Any ) -> Tuple: __SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __SCREAMING_SNAKE_CASE = {} for i, token in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = WordpieceTokenizer(vocab=UpperCAmelCase__ , 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 : int ) -> List[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 UpperCAmelCase_ ( self : str ) -> Optional[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 : str ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) self.assertListEqual( [rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) @slow def UpperCAmelCase_ ( self : Dict ) -> Tuple: __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained("google/mobilebert-uncased" ) __SCREAMING_SNAKE_CASE = tokenizer.encode("sequence builders" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode("multi-sequence build" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == [1_0_1] + text + [1_0_2] assert encoded_pair == [1_0_1] + text + [1_0_2] + text_a + [1_0_2] def UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus( UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , "do_lower_case" ) else False __SCREAMING_SNAKE_CASE = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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[int] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = ["的", "人", "有"] __SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ ) ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ )
195
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule a__ : Optional[int] = {'''tokenization_byt5''': ['''ByT5Tokenizer''']} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys a__ : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
195
1
from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class lowercase ( UpperCamelCase__ ): @slow @require_torch def a__ ( self ) -> Dict: _A : int = EncoderDecoderModel.from_encoder_decoder_pretrained("""prajjwal1/bert-tiny""" , """prajjwal1/bert-tiny""" ) _A : Tuple = BertTokenizer.from_pretrained("""bert-base-uncased""" ) _A : Dict = bertabert.config.encoder.vocab_size _A : List[str] = tokenizer.sep_token_id _A : Dict = tokenizer.cls_token_id _A : List[Any] = 128 _A : Tuple = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""train[:1%]""" ) _A : List[str] = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""validation[:1%]""" ) _A : Union[str, Any] = train_dataset.select(range(32 ) ) _A : str = val_dataset.select(range(16 ) ) _A : Dict = 4 def _map_to_encoder_decoder_inputs(_a ): # Tokenizer will automatically set [BOS] <text> [EOS] _A : List[Any] = tokenizer(batch["""article"""] , padding="""max_length""" , truncation=_a , max_length=512 ) _A : int = tokenizer(batch["""highlights"""] , padding="""max_length""" , truncation=_a , max_length=128 ) _A : Union[str, Any] = inputs.input_ids _A : List[Any] = inputs.attention_mask _A : Dict = outputs.input_ids _A : str = outputs.input_ids.copy() _A : Union[str, Any] = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["""labels"""] ] _A : Dict = outputs.attention_mask assert all(len(_a ) == 512 for x in inputs.input_ids ) assert all(len(_a ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(_a ): _A : int = pred.label_ids _A : str = pred.predictions # all unnecessary tokens are removed _A : Dict = tokenizer.batch_decode(_a , skip_special_tokens=_a ) _A : Optional[Any] = tokenizer.batch_decode(_a , skip_special_tokens=_a ) _A : Tuple = sum([int(pred_str[i] == label_str[i] ) for i in range(len(_a ) )] ) / len(_a ) return {"accuracy": accuracy} # map train dataset _A : Dict = train_dataset.map( _map_to_encoder_decoder_inputs , batched=_a , batch_size=_a , remove_columns=["""article""", """highlights"""] , ) train_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) # same for validation dataset _A : Optional[int] = val_dataset.map( _map_to_encoder_decoder_inputs , batched=_a , batch_size=_a , remove_columns=["""article""", """highlights"""] , ) val_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) _A : Optional[int] = self.get_auto_remove_tmp_dir() _A : Any = SeqaSeqTrainingArguments( output_dir=_a , per_device_train_batch_size=_a , per_device_eval_batch_size=_a , predict_with_generate=_a , evaluation_strategy="""steps""" , do_train=_a , do_eval=_a , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer _A : Optional[Any] = SeqaSeqTrainer( model=_a , args=_a , compute_metrics=_compute_metrics , train_dataset=_a , eval_dataset=_a , tokenizer=_a , ) # start training trainer.train()
26
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = 42 class UpperCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : Tuple , UpperCamelCase__ : List[Any]=3 , UpperCamelCase__ : str=3 , UpperCamelCase__ : List[Any]=("DownEncoderBlock2D",) , UpperCamelCase__ : Optional[Any]=(64,) , UpperCamelCase__ : Optional[Any]=2 , UpperCamelCase__ : Union[str, Any]=32 , UpperCamelCase__ : Optional[Any]="silu" , UpperCamelCase__ : List[str]=True , ) -> str: """simple docstring""" super().__init__() __magic_name__ = layers_per_block __magic_name__ = torch.nn.Convad( UpperCamelCase__ , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) __magic_name__ = None __magic_name__ = nn.ModuleList([] ) # down __magic_name__ = block_out_channels[0] for i, down_block_type in enumerate(UpperCamelCase__ ): __magic_name__ = output_channel __magic_name__ = block_out_channels[i] __magic_name__ = i == len(UpperCamelCase__ ) - 1 __magic_name__ = get_down_block( UpperCamelCase__ , num_layers=self.layers_per_block , in_channels=UpperCamelCase__ , out_channels=UpperCamelCase__ , add_downsample=not is_final_block , resnet_eps=1E-6 , downsample_padding=0 , resnet_act_fn=UpperCamelCase__ , resnet_groups=UpperCamelCase__ , attention_head_dim=UpperCamelCase__ , temb_channels=UpperCamelCase__ , ) self.down_blocks.append(UpperCamelCase__ ) # mid __magic_name__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=UpperCamelCase__ , output_scale_factor=1 , resnet_time_scale_shift="""default""" , attention_head_dim=block_out_channels[-1] , resnet_groups=UpperCamelCase__ , temb_channels=UpperCamelCase__ , ) # out __magic_name__ = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=UpperCamelCase__ , eps=1E-6 ) __magic_name__ = nn.SiLU() __magic_name__ = 2 * out_channels if double_z else out_channels __magic_name__ = nn.Convad(block_out_channels[-1] , UpperCamelCase__ , 3 , padding=1 ) __magic_name__ = False def _lowercase ( self : List[str] , UpperCamelCase__ : Optional[Any] ) -> int: """simple docstring""" __magic_name__ = x __magic_name__ = self.conv_in(UpperCamelCase__ ) if self.training and self.gradient_checkpointing: def create_custom_forward(UpperCamelCase__ : int ): def custom_forward(*UpperCamelCase__ : str ): return module(*UpperCamelCase__ ) return custom_forward # down if is_torch_version(""">=""" , """1.11.0""" ): for down_block in self.down_blocks: __magic_name__ = torch.utils.checkpoint.checkpoint( create_custom_forward(UpperCamelCase__ ) , UpperCamelCase__ , use_reentrant=UpperCamelCase__ ) # middle __magic_name__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , UpperCamelCase__ , use_reentrant=UpperCamelCase__ ) else: for down_block in self.down_blocks: __magic_name__ = torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCamelCase__ ) , UpperCamelCase__ ) # middle __magic_name__ = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , UpperCamelCase__ ) else: # down for down_block in self.down_blocks: __magic_name__ = down_block(UpperCamelCase__ ) # middle __magic_name__ = self.mid_block(UpperCamelCase__ ) # post-process __magic_name__ = self.conv_norm_out(UpperCamelCase__ ) __magic_name__ = self.conv_act(UpperCamelCase__ ) __magic_name__ = self.conv_out(UpperCamelCase__ ) return sample class UpperCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[str] , UpperCamelCase__ : int=3 , UpperCamelCase__ : Dict=3 , UpperCamelCase__ : List[Any]=("UpDecoderBlock2D",) , UpperCamelCase__ : List[Any]=(64,) , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : int=32 , UpperCamelCase__ : Optional[int]="silu" , UpperCamelCase__ : Tuple="group" , ) -> Dict: """simple docstring""" super().__init__() __magic_name__ = layers_per_block __magic_name__ = nn.Convad( UpperCamelCase__ , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) __magic_name__ = None __magic_name__ = nn.ModuleList([] ) __magic_name__ = in_channels if norm_type == """spatial""" else None # mid __magic_name__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=UpperCamelCase__ , output_scale_factor=1 , resnet_time_scale_shift="""default""" if norm_type == """group""" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=UpperCamelCase__ , temb_channels=UpperCamelCase__ , ) # up __magic_name__ = list(reversed(UpperCamelCase__ ) ) __magic_name__ = reversed_block_out_channels[0] for i, up_block_type in enumerate(UpperCamelCase__ ): __magic_name__ = output_channel __magic_name__ = reversed_block_out_channels[i] __magic_name__ = i == len(UpperCamelCase__ ) - 1 __magic_name__ = get_up_block( UpperCamelCase__ , num_layers=self.layers_per_block + 1 , in_channels=UpperCamelCase__ , out_channels=UpperCamelCase__ , prev_output_channel=UpperCamelCase__ , add_upsample=not is_final_block , resnet_eps=1E-6 , resnet_act_fn=UpperCamelCase__ , resnet_groups=UpperCamelCase__ , attention_head_dim=UpperCamelCase__ , temb_channels=UpperCamelCase__ , resnet_time_scale_shift=UpperCamelCase__ , ) self.up_blocks.append(UpperCamelCase__ ) __magic_name__ = output_channel # out if norm_type == "spatial": __magic_name__ = SpatialNorm(block_out_channels[0] , UpperCamelCase__ ) else: __magic_name__ = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=UpperCamelCase__ , eps=1E-6 ) __magic_name__ = nn.SiLU() __magic_name__ = nn.Convad(block_out_channels[0] , UpperCamelCase__ , 3 , padding=1 ) __magic_name__ = False def _lowercase ( self : str , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Tuple=None ) -> Tuple: """simple docstring""" __magic_name__ = z __magic_name__ = self.conv_in(UpperCamelCase__ ) __magic_name__ = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(UpperCamelCase__ : Optional[int] ): def custom_forward(*UpperCamelCase__ : int ): return module(*UpperCamelCase__ ) return custom_forward if is_torch_version(""">=""" , """1.11.0""" ): # middle __magic_name__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , UpperCamelCase__ , UpperCamelCase__ , use_reentrant=UpperCamelCase__ ) __magic_name__ = sample.to(UpperCamelCase__ ) # up for up_block in self.up_blocks: __magic_name__ = torch.utils.checkpoint.checkpoint( create_custom_forward(UpperCamelCase__ ) , UpperCamelCase__ , UpperCamelCase__ , use_reentrant=UpperCamelCase__ ) else: # middle __magic_name__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , UpperCamelCase__ , UpperCamelCase__ ) __magic_name__ = sample.to(UpperCamelCase__ ) # up for up_block in self.up_blocks: __magic_name__ = torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCamelCase__ ) , UpperCamelCase__ , UpperCamelCase__ ) else: # middle __magic_name__ = self.mid_block(UpperCamelCase__ , UpperCamelCase__ ) __magic_name__ = sample.to(UpperCamelCase__ ) # up for up_block in self.up_blocks: __magic_name__ = up_block(UpperCamelCase__ , UpperCamelCase__ ) # post-process if latent_embeds is None: __magic_name__ = self.conv_norm_out(UpperCamelCase__ ) else: __magic_name__ = self.conv_norm_out(UpperCamelCase__ , UpperCamelCase__ ) __magic_name__ = self.conv_act(UpperCamelCase__ ) __magic_name__ = self.conv_out(UpperCamelCase__ ) return sample class UpperCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : str , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Dict="random" , UpperCamelCase__ : List[Any]=False , UpperCamelCase__ : Dict=True ) -> Optional[Any]: """simple docstring""" super().__init__() __magic_name__ = n_e __magic_name__ = vq_embed_dim __magic_name__ = beta __magic_name__ = legacy __magic_name__ = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) __magic_name__ = remap if self.remap is not None: self.register_buffer("""used""" , torch.tensor(np.load(self.remap ) ) ) __magic_name__ = self.used.shape[0] __magic_name__ = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": __magic_name__ = self.re_embed __magic_name__ = self.re_embed + 1 print( F'''Remapping {self.n_e} indices to {self.re_embed} indices. ''' F'''Using {self.unknown_index} for unknown indices.''' ) else: __magic_name__ = n_e __magic_name__ = sane_index_shape def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Dict ) -> Union[str, Any]: """simple docstring""" __magic_name__ = inds.shape assert len(UpperCamelCase__ ) > 1 __magic_name__ = inds.reshape(ishape[0] , -1 ) __magic_name__ = self.used.to(UpperCamelCase__ ) __magic_name__ = (inds[:, :, None] == used[None, None, ...]).long() __magic_name__ = match.argmax(-1 ) __magic_name__ = match.sum(2 ) < 1 if self.unknown_index == "random": __magic_name__ = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: __magic_name__ = self.unknown_index return new.reshape(UpperCamelCase__ ) def _lowercase ( self : Optional[Any] , UpperCamelCase__ : str ) -> Tuple: """simple docstring""" __magic_name__ = inds.shape assert len(UpperCamelCase__ ) > 1 __magic_name__ = inds.reshape(ishape[0] , -1 ) __magic_name__ = self.used.to(UpperCamelCase__ ) if self.re_embed > self.used.shape[0]: # extra token __magic_name__ = 0 # simply set to zero __magic_name__ = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , UpperCamelCase__ ) return back.reshape(UpperCamelCase__ ) def _lowercase ( self : List[str] , UpperCamelCase__ : List[str] ) -> List[str]: """simple docstring""" __magic_name__ = z.permute(0 , 2 , 3 , 1 ).contiguous() __magic_name__ = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z __magic_name__ = torch.argmin(torch.cdist(UpperCamelCase__ , self.embedding.weight ) , dim=1 ) __magic_name__ = self.embedding(UpperCamelCase__ ).view(z.shape ) __magic_name__ = None __magic_name__ = None # compute loss for embedding if not self.legacy: __magic_name__ = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: __magic_name__ = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients __magic_name__ = z + (z_q - z).detach() # reshape back to match original input shape __magic_name__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: __magic_name__ = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis __magic_name__ = self.remap_to_used(UpperCamelCase__ ) __magic_name__ = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: __magic_name__ = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Union[str, Any] ) -> int: """simple docstring""" if self.remap is not None: __magic_name__ = indices.reshape(shape[0] , -1 ) # add batch axis __magic_name__ = self.unmap_to_all(UpperCamelCase__ ) __magic_name__ = indices.reshape(-1 ) # flatten again # get quantized latent vectors __magic_name__ = self.embedding(UpperCamelCase__ ) if shape is not None: __magic_name__ = z_q.view(UpperCamelCase__ ) # reshape back to match original input shape __magic_name__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class UpperCAmelCase_ ( _A ): '''simple docstring''' def __init__( self : Dict , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Tuple=False ) -> Optional[int]: """simple docstring""" __magic_name__ = parameters __magic_name__ , __magic_name__ = torch.chunk(UpperCamelCase__ , 2 , dim=1 ) __magic_name__ = torch.clamp(self.logvar , -30.0 , 20.0 ) __magic_name__ = deterministic __magic_name__ = torch.exp(0.5 * self.logvar ) __magic_name__ = torch.exp(self.logvar ) if self.deterministic: __magic_name__ = __magic_name__ = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def _lowercase ( self : Tuple , UpperCamelCase__ : Optional[torch.Generator] = None ) -> torch.FloatTensor: """simple docstring""" __magic_name__ = randn_tensor( self.mean.shape , generator=UpperCamelCase__ , device=self.parameters.device , dtype=self.parameters.dtype ) __magic_name__ = self.mean + self.std * sample return x def _lowercase ( self : Dict , UpperCamelCase__ : Optional[int]=None ) -> Any: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def _lowercase ( self : Optional[int] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Dict=[1, 2, 3] ) -> Optional[int]: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) __magic_name__ = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=UpperCamelCase__ ) def _lowercase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" return self.mean
88
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import LEDConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class UpperCAmelCase_ : '''simple docstring''' _lowercase : List[Any] = LEDConfig _lowercase : List[Any] = {} _lowercase : int = '''gelu''' def __init__( self , _lowercase , _lowercase=13 , _lowercase=7 , _lowercase=True , _lowercase=False , _lowercase=99 , _lowercase=32 , _lowercase=2 , _lowercase=4 , _lowercase=37 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=20 , _lowercase=2 , _lowercase=1 , _lowercase=0 , _lowercase=4 , ): """simple docstring""" _lowerCAmelCase = parent _lowerCAmelCase = batch_size _lowerCAmelCase = seq_length _lowerCAmelCase = is_training _lowerCAmelCase = use_labels _lowerCAmelCase = vocab_size _lowerCAmelCase = hidden_size _lowerCAmelCase = num_hidden_layers _lowerCAmelCase = num_attention_heads _lowerCAmelCase = intermediate_size _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = max_position_embeddings _lowerCAmelCase = eos_token_id _lowerCAmelCase = pad_token_id _lowerCAmelCase = bos_token_id _lowerCAmelCase = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after _lowerCAmelCase = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests _lowerCAmelCase = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _lowerCAmelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _lowerCAmelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) _lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCAmelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) _lowerCAmelCase = prepare_led_inputs_dict(_lowercase , _lowercase , _lowercase ) _lowerCAmelCase = tf.concat( [tf.zeros_like(_lowercase )[:, :-1], tf.ones_like(_lowercase )[:, -1:]] , axis=-1 , ) _lowerCAmelCase = global_attention_mask return config, inputs_dict def _lowercase ( self , _lowercase , _lowercase ): """simple docstring""" _lowerCAmelCase = TFLEDModel(config=_lowercase ).get_decoder() _lowerCAmelCase = inputs_dict["""input_ids"""] _lowerCAmelCase = input_ids[:1, :] _lowerCAmelCase = inputs_dict["""attention_mask"""][:1, :] _lowerCAmelCase = 1 # first forward pass _lowerCAmelCase = model(_lowercase , attention_mask=_lowercase , use_cache=_lowercase ) _lowerCAmelCase , _lowerCAmelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _lowerCAmelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) _lowerCAmelCase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _lowerCAmelCase = tf.concat([input_ids, next_tokens] , axis=-1 ) _lowerCAmelCase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _lowerCAmelCase = model(_lowercase , attention_mask=_lowercase )[0] _lowerCAmelCase = model(_lowercase , attention_mask=_lowercase , past_key_values=_lowercase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _lowerCAmelCase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _lowerCAmelCase = output_from_no_past[:, -3:, random_slice_idx] _lowerCAmelCase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_lowercase , _lowercase , rtol=1e-3 ) def A (__lowerCamelCase :Dict , __lowerCamelCase :Optional[int] , __lowerCamelCase :Tuple , __lowerCamelCase :Tuple=None , __lowerCamelCase :Union[str, Any]=None , __lowerCamelCase :Union[str, Any]=None , __lowerCamelCase :List[str]=None , ): if attention_mask is None: _lowerCAmelCase = tf.cast(tf.math.not_equal(__lowerCamelCase , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: _lowerCAmelCase = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: _lowerCAmelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _lowerCAmelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' _lowercase : Optional[Any] = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () _lowercase : Union[str, Any] = (TFLEDForConditionalGeneration,) if is_tf_available() else () _lowercase : List[str] = ( { '''conversational''': TFLEDForConditionalGeneration, '''feature-extraction''': TFLEDModel, '''summarization''': TFLEDForConditionalGeneration, '''text2text-generation''': TFLEDForConditionalGeneration, '''translation''': TFLEDForConditionalGeneration, } if is_tf_available() else {} ) _lowercase : List[str] = True _lowercase : Tuple = False _lowercase : Any = False _lowercase : Optional[int] = False def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = TFLEDModelTester(self ) _lowerCAmelCase = ConfigTester(self , config_class=_lowercase ) def _lowercase ( self ): """simple docstring""" self.config_tester.run_common_tests() def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_lowercase ) def _lowercase ( self ): """simple docstring""" _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _lowerCAmelCase = tf.zeros_like(inputs_dict["""attention_mask"""] ) _lowerCAmelCase = 2 _lowerCAmelCase = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["""global_attention_mask"""] , ) _lowerCAmelCase = True _lowerCAmelCase = self.model_tester.seq_length _lowerCAmelCase = self.model_tester.encoder_seq_length def check_decoder_attentions_output(_lowercase ): _lowerCAmelCase = outputs.decoder_attentions self.assertEqual(len(_lowercase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(_lowercase ): _lowerCAmelCase = [t.numpy() for t in outputs.encoder_attentions] _lowerCAmelCase = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(_lowercase ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(_lowercase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: _lowerCAmelCase = True _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = model_class(_lowercase ) _lowerCAmelCase = model(self._prepare_for_class(_lowercase , _lowercase ) ) _lowerCAmelCase = len(_lowercase ) self.assertEqual(config.output_hidden_states , _lowercase ) check_encoder_attentions_output(_lowercase ) if self.is_encoder_decoder: _lowerCAmelCase = model_class(_lowercase ) _lowerCAmelCase = model(self._prepare_for_class(_lowercase , _lowercase ) ) self.assertEqual(config.output_hidden_states , _lowercase ) check_decoder_attentions_output(_lowercase ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _lowerCAmelCase = True _lowerCAmelCase = model_class(_lowercase ) _lowerCAmelCase = model(self._prepare_for_class(_lowercase , _lowercase ) ) self.assertEqual(config.output_hidden_states , _lowercase ) check_encoder_attentions_output(_lowercase ) # Check attention is always last and order is fine _lowerCAmelCase = True _lowerCAmelCase = True _lowerCAmelCase = model_class(_lowercase ) _lowerCAmelCase = model(self._prepare_for_class(_lowercase , _lowercase ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_lowercase ) ) self.assertEqual(model.config.output_hidden_states , _lowercase ) check_encoder_attentions_output(_lowercase ) @unittest.skip("""LED keeps using potentially symbolic tensors in conditionals and breaks tracing.""" ) def _lowercase ( self ): """simple docstring""" pass def _lowercase ( self ): """simple docstring""" pass def A (__lowerCamelCase :List[Any] ): return tf.constant(__lowerCamelCase , dtype=tf.intaa ) _lowercase = 1e-4 @slow @require_tf class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = TFLEDForConditionalGeneration.from_pretrained("""allenai/led-base-16384""" ).led # change to intended input here _lowerCAmelCase = _long_tensor([512 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) _lowerCAmelCase = _long_tensor([128 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) _lowerCAmelCase = prepare_led_inputs_dict(model.config , _lowercase , _lowercase ) _lowerCAmelCase = model(**_lowercase )[0] _lowerCAmelCase = (1, 1_024, 768) self.assertEqual(output.shape , _lowercase ) # change to expected output here _lowerCAmelCase = tf.convert_to_tensor( [[2.3050, 2.8279, 0.6531], [-1.8457, -0.1455, -3.5661], [-1.0186, 0.4586, -2.2043]] , ) tf.debugging.assert_near(output[:, :3, :3] , _lowercase , atol=1e-3 ) def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = TFLEDForConditionalGeneration.from_pretrained("""allenai/led-base-16384""" ) # change to intended input here _lowerCAmelCase = _long_tensor([512 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) _lowerCAmelCase = _long_tensor([128 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) _lowerCAmelCase = prepare_led_inputs_dict(model.config , _lowercase , _lowercase ) _lowerCAmelCase = model(**_lowercase )[0] _lowerCAmelCase = (1, 1_024, model.config.vocab_size) self.assertEqual(output.shape , _lowercase ) # change to expected output here _lowerCAmelCase = tf.convert_to_tensor( [[33.6507, 6.4572, 16.8089], [5.8739, -2.4238, 11.2902], [-3.2139, -4.3149, 4.2783]] , ) tf.debugging.assert_near(output[:, :3, :3] , _lowercase , atol=1e-3 , rtol=1e-3 )
229
'''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
1
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
import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : Tuple =KandinskyVaaPriorPipeline __lowerCamelCase : Union[str, Any] =['prompt'] __lowerCamelCase : Any =['prompt', 'negative_prompt'] __lowerCamelCase : List[str] =[ 'num_images_per_prompt', 'generator', 'num_inference_steps', 'latents', 'negative_prompt', 'guidance_scale', 'output_type', 'return_dict', ] __lowerCamelCase : List[Any] =False @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return 32 @property def UpperCamelCase_ ( self : Any ): '''simple docstring''' return 32 @property def UpperCamelCase_ ( self : 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 : Union[str, Any] ): '''simple docstring''' return 100 @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) __a = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__lowercase ) @property def UpperCamelCase_ ( self : int ): '''simple docstring''' torch.manual_seed(0 ) __a = { """num_attention_heads""": 2, """attention_head_dim""": 12, """embedding_dim""": self.text_embedder_hidden_size, """num_layers""": 1, } __a = PriorTransformer(**__lowercase ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __a = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' torch.manual_seed(0 ) __a = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __a = CLIPVisionModelWithProjection(__lowercase ) return model @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' __a = CLIPImageProcessor( crop_size=224 , do_center_crop=__lowercase , do_normalize=__lowercase , do_resize=__lowercase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor def UpperCamelCase_ ( self : str ): '''simple docstring''' __a = self.dummy_prior __a = self.dummy_image_encoder __a = self.dummy_text_encoder __a = self.dummy_tokenizer __a = self.dummy_image_processor __a = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1000 , clip_sample=__lowercase , clip_sample_range=10.0 , ) __a = { """prior""": prior, """image_encoder""": image_encoder, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """scheduler""": scheduler, """image_processor""": image_processor, } return components def UpperCamelCase_ ( self : Optional[int] , __lowercase : List[str] , __lowercase : Any=0 ): '''simple docstring''' if str(__lowercase ).startswith("""mps""" ): __a = torch.manual_seed(__lowercase ) else: __a = torch.Generator(device=__lowercase ).manual_seed(__lowercase ) __a = { """prompt""": """horse""", """generator""": generator, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = """cpu""" __a = self.get_dummy_components() __a = self.pipeline_class(**__lowercase ) __a = pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) __a = pipe(**self.get_dummy_inputs(__lowercase ) ) __a = output.image_embeds __a = pipe( **self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0] __a = image[0, -10:] __a = image_from_tuple[0, -10:] assert image.shape == (1, 32) __a = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = torch_device == """cpu""" __a = True __a = False self._test_inference_batch_single_identical( test_max_difference=__lowercase , relax_max_difference=__lowercase , test_mean_pixel_difference=__lowercase , ) @skip_mps def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = torch_device == """cpu""" __a = False self._test_attention_slicing_forward_pass( test_max_difference=__lowercase , test_mean_pixel_difference=__lowercase , )
302
1
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class __snake_case ( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase__ ( self : Tuple ): __snake_case: Dict = 10 def UpperCAmelCase__ ( self : Dict ): __snake_case: Optional[int] = [1, 2, 3, 4] __snake_case: str = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(A , self.block_size , 0 ) , A ) def UpperCAmelCase__ ( self : int ): __snake_case: Any = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] __snake_case: Union[str, Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(A , self.block_size , 0 ) , A ) def UpperCAmelCase__ ( self : Union[str, Any] ): __snake_case: Optional[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] __snake_case: Tuple = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(A , self.block_size , 0 ) , A ) def UpperCAmelCase__ ( self : Dict ): __snake_case: Optional[Any] = """It was the year of Our Lord one thousand seven hundred and seventy-five.\n\nSpiritual revelations were conceded to England at that favoured period, as at this.""" __snake_case , __snake_case: int = process_story(A ) self.assertEqual(A , [] ) def UpperCAmelCase__ ( self : List[str] ): __snake_case: List[str] = """""" __snake_case , __snake_case: Optional[Any] = process_story(A ) self.assertEqual(A , [] ) self.assertEqual(A , [] ) def UpperCAmelCase__ ( self : Dict ): __snake_case: int = ( """It was the year of Our Lord one thousand seven hundred and """ """seventy-five\n\nSpiritual revelations were conceded to England """ """at that favoured period, as at this.\n@highlight\n\nIt was the best of times""" ) __snake_case , __snake_case: int = process_story(A ) __snake_case: str = [ """It was the year of Our Lord one thousand seven hundred and seventy-five.""", """Spiritual revelations were conceded to England at that favoured period, as at this.""", ] self.assertEqual(A , A ) __snake_case: List[Any] = ["""It was the best of times."""] self.assertEqual(A , A ) def UpperCAmelCase__ ( self : List[str] ): __snake_case: List[str] = torch.tensor([1, 2, 3, 4] ) __snake_case: Tuple = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(A , 0 ).numpy() , expected.numpy() ) def UpperCAmelCase__ ( self : str ): __snake_case: Optional[Any] = torch.tensor([1, 2, 3, 4, 23, 23, 23] ) __snake_case: List[str] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(A , 23 ).numpy() , expected.numpy() ) def UpperCAmelCase__ ( self : str ): __snake_case: Dict = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) __snake_case: Dict = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(A , 1 ).numpy() , expected.numpy() ) def UpperCAmelCase__ ( self : str ): __snake_case: Any = 101 __snake_case: Tuple = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 101, 5, 6], [1, 101, 3, 4, 101, 6]] ) __snake_case: List[Any] = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) __snake_case: Tuple = compute_token_type_ids(A , A ) np.testing.assert_array_equal(A , A )
293
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging __UpperCAmelCase : Dict = logging.get_logger(__name__) # pylint: disable=invalid-name class __snake_case ( __lowerCamelCase ): '''simple docstring''' def __init__( self : List[Any] , A : AutoencoderKL , A : CLIPTextModel , A : CLIPTokenizer , A : UNetaDConditionModel , A : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , A : StableDiffusionSafetyChecker , A : CLIPImageProcessor , ): super().__init__() self.register_modules( vae=A , text_encoder=A , tokenizer=A , unet=A , scheduler=A , safety_checker=A , feature_extractor=A , ) def UpperCAmelCase__ ( self : Optional[Any] , A : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __snake_case: Tuple = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(A ) def UpperCAmelCase__ ( self : str ): self.enable_attention_slicing(A ) @torch.no_grad() def __call__( self : List[str] , A : Union[str, List[str]] , A : int = 512 , A : int = 512 , A : int = 50 , A : float = 7.5 , A : Optional[Union[str, List[str]]] = None , A : Optional[int] = 1 , A : float = 0.0 , A : Optional[torch.Generator] = None , A : Optional[torch.FloatTensor] = None , A : Optional[str] = "pil" , A : bool = True , A : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , A : int = 1 , A : Optional[torch.FloatTensor] = None , **A : Optional[Any] , ): if isinstance(A , A ): __snake_case: int = 1 elif isinstance(A , A ): __snake_case: Optional[Any] = len(A ) else: raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(A )}''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(A , A ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(A )}.''' ) # get prompt text embeddings __snake_case: Tuple = self.tokenizer( A , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) __snake_case: Any = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: __snake_case: List[str] = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" f''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) __snake_case: Dict = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: __snake_case: Union[str, Any] = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method __snake_case , __snake_case , __snake_case: List[Any] = text_embeddings.shape __snake_case: Tuple = text_embeddings.repeat(1 , A , 1 ) __snake_case: Dict = text_embeddings.view(bs_embed * num_images_per_prompt , A , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. __snake_case: List[str] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __snake_case: List[str] if negative_prompt is None: __snake_case: Any = [""""""] elif type(A ) is not type(A ): raise TypeError( f'''`negative_prompt` should be the same type to `prompt`, but got {type(A )} !=''' f''' {type(A )}.''' ) elif isinstance(A , A ): __snake_case: List[str] = [negative_prompt] elif batch_size != len(A ): raise ValueError( f'''`negative_prompt`: {negative_prompt} has batch size {len(A )}, but `prompt`:''' f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches''' """ the batch size of `prompt`.""" ) else: __snake_case: str = negative_prompt __snake_case: Any = text_input_ids.shape[-1] __snake_case: Dict = self.tokenizer( A , padding="""max_length""" , max_length=A , truncation=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, using mps friendly method __snake_case: Optional[Any] = uncond_embeddings.shape[1] __snake_case: str = uncond_embeddings.repeat(A , A , 1 ) __snake_case: List[Any] = uncond_embeddings.view(batch_size * num_images_per_prompt , A , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __snake_case: Any = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. __snake_case: Tuple = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) __snake_case: List[Any] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) __snake_case: Optional[Any] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps __snake_case: Any = torch.randn( A , generator=A , device="""cpu""" , dtype=A ).to(self.device ) __snake_case: Tuple = torch.randn(A , generator=A , device="""cpu""" , dtype=A ).to( self.device ) else: __snake_case: Dict = torch.randn( A , generator=A , device=self.device , dtype=A ) __snake_case: Optional[int] = torch.randn(A , generator=A , device=self.device , dtype=A ) else: if latents_reference.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) __snake_case: Optional[int] = latents_reference.to(self.device ) __snake_case: List[str] = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images __snake_case: int = (latents_shape[3] - latents_shape_reference[3]) // 2 __snake_case: Optional[int] = (latents_shape[2] - latents_shape_reference[2]) // 2 __snake_case: int = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx __snake_case: Dict = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy __snake_case: List[Any] = 0 if dx < 0 else dx __snake_case: Dict = 0 if dy < 0 else dy __snake_case: List[str] = max(-dx , 0 ) __snake_case: int = max(-dy , 0 ) # import pdb # pdb.set_trace() __snake_case: List[Any] = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(A ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand __snake_case: str = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __snake_case: Optional[Any] = 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: Optional[int] = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __snake_case: int = {} if accepts_eta: __snake_case: Optional[Any] = eta for i, t in enumerate(self.progress_bar(A ) ): # expand the latents if we are doing classifier free guidance __snake_case: str = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __snake_case: Dict = self.scheduler.scale_model_input(A , A ) # predict the noise residual __snake_case: List[Any] = self.unet(A , A , encoder_hidden_states=A ).sample # perform guidance if do_classifier_free_guidance: __snake_case , __snake_case: Any = noise_pred.chunk(2 ) __snake_case: Optional[int] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 __snake_case: str = self.scheduler.step(A , A , A , **A ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(A , A , A ) __snake_case: Optional[int] = 1 / 0.1_8215 * latents __snake_case: List[Any] = self.vae.decode(A ).sample __snake_case: str = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 __snake_case: Any = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: __snake_case: List[Any] = self.feature_extractor(self.numpy_to_pil(A ) , return_tensors="""pt""" ).to( self.device ) __snake_case , __snake_case: List[str] = self.safety_checker( images=A , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: __snake_case: Optional[int] = None if output_type == "pil": __snake_case: Tuple = self.numpy_to_pil(A ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=A , nsfw_content_detected=A )
293
1
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A : List[Any] = logging.get_logger(__name__) A : Optional[Any] = { 'google/owlvit-base-patch32': 'https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json', 'google/owlvit-base-patch16': 'https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json', 'google/owlvit-large-patch14': 'https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json', } class A ( UpperCAmelCase__ ): '''simple docstring''' A__ = '''owlvit_text_model''' def __init__(self : int , _UpperCAmelCase : Dict=4_9408 , _UpperCAmelCase : Any=512 , _UpperCAmelCase : int=2048 , _UpperCAmelCase : List[str]=12 , _UpperCAmelCase : int=8 , _UpperCAmelCase : List[str]=16 , _UpperCAmelCase : int="quick_gelu" , _UpperCAmelCase : int=1E-5 , _UpperCAmelCase : Dict=0.0 , _UpperCAmelCase : Dict=0.02 , _UpperCAmelCase : Tuple=1.0 , _UpperCAmelCase : Tuple=0 , _UpperCAmelCase : Tuple=4_9406 , _UpperCAmelCase : Optional[Any]=4_9407 , **_UpperCAmelCase : int , ) -> Optional[Any]: """simple docstring""" super().__init__(pad_token_id=_UpperCAmelCase , bos_token_id=_UpperCAmelCase , eos_token_id=_UpperCAmelCase , **_UpperCAmelCase ) lowercase__ = vocab_size lowercase__ = hidden_size lowercase__ = intermediate_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = max_position_embeddings lowercase__ = hidden_act lowercase__ = layer_norm_eps lowercase__ = attention_dropout lowercase__ = initializer_range lowercase__ = initializer_factor @classmethod def lowerCamelCase__ (cls : Optional[int] , _UpperCAmelCase : Union[str, os.PathLike] , **_UpperCAmelCase : Dict ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(_UpperCAmelCase ) lowercase__ , lowercase__ = cls.get_config_dict(_UpperCAmelCase , **_UpperCAmelCase ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get("""model_type""" ) == "owlvit": lowercase__ = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_UpperCAmelCase , **_UpperCAmelCase ) class A ( UpperCAmelCase__ ): '''simple docstring''' A__ = '''owlvit_vision_model''' def __init__(self : List[Any] , _UpperCAmelCase : int=768 , _UpperCAmelCase : Optional[int]=3072 , _UpperCAmelCase : Tuple=12 , _UpperCAmelCase : Tuple=12 , _UpperCAmelCase : Tuple=3 , _UpperCAmelCase : Tuple=768 , _UpperCAmelCase : Tuple=32 , _UpperCAmelCase : Dict="quick_gelu" , _UpperCAmelCase : List[str]=1E-5 , _UpperCAmelCase : Tuple=0.0 , _UpperCAmelCase : Optional[int]=0.02 , _UpperCAmelCase : List[Any]=1.0 , **_UpperCAmelCase : List[Any] , ) -> List[str]: """simple docstring""" super().__init__(**_UpperCAmelCase ) lowercase__ = hidden_size lowercase__ = intermediate_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = num_channels lowercase__ = image_size lowercase__ = patch_size lowercase__ = hidden_act lowercase__ = layer_norm_eps lowercase__ = attention_dropout lowercase__ = initializer_range lowercase__ = initializer_factor @classmethod def lowerCamelCase__ (cls : Dict , _UpperCAmelCase : Union[str, os.PathLike] , **_UpperCAmelCase : Union[str, Any] ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(_UpperCAmelCase ) lowercase__ , lowercase__ = cls.get_config_dict(_UpperCAmelCase , **_UpperCAmelCase ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get("""model_type""" ) == "owlvit": lowercase__ = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_UpperCAmelCase , **_UpperCAmelCase ) class A ( UpperCAmelCase__ ): '''simple docstring''' A__ = '''owlvit''' A__ = True def __init__(self : Optional[Any] , _UpperCAmelCase : Tuple=None , _UpperCAmelCase : Tuple=None , _UpperCAmelCase : Tuple=512 , _UpperCAmelCase : Optional[int]=2.6_592 , _UpperCAmelCase : Optional[Any]=True , **_UpperCAmelCase : Optional[Any] , ) -> List[Any]: """simple docstring""" super().__init__(**_UpperCAmelCase ) if text_config is None: lowercase__ = {} logger.info("""text_config is None. Initializing the OwlViTTextConfig with default values.""" ) if vision_config is None: lowercase__ = {} logger.info("""vision_config is None. initializing the OwlViTVisionConfig with default values.""" ) lowercase__ = OwlViTTextConfig(**_UpperCAmelCase ) lowercase__ = OwlViTVisionConfig(**_UpperCAmelCase ) lowercase__ = projection_dim lowercase__ = logit_scale_init_value lowercase__ = return_dict lowercase__ = 1.0 @classmethod def lowerCamelCase__ (cls : Tuple , _UpperCAmelCase : Union[str, os.PathLike] , **_UpperCAmelCase : Tuple ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(_UpperCAmelCase ) lowercase__ , lowercase__ = cls.get_config_dict(_UpperCAmelCase , **_UpperCAmelCase ) if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_UpperCAmelCase , **_UpperCAmelCase ) @classmethod def lowerCamelCase__ (cls : Dict , _UpperCAmelCase : Dict , _UpperCAmelCase : Dict , **_UpperCAmelCase : Dict ) -> List[Any]: """simple docstring""" lowercase__ = {} lowercase__ = text_config lowercase__ = vision_config return cls.from_dict(_UpperCAmelCase , **_UpperCAmelCase ) def lowerCamelCase__ (self : Tuple ) -> Any: """simple docstring""" lowercase__ = copy.deepcopy(self.__dict__ ) lowercase__ = self.text_config.to_dict() lowercase__ = self.vision_config.to_dict() lowercase__ = self.__class__.model_type return output class A ( UpperCAmelCase__ ): '''simple docstring''' @property def lowerCamelCase__ (self : int ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ] ) @property def lowerCamelCase__ (self : Dict ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""logits_per_image""", {0: """batch"""}), ("""logits_per_text""", {0: """batch"""}), ("""text_embeds""", {0: """batch"""}), ("""image_embeds""", {0: """batch"""}), ] ) @property def lowerCamelCase__ (self : Optional[int] ) -> float: """simple docstring""" return 1E-4 def lowerCamelCase__ (self : Any , _UpperCAmelCase : "ProcessorMixin" , _UpperCAmelCase : int = -1 , _UpperCAmelCase : int = -1 , _UpperCAmelCase : Optional["TensorType"] = None , ) -> Mapping[str, Any]: """simple docstring""" lowercase__ = super().generate_dummy_inputs( processor.tokenizer , batch_size=_UpperCAmelCase , seq_length=_UpperCAmelCase , framework=_UpperCAmelCase ) lowercase__ = super().generate_dummy_inputs( processor.image_processor , batch_size=_UpperCAmelCase , framework=_UpperCAmelCase ) return {**text_input_dict, **image_input_dict} @property def lowerCamelCase__ (self : Optional[int] ) -> int: """simple docstring""" return 14
305
import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def UpperCamelCase ( __magic_name__ : Optional[Any] ) -> List[Any]: """simple docstring""" lowercase__ = tmp_path / """file.csv""" lowercase__ = textwrap.dedent( """\ header1,header2 1,2 10,20 """ ) with open(__magic_name__ , """w""" ) as f: f.write(__magic_name__ ) return str(__magic_name__ ) @pytest.fixture def UpperCamelCase ( __magic_name__ : str ) -> Tuple: """simple docstring""" lowercase__ = tmp_path / """malformed_file.csv""" lowercase__ = textwrap.dedent( """\ header1,header2 1,2 10,20, """ ) with open(__magic_name__ , """w""" ) as f: f.write(__magic_name__ ) return str(__magic_name__ ) @pytest.fixture def UpperCamelCase ( __magic_name__ : List[Any] , __magic_name__ : List[str] ) -> str: """simple docstring""" lowercase__ = tmp_path / """csv_with_image.csv""" lowercase__ = textwrap.dedent( f'''\ image {image_file} ''' ) with open(__magic_name__ , """w""" ) as f: f.write(__magic_name__ ) return str(__magic_name__ ) @pytest.fixture def UpperCamelCase ( __magic_name__ : Tuple ) -> Union[str, Any]: """simple docstring""" lowercase__ = tmp_path / """csv_with_label.csv""" lowercase__ = textwrap.dedent( """\ label good bad good """ ) with open(__magic_name__ , """w""" ) as f: f.write(__magic_name__ ) return str(__magic_name__ ) @pytest.fixture def UpperCamelCase ( __magic_name__ : Dict ) -> Union[str, Any]: """simple docstring""" lowercase__ = tmp_path / """csv_with_int_list.csv""" lowercase__ = textwrap.dedent( """\ int_list 1 2 3 4 5 6 7 8 9 """ ) with open(__magic_name__ , """w""" ) as f: f.write(__magic_name__ ) return str(__magic_name__ ) def UpperCamelCase ( __magic_name__ : Tuple , __magic_name__ : Tuple , __magic_name__ : Tuple ) -> Optional[Any]: """simple docstring""" lowercase__ = Csv() lowercase__ = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(__magic_name__ , match="""Error tokenizing data""" ): for _ in generator: pass assert any( record.levelname == """ERROR""" and """Failed to read file""" in record.message and os.path.basename(__magic_name__ ) in record.message for record in caplog.records ) @require_pil def UpperCamelCase ( __magic_name__ : Optional[Any] ) -> Optional[Any]: """simple docstring""" with open(__magic_name__ , encoding="""utf-8""" ) as f: lowercase__ = f.read().splitlines()[1] lowercase__ = Csv(encoding="""utf-8""" , features=Features({"""image""": Image()} ) ) lowercase__ = csv._generate_tables([[csv_file_with_image]] ) lowercase__ = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("""image""" ).type == Image()() lowercase__ = pa_table.to_pydict()["""image"""] assert generated_content == [{"path": image_file, "bytes": None}] def UpperCamelCase ( __magic_name__ : Optional[Any] ) -> str: """simple docstring""" with open(__magic_name__ , encoding="""utf-8""" ) as f: lowercase__ = f.read().splitlines()[1:] lowercase__ = Csv(encoding="""utf-8""" , features=Features({"""label""": ClassLabel(names=["""good""", """bad"""] )} ) ) lowercase__ = csv._generate_tables([[csv_file_with_label]] ) lowercase__ = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("""label""" ).type == ClassLabel(names=["""good""", """bad"""] )() lowercase__ = pa_table.to_pydict()["""label"""] assert generated_content == [ClassLabel(names=["""good""", """bad"""] ).straint(__magic_name__ ) for label in labels] def UpperCamelCase ( __magic_name__ : Any ) -> Union[str, Any]: """simple docstring""" lowercase__ = Csv(encoding="""utf-8""" , sep=""",""" , converters={"""int_list""": lambda __magic_name__ : [int(__magic_name__ ) for i in x.split()]} ) lowercase__ = csv._generate_tables([[csv_file_with_int_list]] ) lowercase__ = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field("""int_list""" ).type ) lowercase__ = pa_table.to_pydict()["""int_list"""] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
305
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 _UpperCAmelCase = 'scheduler_config.json' class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : Union[str, Any] = 1 _UpperCamelCase : List[Any] = 2 _UpperCamelCase : Any = 3 _UpperCamelCase : str = 4 _UpperCamelCase : Dict = 5 @dataclass class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : jnp.ndarray class _UpperCamelCase : _UpperCamelCase : str = SCHEDULER_CONFIG_NAME _UpperCamelCase : Dict = ['''dtype'''] _UpperCamelCase : int = [] _UpperCamelCase : Optional[int] = True @classmethod def lowercase ( cls: Optional[Any] , _SCREAMING_SNAKE_CASE: Dict[str, Any] = None , _SCREAMING_SNAKE_CASE: Optional[str] = None , _SCREAMING_SNAKE_CASE: List[str]=False , **_SCREAMING_SNAKE_CASE: Any , ) -> Optional[int]: """simple docstring""" UpperCamelCase_ , UpperCamelCase_ = cls.load_config( pretrained_model_name_or_path=_SCREAMING_SNAKE_CASE , subfolder=_SCREAMING_SNAKE_CASE , return_unused_kwargs=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ , UpperCamelCase_ = cls.from_config(_SCREAMING_SNAKE_CASE , return_unused_kwargs=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if hasattr(_SCREAMING_SNAKE_CASE , "create_state" ) and getattr(_SCREAMING_SNAKE_CASE , "has_state" , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: Union[str, os.PathLike] , _SCREAMING_SNAKE_CASE: bool = False , **_SCREAMING_SNAKE_CASE: str ) -> List[Any]: """simple docstring""" self.save_config(save_directory=_SCREAMING_SNAKE_CASE , push_to_hub=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def lowercase ( self: Dict ) -> List[str]: """simple docstring""" return self._get_compatibles() @classmethod def lowercase ( cls: Optional[Any] ) -> str: """simple docstring""" UpperCamelCase_ = list(set([cls.__name__] + cls._compatibles ) ) UpperCamelCase_ = importlib.import_module(__name__.split("." )[0] ) UpperCamelCase_ = [ getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for c in compatible_classes_str if hasattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ] return compatible_classes def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> jnp.ndarray: assert len(UpperCamelCase_ ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(UpperCamelCase_ ) - x.ndim) ) , UpperCamelCase_ ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_=0.9_99 , UpperCamelCase_=jnp.floataa ) -> jnp.ndarray: def alpha_bar(UpperCamelCase_ ): return math.cos((time_step + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 UpperCamelCase_ = [] for i in range(UpperCamelCase_ ): UpperCamelCase_ = i / num_diffusion_timesteps UpperCamelCase_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(UpperCamelCase_ ) / alpha_bar(UpperCamelCase_ ) , UpperCamelCase_ ) ) return jnp.array(UpperCamelCase_ , dtype=UpperCamelCase_ ) @flax.struct.dataclass class _UpperCamelCase : _UpperCamelCase : jnp.ndarray _UpperCamelCase : jnp.ndarray _UpperCamelCase : jnp.ndarray @classmethod def lowercase ( cls: List[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any] ) -> Optional[int]: """simple docstring""" 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(_SCREAMING_SNAKE_CASE , axis=0 ) return cls( alphas=_SCREAMING_SNAKE_CASE , betas=_SCREAMING_SNAKE_CASE , alphas_cumprod=_SCREAMING_SNAKE_CASE , ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> int: UpperCamelCase_ = state.alphas_cumprod UpperCamelCase_ = alphas_cumprod[timesteps] ** 0.5 UpperCamelCase_ = sqrt_alpha_prod.flatten() UpperCamelCase_ = broadcast_to_shape_from_left(UpperCamelCase_ , original_samples.shape ) UpperCamelCase_ = (1 - alphas_cumprod[timesteps]) ** 0.5 UpperCamelCase_ = sqrt_one_minus_alpha_prod.flatten() UpperCamelCase_ = broadcast_to_shape_from_left(UpperCamelCase_ , original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Union[str, Any]: UpperCamelCase_ , UpperCamelCase_ = get_sqrt_alpha_prod(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Union[str, Any]: UpperCamelCase_ , UpperCamelCase_ = get_sqrt_alpha_prod(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
328
import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): _UpperCamelCase : List[Any] = IFImgaImgSuperResolutionPipeline _UpperCamelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''} _UpperCamelCase : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''} ) _UpperCamelCase : List[Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} def lowercase ( self: List[str] ) -> Any: """simple docstring""" return self._get_superresolution_dummy_components() def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Optional[int]=0 ) -> List[Any]: """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith("mps" ): UpperCamelCase_ = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase_ = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = floats_tensor((1, 3, 16, 16) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = { "prompt": "A painting of a squirrel eating a burger", "image": image, "original_image": original_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowercase ( self: Any ) -> Union[str, Any]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def lowercase ( self: int ) -> Tuple: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def lowercase ( self: Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def lowercase ( self: List[Any] ) -> Union[str, Any]: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def lowercase ( self: Dict ) -> Any: """simple docstring""" self._test_save_load_local() def lowercase ( self: Any ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
328
1
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> float: if digit_amount > 0: return round(number - int(UpperCamelCase__ ) , UpperCamelCase__ ) return number - int(UpperCamelCase__ ) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
67
'''simple docstring''' from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING __UpperCAmelCase =logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class a__ ( UpperCAmelCase__ ): def __init__( self : List[str] , *a : Union[str, Any] , **a : Optional[Any] ): """simple docstring""" super().__init__(*a , **a ) requires_backends(self , '''vision''' ) self.check_model_type(a ) def __call__( self : Any , a : Union[str, List[str], "Image.Image", List["Image.Image"]] , **a : Optional[int] ): """simple docstring""" return super().__call__(a , **a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , **a : Any ): """simple docstring""" return {}, {}, {} def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : List[str] ): """simple docstring""" __lowerCamelCase = load_image(a ) __lowerCamelCase = image.size __lowerCamelCase = self.image_processor(images=a , return_tensors=self.framework ) return model_inputs def SCREAMING_SNAKE_CASE__ ( self : int , a : Optional[Any] ): """simple docstring""" __lowerCamelCase = self.model(**a ) return model_outputs def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : Any ): """simple docstring""" __lowerCamelCase = model_outputs.predicted_depth __lowerCamelCase = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode='''bicubic''' , align_corners=a ) __lowerCamelCase = prediction.squeeze().cpu().numpy() __lowerCamelCase = (output * 2_55 / np.max(a )).astype('''uint8''' ) __lowerCamelCase = Image.fromarray(a ) __lowerCamelCase = {} __lowerCamelCase = predicted_depth __lowerCamelCase = depth return output_dict
67
1
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class UpperCamelCase ( unittest.TestCase ): """simple docstring""" def _lowercase (self : Optional[int]) -> Optional[int]: __snake_case : Optional[Any] = inspect.getfile(accelerate.test_utils) __snake_case : Dict = os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ['scripts', 'external_deps', 'test_metrics.py']) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 __snake_case : Tuple = test_metrics @require_cpu def _lowercase (self : Tuple) -> List[str]: debug_launcher(self.test_metrics.main , num_processes=1) @require_cpu def _lowercase (self : List[Any]) -> Dict: debug_launcher(self.test_metrics.main) @require_single_gpu def _lowercase (self : Union[str, Any]) -> Union[str, Any]: self.test_metrics.main() @require_multi_gpu def _lowercase (self : Tuple) -> List[str]: print(f"Found {torch.cuda.device_count()} devices.") __snake_case : Any = ['torchrun', f"--nproc_per_node={torch.cuda.device_count()}", self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(_A , env=os.environ.copy())
365
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class UpperCamelCase ( unittest.TestCase ): def _lowercase (self : Union[str, Any]) -> Optional[int]: __snake_case : Optional[Any] = 0 def _lowercase (self : Tuple) -> int: __snake_case : Optional[Any] = AutoImageProcessor.from_pretrained('openai/clip-vit-base-patch32') self.assertIsInstance(_A , _A) def _lowercase (self : str) -> List[str]: with tempfile.TemporaryDirectory() as tmpdirname: __snake_case : List[str] = Path(_A) / 'preprocessor_config.json' __snake_case : Optional[Any] = Path(_A) / 'config.json' json.dump( {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'} , open(_A , 'w') , ) json.dump({'model_type': 'clip'} , open(_A , 'w')) __snake_case : Optional[int] = AutoImageProcessor.from_pretrained(_A) self.assertIsInstance(_A , _A) def _lowercase (self : Any) -> Optional[int]: # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __snake_case : Any = Path(_A) / 'preprocessor_config.json' __snake_case : List[Any] = Path(_A) / 'config.json' json.dump( {'feature_extractor_type': 'CLIPFeatureExtractor', 'processor_class': 'CLIPProcessor'} , open(_A , 'w') , ) json.dump({'model_type': 'clip'} , open(_A , 'w')) __snake_case : Tuple = AutoImageProcessor.from_pretrained(_A) self.assertIsInstance(_A , _A) def _lowercase (self : List[Any]) -> Optional[Any]: with tempfile.TemporaryDirectory() as tmpdirname: __snake_case : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __snake_case : List[Any] = Path(_A) / 'preprocessor_config.json' __snake_case : Optional[Any] = Path(_A) / 'config.json' json.dump( {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'} , open(_A , 'w') , ) json.dump({'model_type': 'clip'} , open(_A , 'w')) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __snake_case : List[str] = AutoImageProcessor.from_pretrained(_A).to_dict() config_dict.pop('image_processor_type') __snake_case : Optional[int] = CLIPImageProcessor(**_A) # save in new folder model_config.save_pretrained(_A) config.save_pretrained(_A) __snake_case : Optional[int] = AutoImageProcessor.from_pretrained(_A) # make sure private variable is not incorrectly saved __snake_case : int = json.loads(config.to_json_string()) self.assertTrue('_processor_class' not in dict_as_saved) self.assertIsInstance(_A , _A) def _lowercase (self : Union[str, Any]) -> Optional[Any]: with tempfile.TemporaryDirectory() as tmpdirname: __snake_case : int = Path(_A) / 'preprocessor_config.json' json.dump( {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'} , open(_A , 'w') , ) __snake_case : List[str] = AutoImageProcessor.from_pretrained(_A) self.assertIsInstance(_A , _A) def _lowercase (self : Optional[int]) -> Dict: with self.assertRaisesRegex( _A , 'clip-base is not a local folder and is not a valid model identifier'): __snake_case : Tuple = AutoImageProcessor.from_pretrained('clip-base') def _lowercase (self : str) -> int: with self.assertRaisesRegex( _A , r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'): __snake_case : str = AutoImageProcessor.from_pretrained(_A , revision='aaaaaa') def _lowercase (self : List[Any]) -> str: with self.assertRaisesRegex( _A , 'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.' , ): __snake_case : List[Any] = AutoImageProcessor.from_pretrained('hf-internal-testing/config-no-model') def _lowercase (self : Optional[int]) -> List[str]: # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_A): __snake_case : Any = AutoImageProcessor.from_pretrained('hf-internal-testing/test_dynamic_image_processor') # If remote code is disabled, we can't load this config. with self.assertRaises(_A): __snake_case : Tuple = AutoImageProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_image_processor' , trust_remote_code=_A) __snake_case : Union[str, Any] = AutoImageProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_image_processor' , trust_remote_code=_A) self.assertEqual(image_processor.__class__.__name__ , 'NewImageProcessor') # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_A) __snake_case : Optional[int] = AutoImageProcessor.from_pretrained(_A , trust_remote_code=_A) self.assertEqual(reloaded_image_processor.__class__.__name__ , 'NewImageProcessor') def _lowercase (self : int) -> Optional[int]: try: AutoConfig.register('custom' , _A) AutoImageProcessor.register(_A , _A) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_A): AutoImageProcessor.register(_A , _A) with tempfile.TemporaryDirectory() as tmpdirname: __snake_case : Tuple = Path(_A) / 'preprocessor_config.json' __snake_case : Dict = Path(_A) / 'config.json' json.dump( {'feature_extractor_type': 'CLIPFeatureExtractor', 'processor_class': 'CLIPProcessor'} , open(_A , 'w') , ) json.dump({'model_type': 'clip'} , open(_A , 'w')) __snake_case : Tuple = CustomImageProcessor.from_pretrained(_A) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_A) __snake_case : Tuple = AutoImageProcessor.from_pretrained(_A) self.assertIsInstance(_A , _A) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def _lowercase (self : List[Any]) -> Tuple: class UpperCamelCase ( lowercase ): UpperCAmelCase : str = True try: AutoConfig.register('custom' , _A) AutoImageProcessor.register(_A , _A) # If remote code is not set, the default is to use local __snake_case : Tuple = AutoImageProcessor.from_pretrained('hf-internal-testing/test_dynamic_image_processor') self.assertEqual(image_processor.__class__.__name__ , 'NewImageProcessor') self.assertTrue(image_processor.is_local) # If remote code is disabled, we load the local one. __snake_case : Optional[int] = AutoImageProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_image_processor' , trust_remote_code=_A) self.assertEqual(image_processor.__class__.__name__ , 'NewImageProcessor') self.assertTrue(image_processor.is_local) # If remote is enabled, we load from the Hub __snake_case : List[Any] = AutoImageProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_image_processor' , trust_remote_code=_A) self.assertEqual(image_processor.__class__.__name__ , 'NewImageProcessor') self.assertTrue(not hasattr(_A , 'is_local')) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
95
0
def lowerCAmelCase_ ( __A ) -> bool: '''simple docstring''' return credit_card_number.startswith(("34", "35", "37", "4", "5", "6") ) def lowerCAmelCase_ ( __A ) -> bool: '''simple docstring''' UpperCAmelCase__ = credit_card_number UpperCAmelCase__ = 0 UpperCAmelCase__ = len(__A ) - 2 for i in range(__A, -1, -2 ): # double the value of every second digit UpperCAmelCase__ = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 UpperCAmelCase__ = cc_number[:i] + str(__A ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(__A ) - 1, -1, -2 ): total += int(cc_number[i] ) return total % 10 == 0 def lowerCAmelCase_ ( __A ) -> bool: '''simple docstring''' UpperCAmelCase__ = f"""{credit_card_number} is an invalid credit card number because""" if not credit_card_number.isdigit(): print(f"""{error_message} it has nonnumerical characters.""" ) return False if not 13 <= len(__A ) <= 16: print(f"""{error_message} of its length.""" ) return False if not validate_initial_digits(__A ): print(f"""{error_message} of its first two digits.""" ) return False if not luhn_validation(__A ): print(f"""{error_message} it fails the Luhn check.""" ) return False print(f"""{credit_card_number} is a valid credit card number.""" ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('4111111111111111') validate_credit_card_number('32323')
65
'''simple docstring''' from ..utils import DummyObject, requires_backends class _lowerCamelCase ( metaclass=lowercase__ ): '''simple docstring''' A_ : Optional[Any] = ["""flax""", """transformers"""] def __init__( self : Union[str, Any] , *_A : Dict , **_A : Any ) -> int: requires_backends(self , ['flax', 'transformers'] ) @classmethod def __lowerCAmelCase ( cls : Optional[Any] , *_A : List[Any] , **_A : Any ) -> List[str]: requires_backends(cls , ['flax', 'transformers'] ) @classmethod def __lowerCAmelCase ( cls : List[str] , *_A : Tuple , **_A : Optional[int] ) -> int: requires_backends(cls , ['flax', 'transformers'] ) class _lowerCamelCase ( metaclass=lowercase__ ): '''simple docstring''' A_ : Union[str, Any] = ["""flax""", """transformers"""] def __init__( self : Union[str, Any] , *_A : Any , **_A : int ) -> List[Any]: requires_backends(self , ['flax', 'transformers'] ) @classmethod def __lowerCAmelCase ( cls : Union[str, Any] , *_A : Optional[int] , **_A : Dict ) -> Optional[Any]: requires_backends(cls , ['flax', 'transformers'] ) @classmethod def __lowerCAmelCase ( cls : Tuple , *_A : Any , **_A : Union[str, Any] ) -> Dict: requires_backends(cls , ['flax', 'transformers'] ) class _lowerCamelCase ( metaclass=lowercase__ ): '''simple docstring''' A_ : Dict = ["""flax""", """transformers"""] def __init__( self : int , *_A : Optional[int] , **_A : Any ) -> List[Any]: requires_backends(self , ['flax', 'transformers'] ) @classmethod def __lowerCAmelCase ( cls : Any , *_A : int , **_A : str ) -> Any: requires_backends(cls , ['flax', 'transformers'] ) @classmethod def __lowerCAmelCase ( cls : Optional[Any] , *_A : Union[str, Any] , **_A : List[str] ) -> Optional[int]: requires_backends(cls , ['flax', 'transformers'] ) class _lowerCamelCase ( metaclass=lowercase__ ): '''simple docstring''' A_ : Optional[int] = ["""flax""", """transformers"""] def __init__( self : Tuple , *_A : Dict , **_A : str ) -> Optional[Any]: requires_backends(self , ['flax', 'transformers'] ) @classmethod def __lowerCAmelCase ( cls : str , *_A : Dict , **_A : Optional[Any] ) -> Dict: requires_backends(cls , ['flax', 'transformers'] ) @classmethod def __lowerCAmelCase ( cls : Any , *_A : List[str] , **_A : str ) -> Optional[int]: requires_backends(cls , ['flax', 'transformers'] )
331
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tensorflow_text_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ : Union[str, Any] = { """configuration_bert""": ["""BERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BertConfig""", """BertOnnxConfig"""], """tokenization_bert""": ["""BasicTokenizer""", """BertTokenizer""", """WordpieceTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Tuple = ["""BertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : List[str] = [ """BERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BertForMaskedLM""", """BertForMultipleChoice""", """BertForNextSentencePrediction""", """BertForPreTraining""", """BertForQuestionAnswering""", """BertForSequenceClassification""", """BertForTokenClassification""", """BertLayer""", """BertLMHeadModel""", """BertModel""", """BertPreTrainedModel""", """load_tf_weights_in_bert""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Tuple = [ """TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBertEmbeddings""", """TFBertForMaskedLM""", """TFBertForMultipleChoice""", """TFBertForNextSentencePrediction""", """TFBertForPreTraining""", """TFBertForQuestionAnswering""", """TFBertForSequenceClassification""", """TFBertForTokenClassification""", """TFBertLMHeadModel""", """TFBertMainLayer""", """TFBertModel""", """TFBertPreTrainedModel""", ] try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[int] = ["""TFBertTokenizer"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Any = [ """FlaxBertForCausalLM""", """FlaxBertForMaskedLM""", """FlaxBertForMultipleChoice""", """FlaxBertForNextSentencePrediction""", """FlaxBertForPreTraining""", """FlaxBertForQuestionAnswering""", """FlaxBertForSequenceClassification""", """FlaxBertForTokenClassification""", """FlaxBertModel""", """FlaxBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_fast import BertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bert import ( BERT_PRETRAINED_MODEL_ARCHIVE_LIST, BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLayer, BertLMHeadModel, BertModel, BertPreTrainedModel, load_tf_weights_in_bert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_bert import ( TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFBertEmbeddings, TFBertForMaskedLM, TFBertForMultipleChoice, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification, TFBertLMHeadModel, TFBertMainLayer, TFBertModel, TFBertPreTrainedModel, ) try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_tf import TFBertTokenizer try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_bert import ( FlaxBertForCausalLM, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, FlaxBertPreTrainedModel, ) else: import sys UpperCAmelCase__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
353
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests UpperCAmelCase__ : str = open # noqa: we just need to have a builtin inside this module to test it properly
301
0
'''simple docstring''' def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__ ) -> Optional[Any]: return x if y == 0 else greatest_common_divisor(__snake_case, x % y ) def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__ ) -> Dict: return (x * y) // greatest_common_divisor(__snake_case, __snake_case ) def UpperCAmelCase__ ( UpperCAmelCase__ = 20 ) -> List[Any]: A_ = 1 for i in range(1, n + 1 ): A_ = lcm(__snake_case, __snake_case ) return g if __name__ == "__main__": print(f"""{solution() = }""")
162
"""simple docstring""" import argparse import os import re import packaging.version __A : List[str] = '''examples/''' __A : int = { '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''), '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } __A : Dict = { '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } __A : Optional[int] = '''README.md''' def lowercase ( __snake_case : int , __snake_case : Any , __snake_case : int ): with open(__snake_case , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: lowercase_ : int = f.read() lowercase_ , lowercase_ : List[str] = REPLACE_PATTERNS[pattern] lowercase_ : Union[str, Any] = replace.replace('''VERSION''' , __snake_case ) lowercase_ : Optional[Any] = re_pattern.sub(__snake_case , __snake_case ) with open(__snake_case , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(__snake_case ) def lowercase ( __snake_case : int ): for folder, directories, fnames in os.walk(__snake_case ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('''research_projects''' ) if "legacy" in directories: directories.remove('''legacy''' ) for fname in fnames: if fname.endswith('''.py''' ): update_version_in_file(os.path.join(__snake_case , __snake_case ) , __snake_case , pattern='''examples''' ) def lowercase ( __snake_case : Optional[Any] , __snake_case : Optional[Any]=False ): for pattern, fname in REPLACE_FILES.items(): update_version_in_file(__snake_case , __snake_case , __snake_case ) if not patch: update_version_in_examples(__snake_case ) def lowercase ( ): lowercase_ : Union[str, Any] = '''🤗 Transformers currently provides the following architectures''' lowercase_ : Union[str, Any] = '''1. Want to contribute a new model?''' with open(__snake_case , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: lowercase_ : List[str] = f.readlines() # Find the start of the list. lowercase_ : Optional[Any] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 lowercase_ : str = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): lowercase_ : str = lines[index].replace( '''https://huggingface.co/docs/transformers/main/model_doc''' , '''https://huggingface.co/docs/transformers/model_doc''' , ) index += 1 with open(__snake_case , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(__snake_case ) def lowercase ( ): with open(REPLACE_FILES['''init'''] , '''r''' ) as f: lowercase_ : List[Any] = f.read() lowercase_ : List[str] = REPLACE_PATTERNS['''init'''][0].search(__snake_case ).groups()[0] return packaging.version.parse(__snake_case ) def lowercase ( __snake_case : Optional[Any]=False ): lowercase_ : str = get_version() if patch and default_version.is_devrelease: raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' ) if default_version.is_devrelease: lowercase_ : Optional[Any] = default_version.base_version elif patch: lowercase_ : Optional[int] = F'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}''' else: lowercase_ : Optional[int] = F'''{default_version.major}.{default_version.minor + 1}.0''' # Now let's ask nicely if that's the right one. lowercase_ : int = input(F'''Which version are you releasing? [{default_version}]''' ) if len(__snake_case ) == 0: lowercase_ : Dict = default_version print(F'''Updating version to {version}.''' ) global_version_update(__snake_case , patch=__snake_case ) if not patch: print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() def lowercase ( ): lowercase_ : List[Any] = get_version() lowercase_ : List[str] = F'''{current_version.major}.{current_version.minor + 1}.0.dev0''' lowercase_ : Any = current_version.base_version # Check with the user we got that right. lowercase_ : Tuple = input(F'''Which version are we developing now? [{dev_version}]''' ) if len(__snake_case ) == 0: lowercase_ : str = dev_version print(F'''Updating version to {version}.''' ) global_version_update(__snake_case ) print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') __A : Any = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
33
0
"""simple docstring""" from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
350
"""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. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _lowercase ( __a ): """simple docstring""" lowercase__ = '''facebook/bart-large-mnli''' lowercase__ = ( '''This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ''' '''should be the text to classify, and `labels`, which should be the list of labels to use for classification. ''' '''It returns the most likely label in the list of provided `labels` for the input text.''' ) lowercase__ = '''text_classifier''' lowercase__ = AutoTokenizer lowercase__ = AutoModelForSequenceClassification lowercase__ = ['''text''', ['''text''']] lowercase__ = ['''text'''] def UpperCAmelCase_ ( self : Optional[Any] ) -> int: '''simple docstring''' super().setup() __UpperCamelCase =self.model.config __UpperCamelCase =-1 for idx, label in config.idalabel.items(): if label.lower().startswith('''entail''' ): __UpperCamelCase =int(UpperCamelCase__ ) if self.entailment_id == -1: raise ValueError('''Could not determine the entailment ID from the model config, please pass it at init.''' ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Any ) -> Any: '''simple docstring''' __UpperCamelCase =labels return self.pre_processor( [text] * len(UpperCamelCase__ ) , [f"""This example is {label}""" for label in labels] , return_tensors='''pt''' , padding='''max_length''' , ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCamelCase__ : Any ) -> Union[str, Any]: '''simple docstring''' __UpperCamelCase =outputs.logits __UpperCamelCase =torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
85
0
"""simple docstring""" import math from collections.abc import Callable def snake_case_ ( A_ : Callable[[float], float], A_ : float, A_ : float ): '''simple docstring''' _lowerCamelCase : float = xa _lowerCamelCase : float = xa while True: if x_n == x_na or function(A_ ) == function(A_ ): raise ZeroDivisionError('''float division by zero, could not find root''' ) _lowerCamelCase : float = x_na - ( function(A_ ) / ((function(A_ ) - function(A_ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na _lowerCamelCase : int = x_na _lowerCamelCase : List[Any] = x_na def snake_case_ ( A_ : float ): '''simple docstring''' return math.pow(A_, 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
72
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a__ : Union[str, Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : float , **UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = kwargs.pop("padding_side" , "right" ) __SCREAMING_SNAKE_CASE = kwargs.pop("return_attention_mask" , UpperCAmelCase__ ) super().__init__(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , UpperCAmelCase__ : Union[bool, str, PaddingStrategy] = True , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(UpperCAmelCase__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __SCREAMING_SNAKE_CASE = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F""" to this method that includes {self.model_input_names[0]}, but you provided""" F""" {list(processed_features.keys() )}""" ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(UpperCAmelCase__ ) == 0: if return_attention_mask: __SCREAMING_SNAKE_CASE = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __SCREAMING_SNAKE_CASE = required_input[0] if isinstance(UpperCAmelCase__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __SCREAMING_SNAKE_CASE = 0 while len(required_input[index] ) == 0: index += 1 if index < len(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = required_input[index][0] if return_tensors is None: if is_tf_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "tf" elif is_torch_tensor(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "pt" elif isinstance(UpperCAmelCase__ , (int, float, list, tuple, np.ndarray) ): __SCREAMING_SNAKE_CASE = "np" else: raise ValueError( F"""type of {first_element} unknown: {type(UpperCAmelCase__ )}. """ "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __SCREAMING_SNAKE_CASE = to_numpy(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = [to_numpy(UpperCAmelCase__ ) for v in value] # Convert padding_strategy in PaddingStrategy __SCREAMING_SNAKE_CASE = self._get_padding_strategies(padding=UpperCAmelCase__ , max_length=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if not all(len(UpperCAmelCase__ ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) __SCREAMING_SNAKE_CASE = [] for i in range(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = {k: v[i] for k, v in processed_features.items()} # truncation __SCREAMING_SNAKE_CASE = self._truncate( UpperCAmelCase__ , max_length=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , truncation=UpperCAmelCase__ , ) truncated_inputs.append(UpperCAmelCase__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __SCREAMING_SNAKE_CASE = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __SCREAMING_SNAKE_CASE = PaddingStrategy.MAX_LENGTH __SCREAMING_SNAKE_CASE = {} for i in range(UpperCAmelCase__ ): # padding __SCREAMING_SNAKE_CASE = self._pad( truncated_inputs[i] , max_length=UpperCAmelCase__ , padding_strategy=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) for key, value in outputs.items(): if key not in batch_outputs: __SCREAMING_SNAKE_CASE = [] if value.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE = value.astype(np.floataa ) batch_outputs[key].append(UpperCAmelCase__ ) return BatchFeature(UpperCAmelCase__ , tensor_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> dict: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(UpperCAmelCase__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __SCREAMING_SNAKE_CASE = np.ones(len(UpperCAmelCase__ ) , dtype=np.intaa ) if needs_to_be_padded: __SCREAMING_SNAKE_CASE = max_length - len(UpperCAmelCase__ ) if self.padding_side == "right": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (0, difference) ) __SCREAMING_SNAKE_CASE = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __SCREAMING_SNAKE_CASE = np.pad( processed_features["attention_mask"] , (difference, 0) ) __SCREAMING_SNAKE_CASE = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __SCREAMING_SNAKE_CASE = np.pad( UpperCAmelCase__ , UpperCAmelCase__ , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Union[Dict[str, np.ndarray], BatchFeature] , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> str: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __SCREAMING_SNAKE_CASE = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) > max_length if needs_to_be_truncated: __SCREAMING_SNAKE_CASE = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __SCREAMING_SNAKE_CASE = processed_features["attention_mask"][:max_length] return processed_features def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[int]=None ) -> str: # Get padding strategy if padding is not False: if padding is True: __SCREAMING_SNAKE_CASE = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = PaddingStrategy(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = padding else: __SCREAMING_SNAKE_CASE = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined""" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
54
0
# Function to print upper half of diamond (pyramid) def A ( a_ ) -> str: for i in range(0 ,a_ ): for _ in range(0 ,n - i - 1 ): # printing spaces print(' ' ,end='' ) for _ in range(0 ,i + 1 ): # printing stars print('* ' ,end='' ) print() def A ( a_ ) -> Any: for i in range(a_ ,0 ,-1 ): for _ in range(a_ ,0 ,-1 ): # printing stars print('* ' ,end='' ) print() for _ in range(n - i + 1 ,0 ,-1 ): # printing spaces print(' ' ,end='' ) def A ( a_ ) -> Union[str, Any]: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(a_ ) # upper half reverse_floyd(a_ ) # lower half if __name__ == "__main__": print(R'''| /\ | |- | |- |--| |\ /| |-''') print(R'''|/ \| |- |_ |_ |__| | \/ | |_''') A_ :Optional[Any] = 1 while K: A_ :List[Any] = int(input('''enter the number and , and see the magic : ''')) print() pretty_print(user_number) A_ :Optional[int] = int(input('''press 0 to exit... and 1 to continue...''')) print('''Good Bye...''')
245
import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def A ( a_ ,a_ ,a_ ,a_ ,a_ ) -> Optional[int]: # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file __UpperCamelCase : Optional[int] =TapasConfig.from_json_file(a_ ) # set absolute/relative position embeddings parameter __UpperCamelCase : str =reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": __UpperCamelCase : Optional[Any] =TapasForQuestionAnswering(config=a_ ) elif task == "WTQ": # run_task_main.py hparams __UpperCamelCase : Optional[int] =4 __UpperCamelCase : Optional[Any] =True # hparam_utils.py hparams __UpperCamelCase : int =0.664_694 __UpperCamelCase : Any =0.207_951 __UpperCamelCase : Tuple =0.121_194 __UpperCamelCase : List[str] =True __UpperCamelCase : Dict =True __UpperCamelCase : Optional[Any] =False __UpperCamelCase : Optional[int] =0.0_352_513 __UpperCamelCase : Optional[Any] =TapasForQuestionAnswering(config=a_ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams __UpperCamelCase : List[Any] =4 __UpperCamelCase : List[str] =False # hparam_utils.py hparams __UpperCamelCase : List[str] =36.4_519 __UpperCamelCase : Dict =0.903_421 __UpperCamelCase : List[Any] =222.088 __UpperCamelCase : Optional[Any] =True __UpperCamelCase : Optional[int] =True __UpperCamelCase : Dict =True __UpperCamelCase : Dict =0.763_141 __UpperCamelCase : Union[str, Any] =TapasForQuestionAnswering(config=a_ ) elif task == "TABFACT": __UpperCamelCase : List[Any] =TapasForSequenceClassification(config=a_ ) elif task == "MLM": __UpperCamelCase : Optional[Any] =TapasForMaskedLM(config=a_ ) elif task == "INTERMEDIATE_PRETRAINING": __UpperCamelCase : Optional[Any] =TapasModel(config=a_ ) else: raise ValueError(F'Task {task} not supported.' ) print(F'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(a_ ,a_ ,a_ ) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(a_ ) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}' ) __UpperCamelCase : Optional[Any] =TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + 'vocab.txt' ,model_max_length=512 ) tokenizer.save_pretrained(a_ ) print('Used relative position embeddings:' ,model.config.reset_position_index_per_cell ) if __name__ == "__main__": A_ :Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''SQA''', type=str, help='''Model task for which to convert a checkpoint. Defaults to SQA.''' ) parser.add_argument( '''--reset_position_index_per_cell''', default=False, action='''store_true''', help='''Whether to use relative position embeddings or not. Defaults to True.''', ) parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--tapas_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained TAPAS 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_ :Union[str, Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
245
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, PNDMScheduler, StableDiffusionLDMaDPipeline, UNetaDConditionModel, ) from diffusers.utils import nightly, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS enable_full_determinism() class A_ ( unittest.TestCase ): '''simple docstring''' _UpperCamelCase : Tuple = StableDiffusionLDMaDPipeline _UpperCamelCase : List[Any] = TEXT_TO_IMAGE_PARAMS _UpperCamelCase : str = TEXT_TO_IMAGE_BATCH_PARAMS _UpperCamelCase : int = TEXT_TO_IMAGE_IMAGE_PARAMS def SCREAMING_SNAKE_CASE__ ( self ): torch.manual_seed(0 ) lowercase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) lowercase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=snake_case , set_alpha_to_one=snake_case , ) torch.manual_seed(0 ) lowercase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=6 , out_channels=6 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) lowercase = 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 , ) lowercase = CLIPTextModel(snake_case ) lowercase = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) lowercase = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case=0 ): if str(snake_case ).startswith('mps' ): lowercase = torch.manual_seed(snake_case ) else: lowercase = torch.Generator(device=snake_case ).manual_seed(snake_case ) lowercase = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self ): lowercase = 'cpu' # ensure determinism for the device-dependent torch.Generator lowercase = self.get_dummy_components() lowercase = StableDiffusionLDMaDPipeline(**snake_case ) lowercase = ldmad_pipe.to(snake_case ) ldmad_pipe.set_progress_bar_config(disable=snake_case ) lowercase = self.get_dummy_inputs(snake_case ) lowercase = ldmad_pipe(**snake_case ) lowercase , lowercase = output.rgb, output.depth lowercase = rgb[0, -3:, -3:, -1] lowercase = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) lowercase = np.array( [0.37_338_176, 0.70_247, 0.74_203_193, 0.51_643_604, 0.58_256_793, 0.60_932_136, 0.4_181_095, 0.48_355_877, 0.46_535_262] ) lowercase = np.array([103.46_727, 85.812_004, 87.849_236] ) assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb ).max() < 1E-2 assert np.abs(image_slice_depth.flatten() - expected_slice_depth ).max() < 1E-2 def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.get_dummy_components() lowercase = StableDiffusionLDMaDPipeline(**snake_case ) lowercase = ldmad_pipe.to(snake_case ) ldmad_pipe.set_progress_bar_config(disable=snake_case ) lowercase = self.get_dummy_inputs(snake_case ) lowercase = 3 * [inputs['prompt']] # forward lowercase = ldmad_pipe(**snake_case ) lowercase , lowercase = output.rgb, output.depth lowercase = rgb_slice_a[0, -3:, -3:, -1] lowercase = depth_slice_a[0, -3:, -1] lowercase = self.get_dummy_inputs(snake_case ) lowercase = 3 * [inputs.pop('prompt' )] lowercase = ldmad_pipe.tokenizer( snake_case , padding='max_length' , max_length=ldmad_pipe.tokenizer.model_max_length , truncation=snake_case , return_tensors='pt' , ) lowercase = text_inputs['input_ids'].to(snake_case ) lowercase = ldmad_pipe.text_encoder(snake_case )[0] lowercase = prompt_embeds # forward lowercase = ldmad_pipe(**snake_case ) lowercase , lowercase = output.rgb, output.depth lowercase = rgb_slice_a[0, -3:, -3:, -1] lowercase = depth_slice_a[0, -3:, -1] assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten() ).max() < 1E-4 assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten() ).max() < 1E-4 def SCREAMING_SNAKE_CASE__ ( self ): lowercase = 'cpu' # ensure determinism for the device-dependent torch.Generator lowercase = self.get_dummy_components() lowercase = PNDMScheduler(skip_prk_steps=snake_case ) lowercase = StableDiffusionLDMaDPipeline(**snake_case ) lowercase = ldmad_pipe.to(snake_case ) ldmad_pipe.set_progress_bar_config(disable=snake_case ) lowercase = self.get_dummy_inputs(snake_case ) lowercase = 'french fries' lowercase = ldmad_pipe(**snake_case , negative_prompt=snake_case ) lowercase , lowercase = output.rgb, output.depth lowercase = rgb[0, -3:, -3:, -1] lowercase = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) lowercase = np.array( [0.37_044, 0.71_811_503, 0.7_223_251, 0.48_603_675, 0.5_638_391, 0.6_364_948, 0.42_833_704, 0.4_901_315, 0.47_926_217] ) lowercase = np.array([107.84_738, 84.62_802, 89.962_135] ) assert np.abs(rgb_slice.flatten() - expected_slice_rgb ).max() < 1E-2 assert np.abs(depth_slice.flatten() - expected_slice_depth ).max() < 1E-2 @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case="cpu" , snake_case=torch.floataa , snake_case=0 ): lowercase = torch.Generator(device=snake_case ).manual_seed(snake_case ) lowercase = np.random.RandomState(snake_case ).standard_normal((1, 4, 64, 64) ) lowercase = torch.from_numpy(snake_case ).to(device=snake_case , dtype=snake_case ) lowercase = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self ): lowercase = StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d' ) lowercase = ldmad_pipe.to(snake_case ) ldmad_pipe.set_progress_bar_config(disable=snake_case ) lowercase = self.get_inputs(snake_case ) lowercase = ldmad_pipe(**snake_case ) lowercase , lowercase = output.rgb, output.depth lowercase = rgb[0, -3:, -3:, -1].flatten() lowercase = rgb[0, -3:, -1].flatten() assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512) lowercase = np.array( [0.53_805_465, 0.56_707_305, 0.5_486_515, 0.57_012_236, 0.5_814_511, 0.56_253_487, 0.54_843_014, 0.55_092_263, 0.6_459_706] ) lowercase = np.array( [0.9_263_781, 0.6_678_672, 0.5_486_515, 0.92_202_145, 0.67_831_135, 0.56_253_487, 0.9_241_694, 0.7_551_478, 0.6_459_706] ) assert np.abs(rgb_slice - expected_slice_rgb ).max() < 3E-3 assert np.abs(depth_slice - expected_slice_depth ).max() < 3E-3 @nightly @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case="cpu" , snake_case=torch.floataa , snake_case=0 ): lowercase = torch.Generator(device=snake_case ).manual_seed(snake_case ) lowercase = np.random.RandomState(snake_case ).standard_normal((1, 4, 64, 64) ) lowercase = torch.from_numpy(snake_case ).to(device=snake_case , dtype=snake_case ) lowercase = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 50, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self ): lowercase = StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d' ).to(snake_case ) ldmad_pipe.set_progress_bar_config(disable=snake_case ) lowercase = self.get_inputs(snake_case ) lowercase = ldmad_pipe(**snake_case ) lowercase , lowercase = output.rgb, output.depth lowercase = 0.495_586 lowercase = 0.33_795_515 lowercase = 112.48_518 lowercase = 98.489_746 assert np.abs(expected_rgb_mean - rgb.mean() ) < 1E-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1E-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1E-3 assert np.abs(expected_depth_std - depth.std() ) < 1E-3 def SCREAMING_SNAKE_CASE__ ( self ): lowercase = StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d-4c' ).to(snake_case ) ldmad_pipe.set_progress_bar_config(disable=snake_case ) lowercase = self.get_inputs(snake_case ) lowercase = ldmad_pipe(**snake_case ) lowercase , lowercase = output.rgb, output.depth lowercase = 0.4_194_127 lowercase = 0.35_375_586 lowercase = 0.5_638_502 lowercase = 0.34_686_103 assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512, 1) assert np.abs(expected_rgb_mean - rgb.mean() ) < 1E-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1E-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1E-3 assert np.abs(expected_depth_std - depth.std() ) < 1E-3
195
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter UpperCAmelCase = '''Create a default config file for Accelerate with only a few flags set.''' def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE="no" , __SCREAMING_SNAKE_CASE = default_json_config_file , __SCREAMING_SNAKE_CASE = False ): lowercase = Path(__SCREAMING_SNAKE_CASE ) path.parent.mkdir(parents=__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) if path.exists(): print( F'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.''' ) return False lowercase = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( F'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}''' ) lowercase = { 'compute_environment': 'LOCAL_MACHINE', 'mixed_precision': mixed_precision, } if torch.cuda.is_available(): lowercase = torch.cuda.device_count() lowercase = num_gpus lowercase = False if num_gpus > 1: lowercase = 'MULTI_GPU' else: lowercase = 'NO' elif is_xpu_available() and use_xpu: lowercase = torch.xpu.device_count() lowercase = num_xpus lowercase = False if num_xpus > 1: lowercase = 'MULTI_XPU' else: lowercase = 'NO' elif is_npu_available(): lowercase = torch.npu.device_count() lowercase = num_npus lowercase = False if num_npus > 1: lowercase = 'MULTI_NPU' else: lowercase = 'NO' else: lowercase = 0 lowercase = True lowercase = 1 lowercase = 'NO' lowercase = ClusterConfig(**__SCREAMING_SNAKE_CASE ) config.to_json_file(__SCREAMING_SNAKE_CASE ) return path def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase = parser.add_parser('default' , parents=__SCREAMING_SNAKE_CASE , help=__SCREAMING_SNAKE_CASE , formatter_class=__SCREAMING_SNAKE_CASE ) parser.add_argument( '--config_file' , default=__SCREAMING_SNAKE_CASE , 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\'.' ) , dest='save_location' , ) parser.add_argument( '--mixed_precision' , choices=['no', 'fp16', 'bf16'] , type=__SCREAMING_SNAKE_CASE , help='Whether or not to use mixed precision training. ' 'Choose between FP16 and BF16 (bfloat16) training. ' 'BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.' , default='no' , ) parser.set_defaults(func=__SCREAMING_SNAKE_CASE ) return parser def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE ): lowercase = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(F'''accelerate configuration saved at {config_file}''' )
195
1
'''simple docstring''' import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class __UpperCamelCase ( lowercase__ ): lowercase : Union[str, Any] = (DPMSolverSDEScheduler,) lowercase : Dict = 1_0 def a__ ( self :Union[str, Any] ,**_UpperCamelCase :Optional[Any] ): snake_case_ : Union[str, Any] = { """num_train_timesteps""": 1_1_0_0, """beta_start""": 0.00_01, """beta_end""": 0.02, """beta_schedule""": """linear""", """noise_sampler_seed""": 0, } config.update(**_UpperCamelCase ) return config def a__ ( self :int ): for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=_UpperCamelCase ) def a__ ( self :Tuple ): for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01] ,[0.00_02, 0.0_02, 0.02] ): self.check_over_configs(beta_start=_UpperCamelCase ,beta_end=_UpperCamelCase ) def a__ ( self :Optional[int] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_UpperCamelCase ) def a__ ( self :Optional[int] ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_UpperCamelCase ) def a__ ( self :Optional[Any] ): snake_case_ : Any = self.scheduler_classes[0] snake_case_ : Dict = self.get_scheduler_config() snake_case_ : str = scheduler_class(**_UpperCamelCase ) scheduler.set_timesteps(self.num_inference_steps ) snake_case_ : Dict = self.dummy_model() snake_case_ : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma snake_case_ : Any = sample.to(_UpperCamelCase ) for i, t in enumerate(scheduler.timesteps ): snake_case_ : List[Any] = scheduler.scale_model_input(_UpperCamelCase ,_UpperCamelCase ) snake_case_ : Tuple = model(_UpperCamelCase ,_UpperCamelCase ) snake_case_ : List[Any] = scheduler.step(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) snake_case_ : Any = output.prev_sample snake_case_ : Tuple = torch.sum(torch.abs(_UpperCamelCase ) ) snake_case_ : List[str] = torch.mean(torch.abs(_UpperCamelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 1_6_7.4_7_8_2_1_0_4_4_9_2_1_8_7_5 ) < 1E-2 assert abs(result_mean.item() - 0.21_78_70_59_64_56_52_77 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 1_7_1.5_9_3_5_2_1_1_1_8_1_6_4_0_6 ) < 1E-2 assert abs(result_mean.item() - 0.2_23_42_90_68_92_29_96_52 ) < 1E-3 else: assert abs(result_sum.item() - 1_6_2.5_2_3_8_3_4_2_2_8_5_1_5_6_2 ) < 1E-2 assert abs(result_mean.item() - 0.2_11_61_95_70_85_13_26 ) < 1E-3 def a__ ( self :str ): snake_case_ : str = self.scheduler_classes[0] snake_case_ : Any = self.get_scheduler_config(prediction_type="""v_prediction""" ) snake_case_ : Tuple = scheduler_class(**_UpperCamelCase ) scheduler.set_timesteps(self.num_inference_steps ) snake_case_ : Optional[int] = self.dummy_model() snake_case_ : Dict = self.dummy_sample_deter * scheduler.init_noise_sigma snake_case_ : int = sample.to(_UpperCamelCase ) for i, t in enumerate(scheduler.timesteps ): snake_case_ : List[str] = scheduler.scale_model_input(_UpperCamelCase ,_UpperCamelCase ) snake_case_ : int = model(_UpperCamelCase ,_UpperCamelCase ) snake_case_ : Tuple = scheduler.step(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) snake_case_ : str = output.prev_sample snake_case_ : Dict = torch.sum(torch.abs(_UpperCamelCase ) ) snake_case_ : Optional[Any] = torch.mean(torch.abs(_UpperCamelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 1_2_4.7_7_1_4_9_2_0_0_4_3_9_4_5_3 ) < 1E-2 assert abs(result_mean.item() - 0.1_62_26_28_90_14_81_62_84 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 1_2_8.1_6_6_3_3_6_0_5_9_5_7_0_3 ) < 1E-2 assert abs(result_mean.item() - 0.1_66_88_32_60_01_16_72_97 ) < 1E-3 else: assert abs(result_sum.item() - 1_1_9.8_4_8_7_5_4_8_8_2_8_1_2_5 ) < 1E-2 assert abs(result_mean.item() - 0.15_60_53_06_62_53_66_21 ) < 1E-3 def a__ ( self :Any ): snake_case_ : Tuple = self.scheduler_classes[0] snake_case_ : List[str] = self.get_scheduler_config() snake_case_ : Optional[Any] = scheduler_class(**_UpperCamelCase ) scheduler.set_timesteps(self.num_inference_steps ,device=_UpperCamelCase ) snake_case_ : Optional[Any] = self.dummy_model() snake_case_ : Optional[int] = self.dummy_sample_deter.to(_UpperCamelCase ) * scheduler.init_noise_sigma for t in scheduler.timesteps: snake_case_ : Dict = scheduler.scale_model_input(_UpperCamelCase ,_UpperCamelCase ) snake_case_ : str = model(_UpperCamelCase ,_UpperCamelCase ) snake_case_ : List[str] = scheduler.step(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) snake_case_ : List[str] = output.prev_sample snake_case_ : Dict = torch.sum(torch.abs(_UpperCamelCase ) ) snake_case_ : str = torch.mean(torch.abs(_UpperCamelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 1_6_7.4_6_9_5_7_3_9_7_4_6_0_9_3_8 ) < 1E-2 assert abs(result_mean.item() - 0.2_18_05_93_46_07_98_26_35 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 1_7_1.5_9_3_5_3_6_3_7_6_9_5_3_1_2 ) < 1E-2 assert abs(result_mean.item() - 0.2_23_42_90_83_82_41_57_71 ) < 1E-3 else: assert abs(result_sum.item() - 1_6_2.5_2_3_8_3_4_2_2_8_5_1_5_6_2 ) < 1E-2 assert abs(result_mean.item() - 0.2_11_61_95_70_85_13_26 ) < 1E-3 def a__ ( self :Optional[Any] ): snake_case_ : Dict = self.scheduler_classes[0] snake_case_ : Any = self.get_scheduler_config() snake_case_ : List[str] = scheduler_class(**_UpperCamelCase ,use_karras_sigmas=_UpperCamelCase ) scheduler.set_timesteps(self.num_inference_steps ,device=_UpperCamelCase ) snake_case_ : Dict = self.dummy_model() snake_case_ : Tuple = self.dummy_sample_deter.to(_UpperCamelCase ) * scheduler.init_noise_sigma snake_case_ : List[Any] = sample.to(_UpperCamelCase ) for t in scheduler.timesteps: snake_case_ : Any = scheduler.scale_model_input(_UpperCamelCase ,_UpperCamelCase ) snake_case_ : int = model(_UpperCamelCase ,_UpperCamelCase ) snake_case_ : List[Any] = scheduler.step(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) snake_case_ : Any = output.prev_sample snake_case_ : Optional[Any] = torch.sum(torch.abs(_UpperCamelCase ) ) snake_case_ : Dict = torch.mean(torch.abs(_UpperCamelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 1_7_6.6_6_9_7_4_1_3_5_7_4_2_1_8_8 ) < 1E-2 assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11 ) < 1E-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 1_7_7.6_3_6_5_3_5_6_4_4_5_3_1_2_5 ) < 1E-2 assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11 ) < 1E-2 else: assert abs(result_sum.item() - 1_7_0.3_1_3_5_2_2_3_3_8_8_6_7_2 ) < 1E-2 assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11 ) < 1E-2
361
'''simple docstring''' from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer __A : Tuple = logging.get_logger(__name__) __A : List[Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } __A : str = { 'vocab_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json' }, 'merges_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt' }, 'tokenizer_config_file': { 'facebook/blenderbot_small-90M': ( 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json' ) }, } __A : Optional[Any] = { 'facebook/blenderbot_small-90M': 512, } class __UpperCamelCase ( lowercase__ ): lowercase : str = VOCAB_FILES_NAMES lowercase : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP lowercase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Dict = BlenderbotSmallTokenizer def __init__( self :str ,_UpperCamelCase :Optional[int]=None ,_UpperCamelCase :Union[str, Any]=None ,_UpperCamelCase :Tuple="<|endoftext|>" ,_UpperCamelCase :int="<|endoftext|>" ,_UpperCamelCase :Dict="<|endoftext|>" ,_UpperCamelCase :Optional[Any]=False ,_UpperCamelCase :List[Any]=True ,**_UpperCamelCase :Any ,): super().__init__( ByteLevelBPETokenizer( vocab=_UpperCamelCase ,merges=_UpperCamelCase ,add_prefix_space=_UpperCamelCase ,trim_offsets=_UpperCamelCase ,) ,bos_token=_UpperCamelCase ,eos_token=_UpperCamelCase ,unk_token=_UpperCamelCase ,**_UpperCamelCase ,) snake_case_ : Any = add_prefix_space def a__ ( self :Optional[Any] ,_UpperCamelCase :int ,_UpperCamelCase :Optional[Any]=None ): snake_case_ : List[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def a__ ( self :int ,_UpperCamelCase :List[int] ,_UpperCamelCase :Optional[List[int]] = None ): snake_case_ : int = [self.sep_token_id] snake_case_ : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
8
0
'''simple docstring''' import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed 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 ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class _lowercase : '''simple docstring''' def __init__( self : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str]=13 , SCREAMING_SNAKE_CASE__ : Any=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=99 , SCREAMING_SNAKE_CASE__ : List[str]=64 , SCREAMING_SNAKE_CASE__ : Tuple=5 , SCREAMING_SNAKE_CASE__ : List[str]=4 , SCREAMING_SNAKE_CASE__ : int=37 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=5_12 , SCREAMING_SNAKE_CASE__ : str=16 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : List[str]=0.0_2 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : Any=4 , SCREAMING_SNAKE_CASE__ : List[Any]=None , ) -> int: __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = seq_length __lowerCAmelCase = is_training __lowerCAmelCase = use_input_mask __lowerCAmelCase = use_token_type_ids __lowerCAmelCase = use_labels __lowerCAmelCase = vocab_size __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 = max_position_embeddings __lowerCAmelCase = type_vocab_size __lowerCAmelCase = type_sequence_label_size __lowerCAmelCase = initializer_range __lowerCAmelCase = num_labels __lowerCAmelCase = num_choices __lowerCAmelCase = scope __lowerCAmelCase = vocab_size - 1 def a ( self : str ) -> Any: __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase = None if self.use_input_mask: __lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase = None if self.use_labels: __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase = self.get_config() return config, input_ids, input_mask, token_labels def a ( self : List[Any] ) -> Tuple: return GPTNeoXConfig( 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 , pad_token_id=self.pad_token_id , ) def a ( self : Tuple ) -> Any: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = self.prepare_config_and_inputs() __lowerCAmelCase = True return config, input_ids, input_mask, token_labels def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: __lowerCAmelCase = GPTNeoXModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ) -> Any: __lowerCAmelCase = True __lowerCAmelCase = GPTNeoXModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: __lowerCAmelCase = GPTNeoXForCausalLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: __lowerCAmelCase = self.num_labels __lowerCAmelCase = GPTNeoXForQuestionAnswering(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=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 a ( self : str , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: __lowerCAmelCase = self.num_labels __lowerCAmelCase = GPTNeoXForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: __lowerCAmelCase = self.num_labels __lowerCAmelCase = GPTNeoXForTokenClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a ( self : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: __lowerCAmelCase = True __lowerCAmelCase = GPTNeoXForCausalLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() # first forward pass __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __lowerCAmelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) __lowerCAmelCase = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __lowerCAmelCase = torch.cat([input_ids, next_tokens] , dim=-1 ) __lowerCAmelCase = torch.cat([input_mask, next_mask] , dim=-1 ) __lowerCAmelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = output_from_no_past["""hidden_states"""][0] __lowerCAmelCase = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , )["""hidden_states"""][0] # select random slice __lowerCAmelCase = ids_tensor((1,) , output_from_past.shape[-1] ).item() __lowerCAmelCase = output_from_no_past[:, -3:, random_slice_idx].detach() __lowerCAmelCase = 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(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) def a ( self : List[Any] ) -> int: __lowerCAmelCase = self.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = config_and_inputs __lowerCAmelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class _lowercase ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' _SCREAMING_SNAKE_CASE : str = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE : Union[str, Any] = (GPTNeoXForCausalLM,) if is_torch_available() else () _SCREAMING_SNAKE_CASE : int = ( { """feature-extraction""": GPTNeoXModel, """question-answering""": GPTNeoXForQuestionAnswering, """text-classification""": GPTNeoXForSequenceClassification, """text-generation""": GPTNeoXForCausalLM, """token-classification""": GPTNeoXForTokenClassification, """zero-shot""": GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE : Dict = False _SCREAMING_SNAKE_CASE : Tuple = False _SCREAMING_SNAKE_CASE : List[Any] = False _SCREAMING_SNAKE_CASE : Union[str, Any] = False def a ( self : Optional[Any] ) -> Union[str, Any]: __lowerCAmelCase = GPTNeoXModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=64 , num_attention_heads=8 ) def a ( self : List[str] ) -> Optional[int]: self.config_tester.run_common_tests() def a ( self : int ) -> Optional[Any]: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Union[str, Any]: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[int]: # This regression test was failing with PyTorch < 1.3 __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_decoder() __lowerCAmelCase = None self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Optional[int]: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] ) -> Tuple: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> int: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Dict: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) def a ( self : str ) -> Optional[int]: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason="""Feed forward chunking is not implemented""" ) def a ( self : str ) -> List[str]: pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = ids_tensor([1, 10] , config.vocab_size ) __lowerCAmelCase = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __lowerCAmelCase = GPTNeoXModel(SCREAMING_SNAKE_CASE__ ) original_model.to(SCREAMING_SNAKE_CASE__ ) original_model.eval() __lowerCAmelCase = original_model(SCREAMING_SNAKE_CASE__ ).last_hidden_state __lowerCAmelCase = original_model(SCREAMING_SNAKE_CASE__ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __lowerCAmelCase = {"""type""": scaling_type, """factor""": 1_0.0} __lowerCAmelCase = GPTNeoXModel(SCREAMING_SNAKE_CASE__ ) scaled_model.to(SCREAMING_SNAKE_CASE__ ) scaled_model.eval() __lowerCAmelCase = scaled_model(SCREAMING_SNAKE_CASE__ ).last_hidden_state __lowerCAmelCase = scaled_model(SCREAMING_SNAKE_CASE__ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-5 ) ) @require_torch class _lowercase ( unittest.TestCase ): '''simple docstring''' @slow def a ( self : Dict ) -> List[Any]: __lowerCAmelCase = AutoTokenizer.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) for checkpointing in [True, False]: __lowerCAmelCase = GPTNeoXForCausalLM.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE__ ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 __lowerCAmelCase = """My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure""" __lowerCAmelCase = model.generate(**SCREAMING_SNAKE_CASE__ , do_sample=SCREAMING_SNAKE_CASE__ , max_new_tokens=20 ) __lowerCAmelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ )[0] self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
229
'''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
1
"""simple docstring""" 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 snake_case : def __init__( self , __UpperCAmelCase , ) ->Union[str, Any]: a_ = parent a_ = 13 a_ = 7 a_ = True a_ = True a_ = True a_ = 99 a_ = 32 a_ = 2 a_ = 4 a_ = 37 a_ = "gelu" a_ = 0.1 a_ = 0.1 a_ = 5_12 a_ = 16 a_ = 2 a_ = 0.02 a_ = 3 a_ = 4 a_ = None def UpperCAmelCase__ ( self) ->List[str]: a_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) a_ = None if self.use_input_mask: a_ = random_attention_mask([self.batch_size, self.seq_length]) a_ = None a_ = None a_ = None if self.use_labels: a_ = ids_tensor([self.batch_size] , self.type_sequence_label_size) a_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) a_ = ids_tensor([self.batch_size] , self.num_choices) a_ = 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) ->str: ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) = self.prepare_config_and_inputs() a_ = True a_ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) a_ = 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 , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) ->List[Any]: a_ = TFEsmModel(config=__UpperCAmelCase) a_ = {"input_ids": input_ids, "attention_mask": input_mask} a_ = model(__UpperCAmelCase) a_ = [input_ids, input_mask] a_ = model(__UpperCAmelCase) a_ = model(__UpperCAmelCase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) ->Tuple: a_ = True a_ = TFEsmModel(config=__UpperCAmelCase) a_ = { "input_ids": input_ids, "attention_mask": input_mask, "encoder_hidden_states": encoder_hidden_states, "encoder_attention_mask": encoder_attention_mask, } a_ = model(__UpperCAmelCase) a_ = [input_ids, input_mask] a_ = model(__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase) # Also check the case where encoder outputs are not passed a_ = 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 , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) ->str: a_ = TFEsmForMaskedLM(config=__UpperCAmelCase) a_ = model([input_ids, input_mask]) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) ->Union[str, Any]: a_ = self.num_labels a_ = TFEsmForTokenClassification(config=__UpperCAmelCase) a_ = {"input_ids": input_ids, "attention_mask": input_mask} a_ = model(__UpperCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def UpperCAmelCase__ ( self) ->List[Any]: a_ = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) = config_and_inputs a_ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class snake_case ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): a_ : int = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) a_ : Union[str, Any] = ( { """feature-extraction""": TFEsmModel, """fill-mask""": TFEsmForMaskedLM, """text-classification""": TFEsmForSequenceClassification, """token-classification""": TFEsmForTokenClassification, """zero-shot""": TFEsmForSequenceClassification, } if is_tf_available() else {} ) a_ : Dict = False a_ : Union[str, Any] = False def UpperCAmelCase__ ( self) ->Any: a_ = TFEsmModelTester(self) a_ = ConfigTester(self , config_class=__UpperCAmelCase , hidden_size=37) def UpperCAmelCase__ ( self) ->str: self.config_tester.run_common_tests() def UpperCAmelCase__ ( self) ->Dict: a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase) def UpperCAmelCase__ ( self) ->Tuple: a_ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*__UpperCAmelCase) def UpperCAmelCase__ ( self) ->str: a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__UpperCAmelCase) def UpperCAmelCase__ ( self) ->str: a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase) @slow def UpperCAmelCase__ ( self) ->Union[str, Any]: for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ = TFEsmModel.from_pretrained(__UpperCAmelCase) self.assertIsNotNone(__UpperCAmelCase) @unittest.skip("Protein models do not support embedding resizing.") def UpperCAmelCase__ ( self) ->Any: pass @unittest.skip("Protein models do not support embedding resizing.") def UpperCAmelCase__ ( self) ->Union[str, Any]: pass def UpperCAmelCase__ ( self) ->Any: a_ , a_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a_ = 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 a_ = model.get_bias() assert isinstance(__UpperCAmelCase , __UpperCAmelCase) for k, v in name.items(): assert isinstance(__UpperCAmelCase , tf.Variable) else: a_ = model.get_output_embeddings() assert x is None a_ = model.get_bias() assert name is None @require_tf class snake_case ( unittest.TestCase ): @slow def UpperCAmelCase__ ( self) ->str: a_ = TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D") a_ = tf.constant([[0, 1, 2, 3, 4, 5]]) a_ = model(__UpperCAmelCase)[0] a_ = [1, 6, 33] self.assertEqual(list(output.numpy().shape) , __UpperCAmelCase) # compare the actual values for a slice. a_ = tf.constant( [ [ [8.921_518, -10.589_814, -6.4_671_307], [-6.3_967_156, -13.911_377, -1.1_211_915], [-7.781_247, -13.951_557, -3.740_592], ] ]) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2)) @slow def UpperCAmelCase__ ( self) ->List[str]: a_ = TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D") a_ = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]) a_ = model(__UpperCAmelCase)[0] # compare the actual values for a slice. a_ = tf.constant( [ [ [0.14_443_092, 0.54_125_327, 0.3_247_739], [0.30_340_484, 0.00_526_676, 0.31_077_722], [0.32_278_043, -0.24_987_096, 0.3_414_628], ] ]) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
303
"""simple docstring""" import numpy as np import torch from imwatermark import WatermarkEncoder # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66 UpperCamelCase_ = 0b10_11_00_11_11_10_11_00_10_01_00_00_01_11_10_11_10_11_00_01_10_01_11_10 # bin(x)[2:] gives bits of x as str, use int to convert them to 0/1 UpperCamelCase_ = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]] class snake_case : def __init__( self) ->Optional[int]: a_ = WATERMARK_BITS a_ = WatermarkEncoder() self.encoder.set_watermark("bits" , self.watermark) def UpperCAmelCase__ ( self , __UpperCAmelCase) ->Optional[int]: # can't encode images that are smaller than 256 if images.shape[-1] < 2_56: return images a_ = (2_55 * (images / 2 + 0.5)).cpu().permute(0 , 2 , 3 , 1).float().numpy() a_ = [self.encoder.encode(__UpperCAmelCase , "dwtDct") for image in images] a_ = torch.from_numpy(np.array(__UpperCAmelCase)).permute(0 , 3 , 1 , 2) a_ = torch.clamp(2 * (images / 2_55 - 0.5) , min=-1.0 , max=1.0) return images
303
1
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[List[PIL.Image.Image], np.ndarray] __magic_name__ :Optional[List[bool]] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.26.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version(""">=""", """0.0.12""") ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :np.ndarray __magic_name__ :List[bool] from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
293
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _lowerCAmelCase ( yaml.SafeLoader ): """simple docstring""" def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[Any] = [self.constructed_objects[key_node] for key_node, _ in node.value] lowerCAmelCase__ :str = [tuple(__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else key for key in keys] lowerCAmelCase__ :Optional[int] = Counter(__UpperCAmelCase ) lowerCAmelCase__ :int = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F"Got duplicate yaml keys: {duplicate_keys}" ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().construct_mapping(__UpperCAmelCase , deep=__UpperCAmelCase ) self._check_no_duplicates_on_constructed_node(__UpperCAmelCase ) return mapping def __A (_SCREAMING_SNAKE_CASE ) ->Tuple[Optional[str], str]: """simple docstring""" lowerCAmelCase__ :Optional[Any] = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: lowerCAmelCase__ :Optional[int] = full_content[1:].index('---' ) + 1 lowerCAmelCase__ :Union[str, Any] = '\n'.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :List[str] = {"""train_eval_index"""} # train-eval-index in the YAML metadata @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(__UpperCAmelCase ) else: return cls() def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path.exists(): with open(__UpperCAmelCase , encoding='utf-8' ) as readme_file: lowerCAmelCase__ :Optional[Any] = readme_file.read() else: lowerCAmelCase__ :Union[str, Any] = None lowerCAmelCase__ :Union[str, Any] = self._to_readme(__UpperCAmelCase ) with open(__UpperCAmelCase , 'w' , encoding='utf-8' ) as readme_file: readme_file.write(__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase = None ): '''simple docstring''' if readme_content is not None: lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = _split_yaml_from_readme(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = '---\n' + self.to_yaml_string() + '---\n' + content else: lowerCAmelCase__ :str = '---\n' + self.to_yaml_string() + '---\n' return full_content @classmethod def snake_case ( cls , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = yaml.load(__UpperCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields lowerCAmelCase__ :int = { (key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' return yaml.safe_dump( { (key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=__UpperCAmelCase , allow_unicode=__UpperCAmelCase , encoding='utf-8' , ).decode('utf-8' ) __A = { """image-classification""": [], """translation""": [], """image-segmentation""": [], """fill-mask""": [], """automatic-speech-recognition""": [], """token-classification""": [], """sentence-similarity""": [], """audio-classification""": [], """question-answering""": [], """summarization""": [], """zero-shot-classification""": [], """table-to-text""": [], """feature-extraction""": [], """other""": [], """multiple-choice""": [], """text-classification""": [], """text-to-image""": [], """text2text-generation""": [], """zero-shot-image-classification""": [], """tabular-classification""": [], """tabular-regression""": [], """image-to-image""": [], """tabular-to-text""": [], """unconditional-image-generation""": [], """text-retrieval""": [], """text-to-speech""": [], """object-detection""": [], """audio-to-audio""": [], """text-generation""": [], """conversational""": [], """table-question-answering""": [], """visual-question-answering""": [], """image-to-text""": [], """reinforcement-learning""": [], """voice-activity-detection""": [], """time-series-forecasting""": [], """document-question-answering""": [], } if __name__ == "__main__": from argparse import ArgumentParser __A = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""") ap.add_argument("""readme_filepath""") __A = ap.parse_args() __A = Path(args.readme_filepath) __A = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
293
1
import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class A_ ( unittest.TestCase ): def _lowerCAmelCase (self :Tuple )-> int: __A = inspect.getfile(accelerate.test_utils ) __A = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) __A = os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def _lowerCAmelCase (self :int )-> str: __A = f""" {self.test_dir}/xla_spawn.py --num_cores 8 {self.test_file_path} """.split() __A = [sys.executable] + distributed_args execute_subprocess_async(_UpperCamelCase , env=os.environ.copy() )
250
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case__ : Union[str, Any] = { 'configuration_blenderbot_small': [ 'BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BlenderbotSmallConfig', 'BlenderbotSmallOnnxConfig', ], 'tokenization_blenderbot_small': ['BlenderbotSmallTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : Dict = ['BlenderbotSmallTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : int = [ 'BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST', 'BlenderbotSmallForCausalLM', 'BlenderbotSmallForConditionalGeneration', 'BlenderbotSmallModel', 'BlenderbotSmallPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : List[str] = [ 'TFBlenderbotSmallForConditionalGeneration', 'TFBlenderbotSmallModel', 'TFBlenderbotSmallPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : str = [ 'FlaxBlenderbotSmallForConditionalGeneration', 'FlaxBlenderbotSmallModel', 'FlaxBlenderbotSmallPreTrainedModel', ] if TYPE_CHECKING: from .configuration_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotSmallConfig, BlenderbotSmallOnnxConfig, ) from .tokenization_blenderbot_small import BlenderbotSmallTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotSmallForCausalLM, BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel, BlenderbotSmallPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot_small import ( TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel, TFBlenderbotSmallPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, FlaxBlenderbotSmallPreTrainedModel, ) else: import sys snake_case__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
250
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 lowercase__ : str = "scheduler_config.json" class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" _snake_case = 1 _snake_case = 2 _snake_case = 3 _snake_case = 4 _snake_case = 5 @dataclass class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" _snake_case = 42 class SCREAMING_SNAKE_CASE__ : """simple docstring""" _snake_case = SCHEDULER_CONFIG_NAME _snake_case = ['dtype'] _snake_case = [] _snake_case = True @classmethod def A__ ( cls , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , )-> str: '''simple docstring''' __UpperCamelCase , __UpperCamelCase = cls.load_config( pretrained_model_name_or_path=SCREAMING_SNAKE_CASE_ , subfolder=SCREAMING_SNAKE_CASE_ , return_unused_kwargs=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) __UpperCamelCase , __UpperCamelCase = cls.from_config(SCREAMING_SNAKE_CASE_ , return_unused_kwargs=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if hasattr(SCREAMING_SNAKE_CASE_ , '''create_state''' ) and getattr(SCREAMING_SNAKE_CASE_ , '''has_state''' , SCREAMING_SNAKE_CASE_ ): __UpperCamelCase = scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def A__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , **SCREAMING_SNAKE_CASE_ )-> Tuple: '''simple docstring''' self.save_config(save_directory=SCREAMING_SNAKE_CASE_ , push_to_hub=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @property def A__ ( self )-> Dict: '''simple docstring''' return self._get_compatibles() @classmethod def A__ ( cls )-> str: '''simple docstring''' __UpperCamelCase = list(set([cls.__name__] + cls._compatibles ) ) __UpperCamelCase = importlib.import_module(__name__.split('''.''' )[0] ) __UpperCamelCase = [ getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for c in compatible_classes_str if hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] return compatible_classes def A_ ( snake_case : jnp.ndarray , snake_case : Tuple[int] ) -> jnp.ndarray: '''simple docstring''' assert len(snake_case ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(snake_case ) - x.ndim) ) , snake_case ) def A_ ( snake_case : int , snake_case : Optional[Any]=0.999 , snake_case : Dict=jnp.floataa ) -> jnp.ndarray: '''simple docstring''' def alpha_bar(snake_case : Optional[Any] ): return math.cos((time_step + 0.008) / 1.008 * math.pi / 2 ) ** 2 __UpperCamelCase = [] for i in range(snake_case ): __UpperCamelCase = i / num_diffusion_timesteps __UpperCamelCase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(snake_case ) / alpha_bar(snake_case ) , snake_case ) ) return jnp.array(snake_case , dtype=snake_case ) @flax.struct.dataclass class SCREAMING_SNAKE_CASE__ : """simple docstring""" _snake_case = 42 _snake_case = 42 _snake_case = 42 @classmethod def A__ ( cls , SCREAMING_SNAKE_CASE_ )-> Optional[int]: '''simple docstring''' __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(SCREAMING_SNAKE_CASE_ , axis=0 ) return cls( alphas=SCREAMING_SNAKE_CASE_ , betas=SCREAMING_SNAKE_CASE_ , alphas_cumprod=SCREAMING_SNAKE_CASE_ , ) def A_ ( snake_case : CommonSchedulerState , snake_case : jnp.ndarray , snake_case : jnp.ndarray , snake_case : jnp.ndarray ) -> Optional[int]: '''simple docstring''' __UpperCamelCase = state.alphas_cumprod __UpperCamelCase = alphas_cumprod[timesteps] ** 0.5 __UpperCamelCase = sqrt_alpha_prod.flatten() __UpperCamelCase = broadcast_to_shape_from_left(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(snake_case , original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def A_ ( snake_case : CommonSchedulerState , snake_case : jnp.ndarray , snake_case : jnp.ndarray , snake_case : jnp.ndarray ) -> str: '''simple docstring''' __UpperCamelCase , __UpperCamelCase = get_sqrt_alpha_prod(snake_case , snake_case , snake_case , snake_case ) __UpperCamelCase = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def A_ ( snake_case : CommonSchedulerState , snake_case : jnp.ndarray , snake_case : jnp.ndarray , snake_case : jnp.ndarray ) -> List[Any]: '''simple docstring''' __UpperCamelCase , __UpperCamelCase = get_sqrt_alpha_prod(snake_case , snake_case , snake_case , snake_case ) __UpperCamelCase = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
328
import argparse 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 ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowercase__ : List[str] = 1_6 lowercase__ : str = 3_2 def A_ ( snake_case : Accelerator , snake_case : int = 16 ) -> Optional[Any]: '''simple docstring''' __UpperCamelCase = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __UpperCamelCase = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(snake_case : Union[str, Any] ): # max_length=None => use the model max length (it's actually the default) __UpperCamelCase = 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 # starting with the main process first: with accelerator.main_process_first(): __UpperCamelCase = datasets.map( snake_case , batched=snake_case , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __UpperCamelCase = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(snake_case : str ): # On TPU it's best to pad everything to the same length or training will be very slow. __UpperCamelCase = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __UpperCamelCase = 16 elif accelerator.mixed_precision != "no": __UpperCamelCase = 8 else: __UpperCamelCase = None return tokenizer.pad( snake_case , padding='''longest''' , max_length=snake_case , pad_to_multiple_of=snake_case , return_tensors='''pt''' , ) # Instantiate dataloaders. __UpperCamelCase = DataLoader( tokenized_datasets['''train'''] , shuffle=snake_case , collate_fn=snake_case , batch_size=snake_case ) __UpperCamelCase = DataLoader( tokenized_datasets['''validation'''] , shuffle=snake_case , collate_fn=snake_case , batch_size=snake_case ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowercase__ : Union[str, Any] = mocked_dataloaders # noqa: F811 def A_ ( snake_case : List[str] , snake_case : List[Any] ) -> Tuple: '''simple docstring''' if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , snake_case ) == "1": __UpperCamelCase = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: __UpperCamelCase = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='''all''' , project_dir=args.project_dir ) else: __UpperCamelCase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __UpperCamelCase = config['''lr'''] __UpperCamelCase = int(config['''num_epochs'''] ) __UpperCamelCase = int(config['''seed'''] ) __UpperCamelCase = int(config['''batch_size'''] ) set_seed(snake_case ) __UpperCamelCase , __UpperCamelCase = get_dataloaders(snake_case , snake_case ) __UpperCamelCase = evaluate.load('''glue''' , '''mrpc''' ) # If the batch size is too big we use gradient accumulation __UpperCamelCase = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: __UpperCamelCase = batch_size // MAX_GPU_BATCH_SIZE __UpperCamelCase = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) __UpperCamelCase = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=snake_case ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __UpperCamelCase = model.to(accelerator.device ) # Instantiate optimizer __UpperCamelCase = AdamW(params=model.parameters() , lr=snake_case ) # Instantiate scheduler __UpperCamelCase = get_linear_schedule_with_warmup( optimizer=snake_case , num_warmup_steps=100 , num_training_steps=(len(snake_case ) * num_epochs) // gradient_accumulation_steps , ) # 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. __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = accelerator.prepare( snake_case , snake_case , snake_case , snake_case , snake_case ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: __UpperCamelCase = os.path.split(snake_case )[-1].split('''.''' )[0] accelerator.init_trackers(snake_case , snake_case ) # Now we train the model for epoch in range(snake_case ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: __UpperCamelCase = 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 ) __UpperCamelCase = model(**snake_case ) __UpperCamelCase = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() __UpperCamelCase = loss / gradient_accumulation_steps accelerator.backward(snake_case ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): __UpperCamelCase = model(**snake_case ) __UpperCamelCase = outputs.logits.argmax(dim=-1 ) __UpperCamelCase , __UpperCamelCase = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=snake_case , references=snake_case , ) __UpperCamelCase = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"epoch {epoch}:" , snake_case ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { '''accuracy''': eval_metric['''accuracy'''], '''f1''': eval_metric['''f1'''], '''train_loss''': total_loss.item() / len(snake_case ), '''epoch''': epoch, } , step=snake_case , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def A_ ( ) -> Optional[Any]: '''simple docstring''' __UpperCamelCase = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=snake_case , default=snake_case , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) parser.add_argument( '''--with_tracking''' , action='''store_true''' , help='''Whether to load in all available experiment trackers from the environment and use them for logging.''' , ) parser.add_argument( '''--project_dir''' , type=snake_case , default='''logs''' , help='''Location on where to store experiment tracking logs` and relevent project information''' , ) __UpperCamelCase = parser.parse_args() __UpperCamelCase = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(snake_case , snake_case ) if __name__ == "__main__": main()
328
1
import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict lowercase_ = namedtuple( """_TestCommandArgs""", [ """dataset""", """name""", """cache_dir""", """data_dir""", """all_configs""", """save_infos""", """ignore_verifications""", """force_redownload""", """clear_cache""", ], defaults=[None, None, None, False, False, False, False, False], ) def __UpperCamelCase (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: return (abs(source - target ) / target) < 0.0_1 @pytest.mark.integration def __UpperCamelCase (_SCREAMING_SNAKE_CASE ) -> Dict: lowercase__ = _TestCommandArgs(dataset=_SCREAMING_SNAKE_CASE , all_configs=_SCREAMING_SNAKE_CASE , save_infos=_SCREAMING_SNAKE_CASE ) lowercase__ = TestCommand(*_SCREAMING_SNAKE_CASE ) test_command.run() lowercase__ = os.path.join(_SCREAMING_SNAKE_CASE , 'README.md' ) assert os.path.exists(_SCREAMING_SNAKE_CASE ) lowercase__ = DatasetInfosDict.from_directory(_SCREAMING_SNAKE_CASE ) lowercase__ = DatasetInfosDict( { 'default': DatasetInfo( features=Features( { 'tokens': Sequence(Value('string' ) ), 'ner_tags': Sequence( ClassLabel(names=['O', 'B-PER', 'I-PER', 'B-ORG', 'I-ORG', 'B-LOC', 'I-LOC'] ) ), 'langs': Sequence(Value('string' ) ), 'spans': Sequence(Value('string' ) ), } ) , splits=[ { 'name': 'train', 'num_bytes': 2351563, 'num_examples': 10000, }, { 'name': 'validation', 'num_bytes': 238418, 'num_examples': 1000, }, ] , download_size=3940680 , dataset_size=2589981 , ) } ) assert dataset_infos.keys() == expected_dataset_infos.keys() for key in DatasetInfo._INCLUDED_INFO_IN_YAML: lowercase__ , lowercase__ = getattr(dataset_infos['default'] , _SCREAMING_SNAKE_CASE ), getattr(expected_dataset_infos['default'] , _SCREAMING_SNAKE_CASE ) if key == "num_bytes": assert is_apercent_close(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif key == "splits": assert list(_SCREAMING_SNAKE_CASE ) == list(_SCREAMING_SNAKE_CASE ) for split in result: assert result[split].name == expected[split].name assert result[split].num_examples == expected[split].num_examples assert is_apercent_close(result[split].num_bytes , expected[split].num_bytes ) else: result == expected
269
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process lowercase_ = logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE : _UpperCamelCase : str = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) _UpperCamelCase : Optional[str] = field( default=UpperCAmelCase , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) _UpperCamelCase : Optional[str] = field( default='NER' , metadata={'help': 'Task type to fine tune in training (e.g. NER, POS, etc)'} ) _UpperCamelCase : Optional[str] = field( default=UpperCAmelCase , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) _UpperCamelCase : bool = field(default=UpperCAmelCase , metadata={'help': 'Set this flag to use fast tokenization.'} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. _UpperCamelCase : Optional[str] = field( default=UpperCAmelCase , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class SCREAMING_SNAKE_CASE : _UpperCamelCase : str = field( metadata={'help': 'The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task.'} ) _UpperCamelCase : Optional[str] = field( default=UpperCAmelCase , metadata={'help': 'Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.'} , ) _UpperCamelCase : int = field( default=1_28 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) _UpperCamelCase : bool = field( default=UpperCAmelCase , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def __UpperCamelCase () -> str: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. lowercase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowercase__ , lowercase__ , lowercase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowercase__ , lowercase__ , lowercase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ' --overwrite_output_dir to overcome.' ) lowercase__ = import_module('tasks' ) try: lowercase__ = getattr(_SCREAMING_SNAKE_CASE , model_args.task_type ) lowercase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F"""Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """ F"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}""" ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowercase__ = token_classification_task.get_labels(data_args.labels ) lowercase__ = dict(enumerate(_SCREAMING_SNAKE_CASE ) ) lowercase__ = len(_SCREAMING_SNAKE_CASE ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowercase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=_SCREAMING_SNAKE_CASE , idalabel=_SCREAMING_SNAKE_CASE , labelaid={label: i for i, label in enumerate(_SCREAMING_SNAKE_CASE )} , cache_dir=model_args.cache_dir , ) lowercase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowercase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=_SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , ) # Get datasets lowercase__ = ( TokenClassificationDataset( token_classification_task=_SCREAMING_SNAKE_CASE , data_dir=data_args.data_dir , tokenizer=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowercase__ = ( TokenClassificationDataset( token_classification_task=_SCREAMING_SNAKE_CASE , data_dir=data_args.data_dir , tokenizer=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple[List[int], List[int]]: lowercase__ = np.argmax(_SCREAMING_SNAKE_CASE , axis=2 ) lowercase__ , lowercase__ = preds.shape lowercase__ = [[] for _ in range(_SCREAMING_SNAKE_CASE )] lowercase__ = [[] for _ in range(_SCREAMING_SNAKE_CASE )] for i in range(_SCREAMING_SNAKE_CASE ): for j in range(_SCREAMING_SNAKE_CASE ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(_SCREAMING_SNAKE_CASE ) -> Dict: lowercase__ , lowercase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), "precision": precision_score(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), "recall": recall_score(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), "f1": fa_score(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), } # Data collator lowercase__ = DataCollatorWithPadding(_SCREAMING_SNAKE_CASE , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowercase__ = Trainer( model=_SCREAMING_SNAKE_CASE , args=_SCREAMING_SNAKE_CASE , train_dataset=_SCREAMING_SNAKE_CASE , eval_dataset=_SCREAMING_SNAKE_CASE , compute_metrics=_SCREAMING_SNAKE_CASE , data_collator=_SCREAMING_SNAKE_CASE , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowercase__ = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) lowercase__ = trainer.evaluate() lowercase__ = os.path.join(training_args.output_dir , 'eval_results.txt' ) if trainer.is_world_process_zero(): with open(_SCREAMING_SNAKE_CASE , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(' %s = %s' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) writer.write('%s = %s\n' % (key, value) ) results.update(_SCREAMING_SNAKE_CASE ) # Predict if training_args.do_predict: lowercase__ = TokenClassificationDataset( token_classification_task=_SCREAMING_SNAKE_CASE , data_dir=data_args.data_dir , tokenizer=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowercase__ , lowercase__ , lowercase__ = trainer.predict(_SCREAMING_SNAKE_CASE ) lowercase__ , lowercase__ = align_predictions(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowercase__ = os.path.join(training_args.output_dir , 'test_results.txt' ) if trainer.is_world_process_zero(): with open(_SCREAMING_SNAKE_CASE , 'w' ) as writer: for key, value in metrics.items(): logger.info(' %s = %s' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) writer.write('%s = %s\n' % (key, value) ) # Save predictions lowercase__ = os.path.join(training_args.output_dir , 'test_predictions.txt' ) if trainer.is_world_process_zero(): with open(_SCREAMING_SNAKE_CASE , 'w' ) as writer: with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f: token_classification_task.write_predictions_to_file(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return results def __UpperCamelCase (_SCREAMING_SNAKE_CASE ) -> Any: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
269
1