code stringlengths 81 54k | code_codestyle int64 0 721 | style_context stringlengths 91 41.9k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
'''simple docstring'''
import 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 _SCREAMING_SNAKE_CASE ( A : Tuple ) -> int:
"""simple docstring"""
@wraps(lowercase__ )
def wrapper(self : Any , A : Union[str, Any] ):
if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
self.skipTest('\"test requires Fairseq\"' )
else:
test_case(self , lowercase__ )
return wrapper
def _SCREAMING_SNAKE_CASE ( A : List[str] ) -> Any:
"""simple docstring"""
@wraps(lowercase__ )
def wrapper(self : Union[str, Any] , A : Union[str, Any] ):
if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
self.skipTest('\"test requires transformers\"' )
else:
test_case(self , lowercase__ )
return wrapper
def _SCREAMING_SNAKE_CASE ( A : List[str] ) -> int:
"""simple docstring"""
@wraps(lowercase__ )
def wrapper(self : Optional[Any] , A : int ):
if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
self.skipTest('\"test not supported on Windows\"' )
else:
test_case(self , lowercase__ )
return wrapper
def _SCREAMING_SNAKE_CASE ( ) -> Tuple:
"""simple docstring"""
__snake_case : Any = [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(
__a , __a , __a )
@local
class a_ ( parameterized.TestCase ):
_snake_case = {}
_snake_case = None
@pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning')
@pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning')
def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]:
"""simple docstring"""
__snake_case : Union[str, Any] = '[...]'
__snake_case : Optional[Any] = importlib.import_module(
datasets.load.metric_module_factory(os.path.join('metrics' , lowerCAmelCase_)).module_path)
__snake_case : List[str] = datasets.load.import_main_class(metric_module.__name__ , dataset=lowerCAmelCase_)
# check parameters
__snake_case : Union[str, Any] = 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(lowerCAmelCase_ , metric_module.__name__):
with self.use_local_metrics():
try:
__snake_case : Tuple = doctest.testmod(lowerCAmelCase_ , verbose=lowerCAmelCase_ , raise_on_error=lowerCAmelCase_)
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 SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple:
"""simple docstring"""
__snake_case : Any = '[...]'
__snake_case : int = importlib.import_module(
datasets.load.metric_module_factory(os.path.join('metrics' , lowerCAmelCase_)).module_path)
# run doctest
with self.use_local_metrics():
__snake_case : Any = doctest.testmod(lowerCAmelCase_ , verbose=lowerCAmelCase_ , raise_on_error=lowerCAmelCase_)
self.assertEqual(results.failed , 0)
self.assertGreater(results.attempted , 1)
@contextmanager
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Tuple:
"""simple docstring"""
if metric_name in self.INTENSIVE_CALLS_PATCHER:
with self.INTENSIVE_CALLS_PATCHER[metric_name](lowerCAmelCase_):
yield
else:
yield
@contextmanager
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
def load_local_metric(__a , *__a , **__a):
return load_metric(os.path.join('metrics' , lowerCAmelCase_) , *lowerCAmelCase_ , **lowerCAmelCase_)
with patch('datasets.load_metric') as mock_load_metric:
__snake_case : Union[str, Any] = load_local_metric
yield
@classmethod
def SCREAMING_SNAKE_CASE__ (cls , __a) -> List[Any]:
"""simple docstring"""
def wrapper(__a):
__snake_case : Dict = contextmanager(lowerCAmelCase_)
__snake_case : Optional[int] = patcher
return patcher
return wrapper
@LocalMetricTest.register_intensive_calls_patcher('bleurt' )
def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> int:
"""simple docstring"""
import tensorflow.compat.va as tf
from bleurt.score import Predictor
tf.flags.DEFINE_string('sv' , '' , '' ) # handle pytest cli flags
class a_ ( __a ):
def SCREAMING_SNAKE_CASE__ (self , __a) -> Optional[Any]:
"""simple docstring"""
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:
__snake_case : int = MockedPredictor()
yield
@LocalMetricTest.register_intensive_calls_patcher('bertscore' )
def _SCREAMING_SNAKE_CASE ( A : Union[str, Any] ) -> Union[str, Any]:
"""simple docstring"""
import torch
def bert_cos_score_idf(A : List[str] , A : Optional[int] , *A : List[str] , **A : Tuple ):
return torch.tensor([[1.0, 1.0, 1.0]] * len(lowercase__ ) )
# 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:
__snake_case : Optional[Any] = bert_cos_score_idf
yield
@LocalMetricTest.register_intensive_calls_patcher('comet' )
def _SCREAMING_SNAKE_CASE ( A : Optional[int] ) -> List[str]:
"""simple docstring"""
def load_from_checkpoint(A : Optional[int] ):
class a_ :
def SCREAMING_SNAKE_CASE__ (self , __a , *__a , **__a) -> Dict:
"""simple docstring"""
assert len(lowerCAmelCase_) == 2
__snake_case : str = [0.19, 0.92]
return scores, sum(lowerCAmelCase_) / len(lowerCAmelCase_)
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:
__snake_case : str = None
with patch('comet.load_from_checkpoint' ) as mock_load_from_checkpoint:
__snake_case : str = load_from_checkpoint
yield
def _SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]:
"""simple docstring"""
__snake_case : List[str] = load_metric(os.path.join('metrics' , 'seqeval' ) )
__snake_case : Any = 'ERROR'
__snake_case : str = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
with pytest.raises(lowercase__ , match=re.escape(lowercase__ ) ):
metric.compute(predictions=[] , references=[] , scheme=lowercase__ ) | 719 |
'''simple docstring'''
import contextlib
import importlib
import io
import unittest
import transformers
# Try to import everything from transformers to ensure every object can be loaded.
from transformers import * # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available
if is_torch_available():
from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification
if is_tf_available():
from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification
if is_flax_available():
from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification
__A = DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co
__A = '''main'''
# Default branch name
__A = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
__A = '''aaaaaaa'''
# This commit does not exist, so we should 404.
__A = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
__A = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''
@contextlib.contextmanager
def _SCREAMING_SNAKE_CASE ( ) -> List[Any]:
"""simple docstring"""
print('Welcome!' )
yield
print('Bye!' )
@contextlib.contextmanager
def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]:
"""simple docstring"""
print('Bonjour!' )
yield
print('Au revoir!' )
class a_ ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
assert transformers.__spec__ is not None
assert importlib.util.find_spec('transformers') is not None
class a_ ( unittest.TestCase ):
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> int:
"""simple docstring"""
with ContextManagers([]):
print('Transformers are awesome!')
# The print statement adds a new line at the end of the output
self.assertEqual(mock_stdout.getvalue() , 'Transformers are awesome!\n')
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]:
"""simple docstring"""
with ContextManagers([context_en()]):
print('Transformers are awesome!')
# The output should be wrapped with an English welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , 'Welcome!\nTransformers are awesome!\nBye!\n')
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple:
"""simple docstring"""
with ContextManagers([context_fr(), context_en()]):
print('Transformers are awesome!')
# The output should be wrapped with an English and French welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , 'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n')
@require_torch
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
self.assertEqual(find_labels(__a) , ['labels'])
self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label'])
self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions'])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , ['labels'])
@require_tf
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
self.assertEqual(find_labels(__a) , ['labels'])
self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label'])
self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions'])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , ['labels'])
@require_flax
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
self.assertEqual(find_labels(__a) , [])
self.assertEqual(find_labels(__a) , [])
self.assertEqual(find_labels(__a) , [])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , []) | 61 | 0 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : dict ) -> set:
"""simple docstring"""
__snake_case : int = set()
# edges = list of graph's edges
__snake_case : List[Any] = get_edges(UpperCamelCase__ )
# While there are still elements in edges list, take an arbitrary edge
# (from_node, to_node) and add his extremity to chosen_vertices and then
# remove all arcs adjacent to the from_node and to_node
while edges:
__snake_case : List[str] = edges.pop()
chosen_vertices.add(UpperCamelCase__ )
chosen_vertices.add(UpperCamelCase__ )
for edge in edges.copy():
if from_node in edge or to_node in edge:
edges.discard(UpperCamelCase__ )
return chosen_vertices
def _SCREAMING_SNAKE_CASE ( A : dict ) -> set:
"""simple docstring"""
__snake_case : Tuple = set()
for from_node, to_nodes in graph.items():
for to_node in to_nodes:
edges.add((from_node, to_node) )
return edges
if __name__ == "__main__":
import doctest
doctest.testmod()
# graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]}
# print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}") | 720 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__A = {'''configuration_timm_backbone''': ['''TimmBackboneConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ['''TimmBackbone''']
if TYPE_CHECKING:
from .configuration_timm_backbone import TimmBackboneConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_timm_backbone import TimmBackbone
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 61 | 0 |
'''simple docstring'''
import json
import os
import re
import unicodedata
from json.encoder import INFINITY
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import regex
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging
from ...utils.generic import _is_jax, _is_numpy
__A = logging.get_logger(__name__)
__A = {
"artists_file": "artists.json",
"lyrics_file": "lyrics.json",
"genres_file": "genres.json",
}
__A = {
"artists_file": {
"jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json",
},
"genres_file": {
"jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json",
},
"lyrics_file": {
"jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json",
},
}
__A = {
"jukebox": 5_1_2,
}
class a_ ( UpperCamelCase_ ):
_snake_case = VOCAB_FILES_NAMES
_snake_case = PRETRAINED_VOCAB_FILES_MAP
_snake_case = PRETRAINED_LYRIC_TOKENS_SIZES
_snake_case = ["""input_ids""", """attention_mask"""]
def __init__(self , __a , __a , __a , __a=["v3", "v2", "v2"] , __a=5_1_2 , __a=5 , __a="<|endoftext|>" , **__a , ) -> List[str]:
"""simple docstring"""
__snake_case : Optional[Any] = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__) if isinstance(UpperCAmelCase__ , UpperCAmelCase__) else unk_token
super().__init__(
unk_token=UpperCAmelCase__ , n_genres=UpperCAmelCase__ , version=UpperCAmelCase__ , max_n_lyric_tokens=UpperCAmelCase__ , **UpperCAmelCase__ , )
__snake_case : Dict = version
__snake_case : int = max_n_lyric_tokens
__snake_case : Optional[Any] = n_genres
with open(UpperCAmelCase__ , encoding='utf-8') as vocab_handle:
__snake_case : Any = json.load(UpperCAmelCase__)
with open(UpperCAmelCase__ , encoding='utf-8') as vocab_handle:
__snake_case : Tuple = json.load(UpperCAmelCase__)
with open(UpperCAmelCase__ , encoding='utf-8') as vocab_handle:
__snake_case : Optional[int] = json.load(UpperCAmelCase__)
__snake_case : str = R'[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+'
# In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters.
if len(self.lyrics_encoder) == 7_9:
__snake_case : Union[str, Any] = oov.replace(R'\-\'' , R'\-+\'')
__snake_case : Tuple = regex.compile(UpperCAmelCase__)
__snake_case : Optional[int] = {v: k for k, v in self.artists_encoder.items()}
__snake_case : Any = {v: k for k, v in self.genres_encoder.items()}
__snake_case : int = {v: k for k, v in self.lyrics_encoder.items()}
@property
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
return len(self.artists_encoder) + len(self.genres_encoder) + len(self.lyrics_encoder)
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return dict(self.artists_encoder , self.genres_encoder , self.lyrics_encoder)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Optional[int]:
"""simple docstring"""
__snake_case : List[Any] = [self.artists_encoder.get(UpperCAmelCase__ , 0) for artist in list_artists]
for genres in range(len(UpperCAmelCase__)):
__snake_case : Dict = [self.genres_encoder.get(UpperCAmelCase__ , 0) for genre in list_genres[genres]]
__snake_case : str = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres]))
__snake_case : str = [[self.lyrics_encoder.get(UpperCAmelCase__ , 0) for character in list_lyrics[0]], [], []]
return artists_id, list_genres, lyric_ids
def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple:
"""simple docstring"""
return list(UpperCAmelCase__)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , **__a) -> Optional[int]:
"""simple docstring"""
__snake_case ,__snake_case ,__snake_case : int = self.prepare_for_tokenization(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__)
__snake_case : List[Any] = self._tokenize(UpperCAmelCase__)
return artist, genre, lyrics
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = False) -> Tuple[str, str, str, Dict[str, Any]]:
"""simple docstring"""
for idx in range(len(self.version)):
if self.version[idx] == "v3":
__snake_case : Any = artists[idx].lower()
__snake_case : Dict = [genres[idx].lower()]
else:
__snake_case : Optional[Any] = self._normalize(artists[idx]) + '.v2'
__snake_case : Tuple = [
self._normalize(UpperCAmelCase__) + '.v2' for genre in genres[idx].split('_')
] # split is for the full dictionary with combined genres
if self.version[0] == "v2":
__snake_case : str = regex.compile(R'[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+')
__snake_case : Any = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n'
__snake_case : List[str] = {vocab[index]: index + 1 for index in range(len(UpperCAmelCase__))}
__snake_case : Optional[int] = 0
__snake_case : Optional[int] = len(UpperCAmelCase__) + 1
__snake_case : Dict = self.vocab
__snake_case : Any = {v: k for k, v in self.vocab.items()}
__snake_case : Optional[Any] = ''
else:
__snake_case : List[Any] = regex.compile(R'[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+')
__snake_case : Optional[int] = self._run_strip_accents(UpperCAmelCase__)
__snake_case : Dict = lyrics.replace('\\' , '\n')
__snake_case : Union[str, Any] = self.out_of_vocab.sub('' , UpperCAmelCase__), [], []
return artists, genres, lyrics
def SCREAMING_SNAKE_CASE__ (self , __a) -> Dict:
"""simple docstring"""
__snake_case : int = unicodedata.normalize('NFD' , UpperCAmelCase__)
__snake_case : Union[str, Any] = []
for char in text:
__snake_case : Any = unicodedata.category(UpperCAmelCase__)
if cat == "Mn":
continue
output.append(UpperCAmelCase__)
return "".join(UpperCAmelCase__)
def SCREAMING_SNAKE_CASE__ (self , __a) -> str:
"""simple docstring"""
__snake_case : Dict = (
[chr(UpperCAmelCase__) for i in range(ord('a') , ord('z') + 1)]
+ [chr(UpperCAmelCase__) for i in range(ord('A') , ord('Z') + 1)]
+ [chr(UpperCAmelCase__) for i in range(ord('0') , ord('9') + 1)]
+ ['.']
)
__snake_case : List[str] = frozenset(UpperCAmelCase__)
__snake_case : List[str] = re.compile(R'_+')
__snake_case : str = ''.join([c if c in accepted else '_' for c in text.lower()])
__snake_case : List[Any] = pattern.sub('_' , UpperCAmelCase__).strip('_')
return text
def SCREAMING_SNAKE_CASE__ (self , __a) -> str:
"""simple docstring"""
return " ".join(UpperCAmelCase__)
def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = False) -> List[str]:
"""simple docstring"""
if not isinstance(UpperCAmelCase__ , UpperCAmelCase__):
__snake_case : Any = TensorType(UpperCAmelCase__)
# Get a function reference for the correct framework
if tensor_type == TensorType.TENSORFLOW:
if not is_tf_available():
raise ImportError(
'Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.')
import tensorflow as tf
__snake_case : Dict = tf.constant
__snake_case : Union[str, Any] = tf.is_tensor
elif tensor_type == TensorType.PYTORCH:
if not is_torch_available():
raise ImportError('Unable to convert output to PyTorch tensors format, PyTorch is not installed.')
import torch
__snake_case : Dict = torch.tensor
__snake_case : str = torch.is_tensor
elif tensor_type == TensorType.JAX:
if not is_flax_available():
raise ImportError('Unable to convert output to JAX tensors format, JAX is not installed.')
import jax.numpy as jnp # noqa: F811
__snake_case : List[str] = jnp.array
__snake_case : int = _is_jax
else:
__snake_case : List[str] = np.asarray
__snake_case : Any = _is_numpy
# Do the tensor conversion in batch
try:
if prepend_batch_axis:
__snake_case : List[Any] = [inputs]
if not is_tensor(UpperCAmelCase__):
__snake_case : Any = as_tensor(UpperCAmelCase__)
except: # noqa E722
raise ValueError(
'Unable to create tensor, you should probably activate truncation and/or padding '
'with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.')
return inputs
def __call__(self , __a , __a , __a="" , __a="pt") -> BatchEncoding:
"""simple docstring"""
__snake_case : Dict = [0, 0, 0]
__snake_case : List[Any] = [artist] * len(self.version)
__snake_case : str = [genres] * len(self.version)
__snake_case ,__snake_case ,__snake_case : Optional[Any] = self.tokenize(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__)
__snake_case ,__snake_case ,__snake_case : Optional[Any] = self._convert_token_to_id(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__)
__snake_case : Any = [-INFINITY] * len(full_tokens[-1])
__snake_case : List[Any] = [
self.convert_to_tensors(
[input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] , tensor_type=UpperCAmelCase__)
for i in range(len(self.version))
]
return BatchEncoding({'input_ids': input_ids, 'attention_masks': attention_masks})
def SCREAMING_SNAKE_CASE__ (self , __a , __a = None) -> Tuple[str]:
"""simple docstring"""
if not os.path.isdir(UpperCAmelCase__):
logger.error(F"""Vocabulary path ({save_directory}) should be a directory""")
return
__snake_case : List[str] = os.path.join(
UpperCAmelCase__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['artists_file'])
with open(UpperCAmelCase__ , 'w' , encoding='utf-8') as f:
f.write(json.dumps(self.artists_encoder , ensure_ascii=UpperCAmelCase__))
__snake_case : Optional[Any] = os.path.join(
UpperCAmelCase__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['genres_file'])
with open(UpperCAmelCase__ , 'w' , encoding='utf-8') as f:
f.write(json.dumps(self.genres_encoder , ensure_ascii=UpperCAmelCase__))
__snake_case : Dict = os.path.join(
UpperCAmelCase__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['lyrics_file'])
with open(UpperCAmelCase__ , 'w' , encoding='utf-8') as f:
f.write(json.dumps(self.lyrics_encoder , ensure_ascii=UpperCAmelCase__))
return (artists_file, genres_file, lyrics_file)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Dict:
"""simple docstring"""
__snake_case : Optional[int] = self.artists_decoder.get(UpperCAmelCase__)
__snake_case : List[str] = [self.genres_decoder.get(UpperCAmelCase__) for genre in genres_index]
__snake_case : List[str] = [self.lyrics_decoder.get(UpperCAmelCase__) for character in lyric_index]
return artist, genres, lyrics | 721 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
__snake_case : str = 1
for i in range(1 , num + 1 ):
fact *= i
return fact
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
__snake_case : Union[str, Any] = 0
while number > 0:
__snake_case : Dict = number % 10
sum_of_digits += last_digit
__snake_case : Union[str, Any] = number // 10 # Removing the last_digit from the given number
return sum_of_digits
def _SCREAMING_SNAKE_CASE ( A : int = 1_00 ) -> int:
"""simple docstring"""
__snake_case : List[Any] = factorial(A )
__snake_case : Dict = split_and_add(A )
return result
if __name__ == "__main__":
print(solution(int(input('''Enter the Number: ''').strip()))) | 61 | 0 |
'''simple docstring'''
from abc import ABC, abstractmethod
from argparse import ArgumentParser
class a_ ( __a ):
@staticmethod
@abstractmethod
def SCREAMING_SNAKE_CASE__ (__a) -> Dict:
"""simple docstring"""
raise NotImplementedError()
@abstractmethod
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
raise NotImplementedError() | 700 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import ChineseCLIPImageProcessor
class a_ ( unittest.TestCase ):
def __init__(self , __a , __a=7 , __a=3 , __a=1_8 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=None , __a=True , __a=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __a=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __a=True , ) -> List[Any]:
"""simple docstring"""
__snake_case : Tuple = size if size is not None else {'height': 2_2_4, 'width': 2_2_4}
__snake_case : Any = crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8}
__snake_case : Optional[int] = parent
__snake_case : Dict = batch_size
__snake_case : str = num_channels
__snake_case : Optional[Any] = image_size
__snake_case : Optional[int] = min_resolution
__snake_case : Tuple = max_resolution
__snake_case : Optional[int] = do_resize
__snake_case : Optional[int] = size
__snake_case : Union[str, Any] = do_center_crop
__snake_case : List[Any] = crop_size
__snake_case : int = do_normalize
__snake_case : Optional[Any] = image_mean
__snake_case : str = image_std
__snake_case : Optional[Any] = do_convert_rgb
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_convert_rgb": self.do_convert_rgb,
}
def SCREAMING_SNAKE_CASE__ (self , __a=False , __a=False , __a=False) -> List[str]:
"""simple docstring"""
assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"
if equal_resolution:
__snake_case : Optional[int] = []
for i in range(self.batch_size):
image_inputs.append(
np.random.randint(
2_5_5 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta))
else:
__snake_case : Dict = []
for i in range(self.batch_size):
__snake_case ,__snake_case : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution) , 2)
image_inputs.append(np.random.randint(2_5_5 , size=(self.num_channels, width, height) , dtype=np.uinta))
if not numpify and not torchify:
# PIL expects the channel dimension as last dimension
__snake_case : int = [Image.fromarray(np.moveaxis(__a , 0 , -1)) for x in image_inputs]
if torchify:
__snake_case : List[Any] = [torch.from_numpy(__a) for x in image_inputs]
return image_inputs
@require_torch
@require_vision
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = ChineseCLIPImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Union[str, Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=__a)
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : int = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , 'do_resize'))
self.assertTrue(hasattr(__a , 'size'))
self.assertTrue(hasattr(__a , 'do_center_crop'))
self.assertTrue(hasattr(__a , 'center_crop'))
self.assertTrue(hasattr(__a , 'do_normalize'))
self.assertTrue(hasattr(__a , 'image_mean'))
self.assertTrue(hasattr(__a , 'image_std'))
self.assertTrue(hasattr(__a , 'do_convert_rgb'))
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'height': 2_2_4, 'width': 2_2_4})
self.assertEqual(image_processor.crop_size , {'height': 1_8, 'width': 1_8})
__snake_case : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4)
self.assertEqual(image_processor.size , {'shortest_edge': 4_2})
self.assertEqual(image_processor.crop_size , {'height': 8_4, 'width': 8_4})
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
__snake_case : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
__snake_case : int = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : List[Any] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
__snake_case : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=__a , numpify=__a)
for image in image_inputs:
self.assertIsInstance(__a , np.ndarray)
# Test not batched input
__snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : int = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Any = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
__snake_case : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__a , torchify=__a)
for image in image_inputs:
self.assertIsInstance(__a , torch.Tensor)
# Test not batched input
__snake_case : Any = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : Union[str, Any] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
@require_torch
@require_vision
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = ChineseCLIPImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[Any] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__a)
__snake_case : List[Any] = 3
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Any = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , 'do_resize'))
self.assertTrue(hasattr(__a , 'size'))
self.assertTrue(hasattr(__a , 'do_center_crop'))
self.assertTrue(hasattr(__a , 'center_crop'))
self.assertTrue(hasattr(__a , 'do_normalize'))
self.assertTrue(hasattr(__a , 'image_mean'))
self.assertTrue(hasattr(__a , 'image_std'))
self.assertTrue(hasattr(__a , 'do_convert_rgb'))
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
__snake_case : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
__snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.expected_encoded_image_num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : Optional[int] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.expected_encoded_image_num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , ) | 61 | 0 |
'''simple docstring'''
import logging
import os
from logging import (
CRITICAL, # NOQA
DEBUG, # NOQA
ERROR, # NOQA
FATAL, # NOQA
INFO, # NOQA
NOTSET, # NOQA
WARN, # NOQA
WARNING, # NOQA
)
from typing import Optional
from tqdm import auto as tqdm_lib
__A = {
'''debug''': logging.DEBUG,
'''info''': logging.INFO,
'''warning''': logging.WARNING,
'''error''': logging.ERROR,
'''critical''': logging.CRITICAL,
}
__A = logging.WARNING
def _SCREAMING_SNAKE_CASE ( ) -> Tuple:
"""simple docstring"""
__snake_case : int = os.getenv('DATASETS_VERBOSITY' , _SCREAMING_SNAKE_CASE )
if env_level_str:
if env_level_str in log_levels:
return log_levels[env_level_str]
else:
logging.getLogger().warning(
F"""Unknown option DATASETS_VERBOSITY={env_level_str}, """
F"""has to be one of: { ", ".join(log_levels.keys() ) }""" )
return _default_log_level
def _SCREAMING_SNAKE_CASE ( ) -> str:
"""simple docstring"""
return __name__.split('.' )[0]
def _SCREAMING_SNAKE_CASE ( ) -> logging.Logger:
"""simple docstring"""
return logging.getLogger(_get_library_name() )
def _SCREAMING_SNAKE_CASE ( ) -> None:
"""simple docstring"""
# Apply our default configuration to the library root logger.
__snake_case : List[Any] = _get_library_root_logger()
library_root_logger.setLevel(_get_default_logging_level() )
def _SCREAMING_SNAKE_CASE ( ) -> None:
"""simple docstring"""
__snake_case : Optional[int] = _get_library_root_logger()
library_root_logger.setLevel(logging.NOTSET )
def _SCREAMING_SNAKE_CASE ( A : Union[str, Any] = None ) -> logging.Logger:
"""simple docstring"""
if name is None:
__snake_case : List[Any] = _get_library_name()
return logging.getLogger(_SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
return _get_library_root_logger().getEffectiveLevel()
def _SCREAMING_SNAKE_CASE ( A : Dict ) -> None:
"""simple docstring"""
_get_library_root_logger().setLevel(_SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( ) -> Dict:
"""simple docstring"""
return set_verbosity(_SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( ) -> List[str]:
"""simple docstring"""
return set_verbosity(_SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]:
"""simple docstring"""
return set_verbosity(_SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( ) -> str:
"""simple docstring"""
return set_verbosity(_SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( ) -> None:
"""simple docstring"""
__snake_case : List[str] = False
def _SCREAMING_SNAKE_CASE ( ) -> None:
"""simple docstring"""
__snake_case : List[Any] = True
# Configure the library root logger at the module level (singleton-like)
_configure_library_root_logger()
class a_ :
def __init__(self , *__a , **__a) -> Union[str, Any]: # pylint: disable=unused-argument
"""simple docstring"""
__snake_case : Optional[int] = args[0] if args else None
def __iter__(self) -> int:
"""simple docstring"""
return iter(self._iterator)
def __getattr__(self , __a) -> Optional[Any]:
"""simple docstring"""
def empty_fn(*__a , **__a): # pylint: disable=unused-argument
return
return empty_fn
def __enter__(self) -> List[Any]:
"""simple docstring"""
return self
def __exit__(self , __a , __a , __a) -> Tuple:
"""simple docstring"""
return
__A = True
class a_ :
def __call__(self , *__a , __a=False , **__a) -> Dict:
"""simple docstring"""
if _tqdm_active and not disable:
return tqdm_lib.tqdm(*__a , **__a)
else:
return EmptyTqdm(*__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , *__a , **__a) -> Optional[Any]:
"""simple docstring"""
__snake_case : List[Any] = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*__a , **__a)
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
if _tqdm_active:
return tqdm_lib.tqdm.get_lock()
__A = _tqdm_cls()
def _SCREAMING_SNAKE_CASE ( ) -> bool:
"""simple docstring"""
global _tqdm_active
return bool(_tqdm_active )
def _SCREAMING_SNAKE_CASE ( ) -> List[str]:
"""simple docstring"""
global _tqdm_active
__snake_case : Tuple = True
def _SCREAMING_SNAKE_CASE ( ) -> Any:
"""simple docstring"""
global _tqdm_active
__snake_case : List[Any] = False | 701 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json''',
# See all ViT MSN models at https://huggingface.co/models?filter=vit_msn
}
class a_ ( UpperCamelCase_ ):
_snake_case = """vit_msn"""
def __init__(self , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-06 , __a=2_2_4 , __a=1_6 , __a=3 , __a=True , **__a , ) -> Any:
"""simple docstring"""
super().__init__(**__a)
__snake_case : List[str] = hidden_size
__snake_case : Optional[int] = num_hidden_layers
__snake_case : Optional[Any] = num_attention_heads
__snake_case : str = intermediate_size
__snake_case : List[str] = hidden_act
__snake_case : List[Any] = hidden_dropout_prob
__snake_case : Tuple = attention_probs_dropout_prob
__snake_case : List[str] = initializer_range
__snake_case : Optional[int] = layer_norm_eps
__snake_case : Dict = image_size
__snake_case : int = patch_size
__snake_case : Dict = num_channels
__snake_case : Tuple = qkv_bias | 61 | 0 |
'''simple docstring'''
import argparse
import os.path as osp
import re
import torch
from safetensors.torch import load_file, save_file
# =================#
# UNet Conversion #
# =================#
__A = [
# (stable-diffusion, HF Diffusers)
('''time_embed.0.weight''', '''time_embedding.linear_1.weight'''),
('''time_embed.0.bias''', '''time_embedding.linear_1.bias'''),
('''time_embed.2.weight''', '''time_embedding.linear_2.weight'''),
('''time_embed.2.bias''', '''time_embedding.linear_2.bias'''),
('''input_blocks.0.0.weight''', '''conv_in.weight'''),
('''input_blocks.0.0.bias''', '''conv_in.bias'''),
('''out.0.weight''', '''conv_norm_out.weight'''),
('''out.0.bias''', '''conv_norm_out.bias'''),
('''out.2.weight''', '''conv_out.weight'''),
('''out.2.bias''', '''conv_out.bias'''),
]
__A = [
# (stable-diffusion, HF Diffusers)
('''in_layers.0''', '''norm1'''),
('''in_layers.2''', '''conv1'''),
('''out_layers.0''', '''norm2'''),
('''out_layers.3''', '''conv2'''),
('''emb_layers.1''', '''time_emb_proj'''),
('''skip_connection''', '''conv_shortcut'''),
]
__A = []
# hardcoded number of downblocks and resnets/attentions...
# would need smarter logic for other networks.
for i in range(4):
# loop over downblocks/upblocks
for j in range(2):
# loop over resnets/attentions for downblocks
__A = f'''down_blocks.{i}.resnets.{j}.'''
__A = f'''input_blocks.{3*i + j + 1}.0.'''
unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
if i < 3:
# no attention layers in down_blocks.3
__A = f'''down_blocks.{i}.attentions.{j}.'''
__A = f'''input_blocks.{3*i + j + 1}.1.'''
unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
for j in range(3):
# loop over resnets/attentions for upblocks
__A = f'''up_blocks.{i}.resnets.{j}.'''
__A = f'''output_blocks.{3*i + j}.0.'''
unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
if i > 0:
# no attention layers in up_blocks.0
__A = f'''up_blocks.{i}.attentions.{j}.'''
__A = f'''output_blocks.{3*i + j}.1.'''
unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
if i < 3:
# no downsample in down_blocks.3
__A = f'''down_blocks.{i}.downsamplers.0.conv.'''
__A = f'''input_blocks.{3*(i+1)}.0.op.'''
unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
# no upsample in up_blocks.3
__A = f'''up_blocks.{i}.upsamplers.0.'''
__A = f'''output_blocks.{3*i + 2}.{1 if i == 0 else 2}.'''
unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
__A = '''mid_block.attentions.0.'''
__A = '''middle_block.1.'''
unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
for j in range(2):
__A = f'''mid_block.resnets.{j}.'''
__A = f'''middle_block.{2*j}.'''
unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
def _SCREAMING_SNAKE_CASE ( A : Dict ) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[int] = {k: k for k in unet_state_dict.keys()}
for sd_name, hf_name in unet_conversion_map:
__snake_case : Tuple = sd_name
for k, v in mapping.items():
if "resnets" in k:
for sd_part, hf_part in unet_conversion_map_resnet:
__snake_case : Any = v.replace(lowercase__ , lowercase__ )
__snake_case : str = v
for k, v in mapping.items():
for sd_part, hf_part in unet_conversion_map_layer:
__snake_case : Optional[int] = v.replace(lowercase__ , lowercase__ )
__snake_case : Optional[Any] = v
__snake_case : List[Any] = {v: unet_state_dict[k] for k, v in mapping.items()}
return new_state_dict
# ================#
# VAE Conversion #
# ================#
__A = [
# (stable-diffusion, HF Diffusers)
('''nin_shortcut''', '''conv_shortcut'''),
('''norm_out''', '''conv_norm_out'''),
('''mid.attn_1.''', '''mid_block.attentions.0.'''),
]
for i in range(4):
# down_blocks have two resnets
for j in range(2):
__A = f'''encoder.down_blocks.{i}.resnets.{j}.'''
__A = f'''encoder.down.{i}.block.{j}.'''
vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
if i < 3:
__A = f'''down_blocks.{i}.downsamplers.0.'''
__A = f'''down.{i}.downsample.'''
vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
__A = f'''up_blocks.{i}.upsamplers.0.'''
__A = f'''up.{3-i}.upsample.'''
vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
# up_blocks have three resnets
# also, up blocks in hf are numbered in reverse from sd
for j in range(3):
__A = f'''decoder.up_blocks.{i}.resnets.{j}.'''
__A = f'''decoder.up.{3-i}.block.{j}.'''
vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
# this part accounts for mid blocks in both the encoder and the decoder
for i in range(2):
__A = f'''mid_block.resnets.{i}.'''
__A = f'''mid.block_{i+1}.'''
vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
__A = [
# (stable-diffusion, HF Diffusers)
('''norm.''', '''group_norm.'''),
('''q.''', '''query.'''),
('''k.''', '''key.'''),
('''v.''', '''value.'''),
('''proj_out.''', '''proj_attn.'''),
]
def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> Union[str, Any]:
"""simple docstring"""
return w.reshape(*w.shape , 1 , 1 )
def _SCREAMING_SNAKE_CASE ( A : Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[Any] = {k: k for k in vae_state_dict.keys()}
for k, v in mapping.items():
for sd_part, hf_part in vae_conversion_map:
__snake_case : int = v.replace(lowercase__ , lowercase__ )
__snake_case : Dict = v
for k, v in mapping.items():
if "attentions" in k:
for sd_part, hf_part in vae_conversion_map_attn:
__snake_case : Tuple = v.replace(lowercase__ , lowercase__ )
__snake_case : str = v
__snake_case : Dict = {v: vae_state_dict[k] for k, v in mapping.items()}
__snake_case : Tuple = ['q', 'k', 'v', 'proj_out']
for k, v in new_state_dict.items():
for weight_name in weights_to_convert:
if F"""mid.attn_1.{weight_name}.weight""" in k:
print(F"""Reshaping {k} for SD format""" )
__snake_case : Dict = reshape_weight_for_sd(lowercase__ )
return new_state_dict
# =========================#
# Text Encoder Conversion #
# =========================#
__A = [
# (stable-diffusion, HF Diffusers)
('''resblocks.''', '''text_model.encoder.layers.'''),
('''ln_1''', '''layer_norm1'''),
('''ln_2''', '''layer_norm2'''),
('''.c_fc.''', '''.fc1.'''),
('''.c_proj.''', '''.fc2.'''),
('''.attn''', '''.self_attn'''),
('''ln_final.''', '''transformer.text_model.final_layer_norm.'''),
('''token_embedding.weight''', '''transformer.text_model.embeddings.token_embedding.weight'''),
('''positional_embedding''', '''transformer.text_model.embeddings.position_embedding.weight'''),
]
__A = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
__A = re.compile('''|'''.join(protected.keys()))
# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
__A = {'''q''': 0, '''k''': 1, '''v''': 2}
def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> Optional[int]:
"""simple docstring"""
__snake_case : str = {}
__snake_case : List[Any] = {}
__snake_case : List[Any] = {}
for k, v in text_enc_dict.items():
if (
k.endswith('.self_attn.q_proj.weight' )
or k.endswith('.self_attn.k_proj.weight' )
or k.endswith('.self_attn.v_proj.weight' )
):
__snake_case : Dict = k[: -len('.q_proj.weight' )]
__snake_case : Union[str, Any] = k[-len('q_proj.weight' )]
if k_pre not in capture_qkv_weight:
__snake_case : int = [None, None, None]
__snake_case : Optional[int] = v
continue
if (
k.endswith('.self_attn.q_proj.bias' )
or k.endswith('.self_attn.k_proj.bias' )
or k.endswith('.self_attn.v_proj.bias' )
):
__snake_case : Optional[Any] = k[: -len('.q_proj.bias' )]
__snake_case : List[Any] = k[-len('q_proj.bias' )]
if k_pre not in capture_qkv_bias:
__snake_case : Optional[Any] = [None, None, None]
__snake_case : Optional[int] = v
continue
__snake_case : Dict = textenc_pattern.sub(lambda A : protected[re.escape(m.group(0 ) )] , lowercase__ )
__snake_case : str = v
for k_pre, tensors in capture_qkv_weight.items():
if None in tensors:
raise Exception('CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing' )
__snake_case : Union[str, Any] = textenc_pattern.sub(lambda A : protected[re.escape(m.group(0 ) )] , lowercase__ )
__snake_case : Optional[Any] = torch.cat(lowercase__ )
for k_pre, tensors in capture_qkv_bias.items():
if None in tensors:
raise Exception('CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing' )
__snake_case : str = textenc_pattern.sub(lambda A : protected[re.escape(m.group(0 ) )] , lowercase__ )
__snake_case : Any = torch.cat(lowercase__ )
return new_state_dict
def _SCREAMING_SNAKE_CASE ( A : List[str] ) -> Tuple:
"""simple docstring"""
return text_enc_dict
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument('''--model_path''', default=None, type=str, required=True, help='''Path to the model to convert.''')
parser.add_argument('''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the output model.''')
parser.add_argument('''--half''', action='''store_true''', help='''Save weights in half precision.''')
parser.add_argument(
'''--use_safetensors''', action='''store_true''', help='''Save weights use safetensors, default is ckpt.'''
)
__A = parser.parse_args()
assert args.model_path is not None, "Must provide a model path!"
assert args.checkpoint_path is not None, "Must provide a checkpoint path!"
# Path for safetensors
__A = osp.join(args.model_path, '''unet''', '''diffusion_pytorch_model.safetensors''')
__A = osp.join(args.model_path, '''vae''', '''diffusion_pytorch_model.safetensors''')
__A = osp.join(args.model_path, '''text_encoder''', '''model.safetensors''')
# Load models from safetensors if it exists, if it doesn't pytorch
if osp.exists(unet_path):
__A = load_file(unet_path, device='''cpu''')
else:
__A = osp.join(args.model_path, '''unet''', '''diffusion_pytorch_model.bin''')
__A = torch.load(unet_path, map_location='''cpu''')
if osp.exists(vae_path):
__A = load_file(vae_path, device='''cpu''')
else:
__A = osp.join(args.model_path, '''vae''', '''diffusion_pytorch_model.bin''')
__A = torch.load(vae_path, map_location='''cpu''')
if osp.exists(text_enc_path):
__A = load_file(text_enc_path, device='''cpu''')
else:
__A = osp.join(args.model_path, '''text_encoder''', '''pytorch_model.bin''')
__A = torch.load(text_enc_path, map_location='''cpu''')
# Convert the UNet model
__A = convert_unet_state_dict(unet_state_dict)
__A = {'''model.diffusion_model.''' + k: v for k, v in unet_state_dict.items()}
# Convert the VAE model
__A = convert_vae_state_dict(vae_state_dict)
__A = {'''first_stage_model.''' + k: v for k, v in vae_state_dict.items()}
# Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper
__A = '''text_model.encoder.layers.22.layer_norm2.bias''' in text_enc_dict
if is_vaa_model:
# Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm
__A = {'''transformer.''' + k: v for k, v in text_enc_dict.items()}
__A = convert_text_enc_state_dict_vaa(text_enc_dict)
__A = {'''cond_stage_model.model.''' + k: v for k, v in text_enc_dict.items()}
else:
__A = convert_text_enc_state_dict(text_enc_dict)
__A = {'''cond_stage_model.transformer.''' + k: v for k, v in text_enc_dict.items()}
# Put together new checkpoint
__A = {**unet_state_dict, **vae_state_dict, **text_enc_dict}
if args.half:
__A = {k: v.half() for k, v in state_dict.items()}
if args.use_safetensors:
save_file(state_dict, args.checkpoint_path)
else:
__A = {'''state_dict''': state_dict}
torch.save(state_dict, args.checkpoint_path) | 702 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : float , A : list[float] ) -> float:
"""simple docstring"""
if discount_rate < 0:
raise ValueError('Discount rate cannot be negative' )
if not cash_flows:
raise ValueError('Cash flows list cannot be empty' )
__snake_case : List[str] = sum(
cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(A ) )
return round(A , ndigits=2 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 61 | 0 |
'''simple docstring'''
import argparse
import os
import gluonnlp as nlp
import mxnet as mx
import numpy as np
import torch
from gluonnlp.base import get_home_dir
from gluonnlp.model.bert import BERTEncoder
from gluonnlp.model.utils import _load_vocab
from gluonnlp.vocab import Vocab
from packaging import version
from torch import nn
from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer
from transformers.models.bert.modeling_bert import (
BertIntermediate,
BertLayer,
BertOutput,
BertSelfAttention,
BertSelfOutput,
)
from transformers.utils import logging
if version.parse(nlp.__version__) != version.parse('''0.8.3'''):
raise Exception('''requires gluonnlp == 0.8.3''')
if version.parse(mx.__version__) != version.parse('''1.5.0'''):
raise Exception('''requires mxnet == 1.5.0''')
logging.set_verbosity_info()
__A = logging.get_logger(__name__)
__A = 'The Nymphenburg Palace is a beautiful palace in Munich!'
def _SCREAMING_SNAKE_CASE ( A : List[Any] , A : Union[str, Any] ) -> int:
"""simple docstring"""
__snake_case : str = {
'''attention_cell''': '''multi_head''',
'''num_layers''': 4,
'''units''': 10_24,
'''hidden_size''': 7_68,
'''max_length''': 5_12,
'''num_heads''': 8,
'''scaled''': True,
'''dropout''': 0.1,
'''use_residual''': True,
'''embed_size''': 10_24,
'''embed_dropout''': 0.1,
'''word_embed''': None,
'''layer_norm_eps''': 1e-5,
'''token_type_vocab_size''': 2,
}
__snake_case : str = bort_4_8_768_1024_hparams
# Let's construct the original Bort model here
# Taken from official BERT implementation, see:
# https://github.com/alexa/bort/blob/master/bort/bort.py
__snake_case : Dict = BERTEncoder(
attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=lowerCAmelCase_ , output_all_encodings=lowerCAmelCase_ , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , lowerCAmelCase_ ) , )
# Vocab information needs to be fetched first
# It's the same as RoBERTa, so RobertaTokenizer can be used later
__snake_case : int = '''openwebtext_ccnews_stories_books_cased'''
# Specify download folder to Gluonnlp's vocab
__snake_case : str = os.path.join(get_home_dir() , 'models' )
__snake_case : Optional[int] = _load_vocab(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , cls=lowerCAmelCase_ )
__snake_case : List[str] = nlp.model.BERTModel(
lowerCAmelCase_ , len(lowerCAmelCase_ ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=lowerCAmelCase_ , use_token_type_embed=lowerCAmelCase_ , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=lowerCAmelCase_ , use_decoder=lowerCAmelCase_ , )
original_bort.load_parameters(lowerCAmelCase_ , cast_dtype=lowerCAmelCase_ , ignore_extra=lowerCAmelCase_ )
__snake_case : List[Any] = original_bort._collect_params_with_prefix()
# Build our config 🤗
__snake_case : Union[str, Any] = {
'''architectures''': ['''BertForMaskedLM'''],
'''attention_probs_dropout_prob''': predefined_args['''dropout'''],
'''hidden_act''': '''gelu''',
'''hidden_dropout_prob''': predefined_args['''dropout'''],
'''hidden_size''': predefined_args['''embed_size'''],
'''initializer_range''': 0.02,
'''intermediate_size''': predefined_args['''hidden_size'''],
'''layer_norm_eps''': predefined_args['''layer_norm_eps'''],
'''max_position_embeddings''': predefined_args['''max_length'''],
'''model_type''': '''bort''',
'''num_attention_heads''': predefined_args['''num_heads'''],
'''num_hidden_layers''': predefined_args['''num_layers'''],
'''pad_token_id''': 1, # 2 = BERT, 1 = RoBERTa
'''type_vocab_size''': 1, # 2 = BERT, 1 = RoBERTa
'''vocab_size''': len(lowerCAmelCase_ ),
}
__snake_case : Union[str, Any] = BertConfig.from_dict(lowerCAmelCase_ )
__snake_case : List[str] = BertForMaskedLM(lowerCAmelCase_ )
hf_bort_model.eval()
# Parameter mapping table (Gluonnlp to Transformers)
# * denotes layer index
#
# | Gluon Parameter | Transformers Parameter
# | -------------------------------------------------------------- | ----------------------
# | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias`
# | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight`
# | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight`
# | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight`
# | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias`
# | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight`
# | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight`
# | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias`
# | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight`
# | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias`
# | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight`
# | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias`
# | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight`
# Helper function to convert MXNET Arrays to PyTorch
def to_torch(A : Optional[int] ) -> nn.Parameter:
return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) )
# Check param shapes and map new HF param back
def check_and_map_params(A : Optional[int] , A : Union[str, Any] ):
__snake_case : Dict = hf_param.shape
__snake_case : Union[str, Any] = to_torch(params[gluon_param] )
__snake_case : str = gluon_param.shape
assert (
shape_hf == shape_gluon
), F"""The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers"""
return gluon_param
__snake_case : Union[str, Any] = check_and_map_params(
hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' )
__snake_case : Union[str, Any] = check_and_map_params(
hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' )
__snake_case : int = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' )
__snake_case : int = check_and_map_params(
hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' )
# Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them)
__snake_case : Tuple = torch.zeros_like(
hf_bort_model.bert.embeddings.token_type_embeddings.weight.data )
for i in range(hf_bort_config.num_hidden_layers ):
__snake_case : BertLayer = hf_bort_model.bert.encoder.layer[i]
# self attention
__snake_case : BertSelfAttention = layer.attention.self
__snake_case : List[str] = check_and_map_params(
self_attn.key.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.bias""" )
__snake_case : List[str] = check_and_map_params(
self_attn.key.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.weight""" )
__snake_case : int = check_and_map_params(
self_attn.query.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.bias""" )
__snake_case : List[Any] = check_and_map_params(
self_attn.query.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.weight""" )
__snake_case : List[str] = check_and_map_params(
self_attn.value.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.bias""" )
__snake_case : Union[str, Any] = check_and_map_params(
self_attn.value.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.weight""" )
# self attention output
__snake_case : BertSelfOutput = layer.attention.output
__snake_case : Union[str, Any] = check_and_map_params(
self_output.dense.bias , F"""encoder.transformer_cells.{i}.proj.bias""" )
__snake_case : str = check_and_map_params(
self_output.dense.weight , F"""encoder.transformer_cells.{i}.proj.weight""" )
__snake_case : Any = check_and_map_params(
self_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.layer_norm.beta""" )
__snake_case : Tuple = check_and_map_params(
self_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.layer_norm.gamma""" )
# intermediate
__snake_case : BertIntermediate = layer.intermediate
__snake_case : List[str] = check_and_map_params(
intermediate.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_1.bias""" )
__snake_case : Tuple = check_and_map_params(
intermediate.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_1.weight""" )
# output
__snake_case : BertOutput = layer.output
__snake_case : str = check_and_map_params(
bert_output.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_2.bias""" )
__snake_case : str = check_and_map_params(
bert_output.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_2.weight""" )
__snake_case : Optional[Any] = check_and_map_params(
bert_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.ffn.layer_norm.beta""" )
__snake_case : int = check_and_map_params(
bert_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.ffn.layer_norm.gamma""" )
# Save space and energy 🎄
hf_bort_model.half()
# Compare output of both models
__snake_case : Optional[Any] = RobertaTokenizer.from_pretrained('roberta-base' )
__snake_case : Union[str, Any] = tokenizer.encode_plus(lowerCAmelCase_ )['''input_ids''']
# Get gluon output
__snake_case : Tuple = mx.nd.array([input_ids] )
__snake_case : int = original_bort(inputs=lowerCAmelCase_ , token_types=[] )
# Get Transformer output (save and reload model again)
hf_bort_model.save_pretrained(lowerCAmelCase_ )
__snake_case : Tuple = BertModel.from_pretrained(lowerCAmelCase_ )
hf_bort_model.eval()
__snake_case : Dict = tokenizer.encode_plus(lowerCAmelCase_ , return_tensors='pt' )
__snake_case : List[str] = hf_bort_model(**lowerCAmelCase_ )[0]
__snake_case : Union[str, Any] = output_gluon[0].asnumpy()
__snake_case : Dict = output_hf[0].detach().numpy()
__snake_case : Dict = np.max(np.abs(hf_layer - gluon_layer ) ).item()
__snake_case : int = np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 )
if success:
print('✔️ Both model do output the same tensors' )
else:
print('❌ Both model do **NOT** output the same tensors' )
print('Absolute difference is:' , lowerCAmelCase_ )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.'''
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
__A = parser.parse_args()
convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path) | 703 |
'''simple docstring'''
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__) | 61 | 0 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( ) -> Tuple:
"""simple docstring"""
__snake_case : List[str] = []
__snake_case : int = 1
while len(SCREAMING_SNAKE_CASE__ ) < 1e6:
constant.append(str(SCREAMING_SNAKE_CASE__ ) )
i += 1
__snake_case : str = """""".join(SCREAMING_SNAKE_CASE__ )
return (
int(constant[0] )
* int(constant[9] )
* int(constant[99] )
* int(constant[9_99] )
* int(constant[99_99] )
* int(constant[9_99_99] )
* int(constant[99_99_99] )
)
if __name__ == "__main__":
print(solution()) | 704 |
'''simple docstring'''
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run
import sys
import warnings
from os.path import abspath, dirname, join
# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
__A = abspath(join(dirname(dirname(__file__)), '''src'''))
sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='''ignore''', category=FutureWarning)
def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> str:
"""simple docstring"""
from diffusers.utils.testing_utils import pytest_addoption_shared
pytest_addoption_shared(A )
def _SCREAMING_SNAKE_CASE ( A : int ) -> Optional[int]:
"""simple docstring"""
from diffusers.utils.testing_utils import pytest_terminal_summary_main
__snake_case : Any = terminalreporter.config.getoption('--make-reports' )
if make_reports:
pytest_terminal_summary_main(A , id=A ) | 61 | 0 |
'''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 _SCREAMING_SNAKE_CASE ( A : Optional[Any] , A : str , A : Any , A : Union[str, Any] , A : int ) -> List[Any]:
"""simple docstring"""
# Load configuration defined in the metadata file
with open(a_ ) as metadata_file:
__snake_case : Union[str, Any] = json.load(a_ )
__snake_case : Union[str, Any] = LukeConfig(use_entity_aware_attention=a_ , **metadata['model_config'] )
# Load in the weights from the checkpoint_path
__snake_case : List[str] = torch.load(a_ , map_location='cpu' )
# Load the entity vocab file
__snake_case : List[str] = load_entity_vocab(a_ )
__snake_case : Optional[int] = RobertaTokenizer.from_pretrained(metadata['model_config']['bert_model_name'] )
# Add special tokens to the token vocabulary for downstream tasks
__snake_case : int = AddedToken('<ent>' , lstrip=a_ , rstrip=a_ )
__snake_case : Optional[Any] = AddedToken('<ent2>' , lstrip=a_ , rstrip=a_ )
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(a_ )
with open(os.path.join(a_ , LukeTokenizer.vocab_files_names['entity_vocab_file'] ) , 'w' ) as f:
json.dump(a_ , a_ )
__snake_case : str = LukeTokenizer.from_pretrained(a_ )
# Initialize the embeddings of the special tokens
__snake_case : Union[str, Any] = state_dict['''embeddings.word_embeddings.weight''']
__snake_case : Any = word_emb[tokenizer.convert_tokens_to_ids(['@'] )[0]].unsqueeze(0 )
__snake_case : List[Any] = word_emb[tokenizer.convert_tokens_to_ids(['#'] )[0]].unsqueeze(0 )
__snake_case : Dict = 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"]:
__snake_case : Tuple = F"""encoder.layer.{layer_index}.attention.self."""
__snake_case : List[Any] = state_dict[prefix + matrix_name]
__snake_case : Any = state_dict[prefix + matrix_name]
__snake_case : str = state_dict[prefix + matrix_name]
# Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks
__snake_case : Any = state_dict['''entity_embeddings.entity_embeddings.weight''']
__snake_case : List[Any] = entity_emb[entity_vocab['''[MASK]''']]
__snake_case : int = LukeModel(config=a_ ).eval()
__snake_case : List[Any] = model.load_state_dict(a_ , strict=a_ )
if not (len(a_ ) == 1 and missing_keys[0] == "embeddings.position_ids"):
raise ValueError(F"""Missing keys {", ".join(a_ )}. 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
__snake_case : Tuple = LukeTokenizer.from_pretrained(a_ , task='entity_classification' )
__snake_case : int = (
'''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 .'''
)
__snake_case : int = (39, 42)
__snake_case : Optional[Any] = tokenizer(a_ , entity_spans=[span] , add_prefix_space=a_ , return_tensors='pt' )
__snake_case : List[str] = model(**a_ )
# Verify word hidden states
if model_size == "large":
__snake_case : List[Any] = torch.Size((1, 42, 10_24) )
__snake_case : Union[str, Any] = torch.tensor(
[[0.0133, 0.0865, 0.0095], [0.3093, -0.2576, -0.7418], [-0.1720, -0.2117, -0.2869]] )
else: # base
__snake_case : Optional[Any] = torch.Size((1, 42, 7_68) )
__snake_case : List[Any] = 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] , a_ , atol=1e-4 ):
raise ValueError
# Verify entity hidden states
if model_size == "large":
__snake_case : List[Any] = torch.Size((1, 1, 10_24) )
__snake_case : int = torch.tensor([[0.0466, -0.0106, -0.0179]] )
else: # base
__snake_case : Optional[int] = torch.Size((1, 1, 7_68) )
__snake_case : List[str] = 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] , a_ , atol=1e-4 ):
raise ValueError
# Finally, save our PyTorch model and tokenizer
print('Saving PyTorch model to {}'.format(a_ ) )
model.save_pretrained(a_ )
def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> Dict:
"""simple docstring"""
__snake_case : Optional[Any] = {}
with open(a_ , 'r' , encoding='utf-8' ) as f:
for index, line in enumerate(a_ ):
__snake_case : Tuple = line.rstrip().split('\t' )
__snake_case : str = 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,
)
| 705 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
__A = {
'''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''],
'''tokenization_biogpt''': ['''BioGptTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''BioGptForCausalLM''',
'''BioGptForTokenClassification''',
'''BioGptForSequenceClassification''',
'''BioGptModel''',
'''BioGptPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig
from .tokenization_biogpt import BioGptTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_biogpt import (
BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST,
BioGptForCausalLM,
BioGptForSequenceClassification,
BioGptForTokenClassification,
BioGptModel,
BioGptPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 61 | 0 |
'''simple docstring'''
import operator
def _SCREAMING_SNAKE_CASE ( A : list , A : bool = False , A : list | None = None ) -> List[Any]:
"""simple docstring"""
__snake_case : List[str] = operator.lt if reverse else operator.gt
__snake_case : str = solution or []
if not arr:
return solution
__snake_case : Union[str, Any] = [arr.pop(0 )]
for i, item in enumerate(A ):
if _operator(A , sublist[-1] ):
sublist.append(A )
arr.pop(A )
# merging sublist into solution list
if not solution:
solution.extend(A )
else:
while sublist:
__snake_case : Any = sublist.pop(0 )
for i, xx in enumerate(A ):
if not _operator(A , A ):
solution.insert(A , A )
break
else:
solution.append(A )
strand_sort(A , A , A )
return solution
if __name__ == "__main__":
assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5]
assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1] | 706 |
'''simple docstring'''
from packaging import version
from .import_utils import is_accelerate_available
if is_accelerate_available():
import accelerate
def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> int:
"""simple docstring"""
if not is_accelerate_available():
return method
__snake_case : Optional[Any] = version.parse(accelerate.__version__ ).base_version
if version.parse(A ) < version.parse('0.17.0' ):
return method
def wrapper(self : Optional[Any] , *A : Optional[Any] , **A : Optional[int] ):
if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ):
self._hf_hook.pre_forward(self )
return method(self , *A , **A )
return wrapper | 61 | 0 |
'''simple docstring'''
from typing import Any, Dict, Optional
import torch
import torch.nn.functional as F
from torch import nn
from ..utils import maybe_allow_in_graph
from .activations import get_activation
from .attention_processor import Attention
from .embeddings import CombinedTimestepLabelEmbeddings
@maybe_allow_in_graph
class a_ ( nn.Module ):
def __init__(self , __a , __a , __a , __a=0.0 , __a = None , __a = "geglu" , __a = None , __a = False , __a = False , __a = False , __a = False , __a = True , __a = "layer_norm" , __a = False , ) -> List[str]:
"""simple docstring"""
super().__init__()
__snake_case : Tuple = only_cross_attention
__snake_case : List[Any] = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
__snake_case : List[Any] = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
raise ValueError(
F"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"""
F""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.""")
# Define 3 blocks. Each block has its own normalization layer.
# 1. Self-Attn
if self.use_ada_layer_norm:
__snake_case : Union[str, Any] = AdaLayerNorm(__a , __a)
elif self.use_ada_layer_norm_zero:
__snake_case : Any = AdaLayerNormZero(__a , __a)
else:
__snake_case : Optional[Any] = nn.LayerNorm(__a , elementwise_affine=__a)
__snake_case : Union[str, Any] = Attention(
query_dim=__a , heads=__a , dim_head=__a , dropout=__a , bias=__a , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=__a , )
# 2. Cross-Attn
if cross_attention_dim is not None or double_self_attention:
# We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
# I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
# the second cross attention block.
__snake_case : int = (
AdaLayerNorm(__a , __a)
if self.use_ada_layer_norm
else nn.LayerNorm(__a , elementwise_affine=__a)
)
__snake_case : Optional[Any] = Attention(
query_dim=__a , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=__a , dim_head=__a , dropout=__a , bias=__a , upcast_attention=__a , ) # is self-attn if encoder_hidden_states is none
else:
__snake_case : Optional[Any] = None
__snake_case : Optional[int] = None
# 3. Feed-forward
__snake_case : List[Any] = nn.LayerNorm(__a , elementwise_affine=__a)
__snake_case : Any = FeedForward(__a , dropout=__a , activation_fn=__a , final_dropout=__a)
# let chunk size default to None
__snake_case : List[str] = None
__snake_case : Optional[Any] = 0
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Tuple:
"""simple docstring"""
__snake_case : List[str] = chunk_size
__snake_case : Tuple = dim
def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , ) -> Optional[Any]:
"""simple docstring"""
if self.use_ada_layer_norm:
__snake_case : int = self.norma(__a , __a)
elif self.use_ada_layer_norm_zero:
__snake_case : Dict = self.norma(
__a , __a , __a , hidden_dtype=hidden_states.dtype)
else:
__snake_case : str = self.norma(__a)
__snake_case : Optional[int] = cross_attention_kwargs if cross_attention_kwargs is not None else {}
__snake_case : Optional[int] = self.attna(
__a , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=__a , **__a , )
if self.use_ada_layer_norm_zero:
__snake_case : Optional[int] = gate_msa.unsqueeze(1) * attn_output
__snake_case : Tuple = attn_output + hidden_states
# 2. Cross-Attention
if self.attna is not None:
__snake_case : str = (
self.norma(__a , __a) if self.use_ada_layer_norm else self.norma(__a)
)
__snake_case : Any = self.attna(
__a , encoder_hidden_states=__a , attention_mask=__a , **__a , )
__snake_case : List[Any] = attn_output + hidden_states
# 3. Feed-forward
__snake_case : Optional[int] = self.norma(__a)
if self.use_ada_layer_norm_zero:
__snake_case : str = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
if self._chunk_size is not None:
# "feed_forward_chunk_size" can be used to save memory
if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
raise ValueError(
F"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.""")
__snake_case : str = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
__snake_case : Dict = torch.cat(
[self.ff(__a) for hid_slice in norm_hidden_states.chunk(__a , dim=self._chunk_dim)] , dim=self._chunk_dim , )
else:
__snake_case : Optional[int] = self.ff(__a)
if self.use_ada_layer_norm_zero:
__snake_case : Any = gate_mlp.unsqueeze(1) * ff_output
__snake_case : Tuple = ff_output + hidden_states
return hidden_states
class a_ ( nn.Module ):
def __init__(self , __a , __a = None , __a = 4 , __a = 0.0 , __a = "geglu" , __a = False , ) -> str:
"""simple docstring"""
super().__init__()
__snake_case : List[Any] = int(dim * mult)
__snake_case : List[Any] = dim_out if dim_out is not None else dim
if activation_fn == "gelu":
__snake_case : Optional[Any] = GELU(__a , __a)
if activation_fn == "gelu-approximate":
__snake_case : Dict = GELU(__a , __a , approximate='tanh')
elif activation_fn == "geglu":
__snake_case : Dict = GEGLU(__a , __a)
elif activation_fn == "geglu-approximate":
__snake_case : List[str] = ApproximateGELU(__a , __a)
__snake_case : Union[str, Any] = nn.ModuleList([])
# project in
self.net.append(__a)
# project dropout
self.net.append(nn.Dropout(__a))
# project out
self.net.append(nn.Linear(__a , __a))
# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
if final_dropout:
self.net.append(nn.Dropout(__a))
def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]:
"""simple docstring"""
for module in self.net:
__snake_case : int = module(__a)
return hidden_states
class a_ ( nn.Module ):
def __init__(self , __a , __a , __a = "none") -> List[str]:
"""simple docstring"""
super().__init__()
__snake_case : Optional[Any] = nn.Linear(__a , __a)
__snake_case : List[str] = approximate
def SCREAMING_SNAKE_CASE__ (self , __a) -> Dict:
"""simple docstring"""
if gate.device.type != "mps":
return F.gelu(__a , approximate=self.approximate)
# mps: gelu is not implemented for float16
return F.gelu(gate.to(dtype=torch.floataa) , approximate=self.approximate).to(dtype=gate.dtype)
def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple:
"""simple docstring"""
__snake_case : int = self.proj(__a)
__snake_case : List[Any] = self.gelu(__a)
return hidden_states
class a_ ( nn.Module ):
def __init__(self , __a , __a) -> str:
"""simple docstring"""
super().__init__()
__snake_case : Optional[Any] = nn.Linear(__a , dim_out * 2)
def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]:
"""simple docstring"""
if gate.device.type != "mps":
return F.gelu(__a)
# mps: gelu is not implemented for float16
return F.gelu(gate.to(dtype=torch.floataa)).to(dtype=gate.dtype)
def SCREAMING_SNAKE_CASE__ (self , __a) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[Any] = self.proj(__a).chunk(2 , dim=-1)
return hidden_states * self.gelu(__a)
class a_ ( nn.Module ):
def __init__(self , __a , __a) -> Any:
"""simple docstring"""
super().__init__()
__snake_case : str = nn.Linear(__a , __a)
def SCREAMING_SNAKE_CASE__ (self , __a) -> str:
"""simple docstring"""
__snake_case : Dict = self.proj(__a)
return x * torch.sigmoid(1.702 * x)
class a_ ( nn.Module ):
def __init__(self , __a , __a) -> Union[str, Any]:
"""simple docstring"""
super().__init__()
__snake_case : Dict = nn.Embedding(__a , __a)
__snake_case : Optional[int] = nn.SiLU()
__snake_case : Tuple = nn.Linear(__a , embedding_dim * 2)
__snake_case : str = nn.LayerNorm(__a , elementwise_affine=__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> List[Any]:
"""simple docstring"""
__snake_case : Optional[int] = self.linear(self.silu(self.emb(__a)))
__snake_case : Optional[Any] = torch.chunk(__a , 2)
__snake_case : List[Any] = self.norm(__a) * (1 + scale) + shift
return x
class a_ ( nn.Module ):
def __init__(self , __a , __a) -> List[Any]:
"""simple docstring"""
super().__init__()
__snake_case : Any = CombinedTimestepLabelEmbeddings(__a , __a)
__snake_case : List[str] = nn.SiLU()
__snake_case : Optional[int] = nn.Linear(__a , 6 * embedding_dim , bias=__a)
__snake_case : List[str] = nn.LayerNorm(__a , elementwise_affine=__a , eps=1E-6)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a=None) -> int:
"""simple docstring"""
__snake_case : Tuple = self.linear(self.silu(self.emb(__a , __a , hidden_dtype=__a)))
__snake_case : str = emb.chunk(6 , dim=1)
__snake_case : Tuple = self.norm(__a) * (1 + scale_msa[:, None]) + shift_msa[:, None]
return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
class a_ ( nn.Module ):
def __init__(self , __a , __a , __a , __a = None , __a = 1E-5) -> Dict:
"""simple docstring"""
super().__init__()
__snake_case : Optional[int] = num_groups
__snake_case : List[str] = eps
if act_fn is None:
__snake_case : int = None
else:
__snake_case : List[str] = get_activation(__a)
__snake_case : List[Any] = nn.Linear(__a , out_dim * 2)
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Tuple:
"""simple docstring"""
if self.act:
__snake_case : Any = self.act(__a)
__snake_case : Optional[Any] = self.linear(__a)
__snake_case : Tuple = emb[:, :, None, None]
__snake_case : Optional[int] = emb.chunk(2 , dim=1)
__snake_case : Optional[int] = F.group_norm(__a , self.num_groups , eps=self.eps)
__snake_case : Optional[Any] = x * (1 + scale) + shift
return x | 707 |
'''simple docstring'''
import unittest
from transformers import load_tool
from transformers.utils import is_torch_available
if is_torch_available():
import torch
from transformers.testing_utils import require_torch
from .test_tools_common import ToolTesterMixin
@require_torch
class a_ ( unittest.TestCase , UpperCamelCase_ ):
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[str] = load_tool('text-to-speech')
self.tool.setup()
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : Dict = self.tool('hey')
__snake_case : List[Any] = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , ))
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : Any = self.tool('hey')
__snake_case : Any = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , )) | 61 | 0 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : Optional[int] ) -> Union[str, Any]:
"""simple docstring"""
__snake_case ,__snake_case : Any = [], []
while len(__UpperCamelCase ) > 1:
__snake_case ,__snake_case : Optional[Any] = min(__UpperCamelCase ), max(__UpperCamelCase )
start.append(__UpperCamelCase )
end.append(__UpperCamelCase )
collection.remove(__UpperCamelCase )
collection.remove(__UpperCamelCase )
end.reverse()
return start + collection + end
if __name__ == "__main__":
__A = input('''Enter numbers separated by a comma:\n''').strip()
__A = [int(item) for item in user_input.split(''',''')]
print(*merge_sort(unsorted), sep=''',''') | 708 |
'''simple docstring'''
import math
class a_ :
def __init__(self , __a=0) -> Any: # a graph with Node 0,1,...,N-1
"""simple docstring"""
__snake_case : List[str] = n
__snake_case : Tuple = [
[math.inf for j in range(0 , __a)] for i in range(0 , __a)
] # adjacency matrix for weight
__snake_case : Union[str, Any] = [
[math.inf for j in range(0 , __a)] for i in range(0 , __a)
] # dp[i][j] stores minimum distance from i to j
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple:
"""simple docstring"""
__snake_case : Union[str, Any] = w
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
for k in range(0 , self.n):
for i in range(0 , self.n):
for j in range(0 , self.n):
__snake_case : List[Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j])
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Optional[int]:
"""simple docstring"""
return self.dp[u][v]
if __name__ == "__main__":
__A = Graph(5)
graph.add_edge(0, 2, 9)
graph.add_edge(0, 4, 1_0)
graph.add_edge(1, 3, 5)
graph.add_edge(2, 3, 7)
graph.add_edge(3, 0, 1_0)
graph.add_edge(3, 1, 2)
graph.add_edge(3, 2, 1)
graph.add_edge(3, 4, 6)
graph.add_edge(4, 1, 3)
graph.add_edge(4, 2, 4)
graph.add_edge(4, 3, 9)
graph.floyd_warshall()
graph.show_min(1, 4)
graph.show_min(0, 3) | 61 | 0 |
'''simple docstring'''
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 how to properly calculate the metrics on the
# validation dataset when in a distributed system, 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
#
########################################################################
__A = 1_6
__A = 3_2
def _SCREAMING_SNAKE_CASE ( A : int , A : int = 16 ) -> Optional[Any]:
"""simple docstring"""
__snake_case : Tuple = AutoTokenizer.from_pretrained('bert-base-cased' )
__snake_case : Union[str, Any] = load_dataset('glue' , 'mrpc' )
def tokenize_function(A : Optional[Any] ):
# max_length=None => use the model max length (it's actually the default)
__snake_case : Optional[int] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=A , max_length=A )
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():
__snake_case : Union[str, Any] = datasets.map(
A , batched=A , 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
__snake_case : int = tokenized_datasets.rename_column('label' , 'labels' )
def collate_fn(A : str ):
# On TPU it's best to pad everything to the same length or training will be very slow.
__snake_case : List[Any] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
__snake_case : Any = 16
elif accelerator.mixed_precision != "no":
__snake_case : Any = 8
else:
__snake_case : Optional[int] = None
return tokenizer.pad(
A , padding='longest' , max_length=A , pad_to_multiple_of=A , return_tensors='pt' , )
# Instantiate dataloaders.
__snake_case : List[Any] = DataLoader(
tokenized_datasets['train'] , shuffle=A , collate_fn=A , batch_size=A )
__snake_case : Any = DataLoader(
tokenized_datasets['validation'] , shuffle=A , collate_fn=A , batch_size=A )
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
__A = mocked_dataloaders # noqa: F811
def _SCREAMING_SNAKE_CASE ( A : Optional[Any] , A : Optional[Any] ) -> List[Any]:
"""simple docstring"""
if os.environ.get('TESTING_MOCKED_DATALOADERS' , A ) == "1":
__snake_case : List[Any] = 2
# Initialize accelerator
__snake_case : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
__snake_case : int = config['lr']
__snake_case : List[str] = int(config['num_epochs'] )
__snake_case : Union[str, Any] = int(config['seed'] )
__snake_case : Optional[int] = int(config['batch_size'] )
__snake_case : List[Any] = evaluate.load('glue' , 'mrpc' )
# If the batch size is too big we use gradient accumulation
__snake_case : Dict = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
__snake_case : int = batch_size // MAX_GPU_BATCH_SIZE
__snake_case : int = MAX_GPU_BATCH_SIZE
set_seed(A )
__snake_case ,__snake_case : Dict = get_dataloaders(A , A )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
__snake_case : Any = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=A )
# 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).
__snake_case : Optional[int] = model.to(accelerator.device )
# Instantiate optimizer
__snake_case : int = AdamW(params=model.parameters() , lr=A )
# Instantiate scheduler
__snake_case : int = get_linear_schedule_with_warmup(
optimizer=A , num_warmup_steps=1_00 , num_training_steps=(len(A ) * 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.
__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case : Optional[int] = accelerator.prepare(
A , A , A , A , A )
# Now we train the model
for epoch in range(A ):
model.train()
for step, batch in enumerate(A ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
__snake_case : str = model(**A )
__snake_case : int = outputs.loss
__snake_case : str = loss / gradient_accumulation_steps
accelerator.backward(A )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
__snake_case : Tuple = 0
for step, batch in enumerate(A ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
__snake_case : List[Any] = model(**A )
__snake_case : List[str] = outputs.logits.argmax(dim=-1 )
__snake_case ,__snake_case : int = accelerator.gather((predictions, batch['labels']) )
# New Code #
# First we check if it's a distributed system
if accelerator.use_distributed:
# Then see if we're on the last batch of our eval dataloader
if step == len(A ) - 1:
# Last batch needs to be truncated on distributed systems as it contains additional samples
__snake_case : Dict = predictions[: len(eval_dataloader.dataset ) - samples_seen]
__snake_case : Optional[Any] = references[: len(eval_dataloader.dataset ) - samples_seen]
else:
# Otherwise we add the number of samples seen
samples_seen += references.shape[0]
# All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`:
# accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=A , references=A , )
__snake_case : Tuple = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(F"""epoch {epoch}:""" , A )
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
__snake_case : Optional[int] = argparse.ArgumentParser(description='Simple example of training script.' )
parser.add_argument(
'--mixed_precision' , type=A , default=A , 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.' )
__snake_case : int = parser.parse_args()
__snake_case : Optional[Any] = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16}
training_function(A , A )
if __name__ == "__main__":
main() | 709 |
'''simple docstring'''
from typing import Dict, List, Optional, Union
import numpy as np
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,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_vision_available():
import PIL
__A = logging.get_logger(__name__)
class a_ ( UpperCamelCase_ ):
_snake_case = ["""pixel_values"""]
def __init__(self , __a = True , __a = None , __a = None , __a = PILImageResampling.BILINEAR , __a = True , __a = 1 / 2_5_5 , __a = True , __a = None , __a = None , **__a , ) -> None:
"""simple docstring"""
super().__init__(**__a)
__snake_case : Tuple = size if size is not None else {'shortest_edge': 3_8_4}
__snake_case : List[Any] = get_size_dict(__a , default_to_square=__a)
__snake_case : int = do_resize
__snake_case : List[str] = size
# Default value set here for backwards compatibility where the value in config is None
__snake_case : Any = crop_pct if crop_pct is not None else 2_2_4 / 2_5_6
__snake_case : Tuple = resample
__snake_case : Dict = do_rescale
__snake_case : Any = rescale_factor
__snake_case : str = do_normalize
__snake_case : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
__snake_case : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = PILImageResampling.BICUBIC , __a = None , **__a , ) -> np.ndarray:
"""simple docstring"""
__snake_case : Dict = get_size_dict(__a , default_to_square=__a)
if "shortest_edge" not in size:
raise ValueError(F"""Size dictionary must contain 'shortest_edge' key. Got {size.keys()}""")
__snake_case : List[str] = size['shortest_edge']
if shortest_edge < 3_8_4:
# maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
__snake_case : Any = int(shortest_edge / crop_pct)
__snake_case : Any = get_resize_output_image_size(__a , size=__a , default_to_square=__a)
__snake_case : int = resize(image=__a , size=__a , resample=__a , data_format=__a , **__a)
# then crop to (shortest_edge, shortest_edge)
return center_crop(image=__a , size=(shortest_edge, shortest_edge) , data_format=__a , **__a)
else:
# warping (no cropping) when evaluated at 384 or larger
return resize(
__a , size=(shortest_edge, shortest_edge) , resample=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> Any:
"""simple docstring"""
return rescale(__a , scale=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray:
"""simple docstring"""
return normalize(__a , mean=__a , std=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image:
"""simple docstring"""
__snake_case : Optional[int] = do_resize if do_resize is not None else self.do_resize
__snake_case : Dict = crop_pct if crop_pct is not None else self.crop_pct
__snake_case : Tuple = resample if resample is not None else self.resample
__snake_case : Any = do_rescale if do_rescale is not None else self.do_rescale
__snake_case : Any = rescale_factor if rescale_factor is not None else self.rescale_factor
__snake_case : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize
__snake_case : Optional[int] = image_mean if image_mean is not None else self.image_mean
__snake_case : Optional[Any] = image_std if image_std is not None else self.image_std
__snake_case : List[str] = size if size is not None else self.size
__snake_case : Any = get_size_dict(__a , default_to_square=__a)
__snake_case : Dict = make_list_of_images(__a)
if not valid_images(__a):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.')
if do_resize and size is None or resample is None:
raise ValueError('Size and resample must be specified if do_resize is True.')
if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None:
raise ValueError('crop_pct must be specified if size < 384.')
if do_rescale and rescale_factor is None:
raise ValueError('Rescale factor must be specified if do_rescale is True.')
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('Image mean and std must be specified if do_normalize is True.')
# All transformations expect numpy arrays.
__snake_case : Tuple = [to_numpy_array(__a) for image in images]
if do_resize:
__snake_case : Optional[int] = [self.resize(image=__a , size=__a , crop_pct=__a , resample=__a) for image in images]
if do_rescale:
__snake_case : Optional[int] = [self.rescale(image=__a , scale=__a) for image in images]
if do_normalize:
__snake_case : Any = [self.normalize(image=__a , mean=__a , std=__a) for image in images]
__snake_case : Dict = [to_channel_dimension_format(__a , __a) for image in images]
__snake_case : Union[str, Any] = {'pixel_values': images}
return BatchFeature(data=__a , tensor_type=__a) | 61 | 0 |
import logging
import os
import threading
import time
try:
import warnings
except ImportError:
__A = None
try:
import msvcrt
except ImportError:
__A = None
try:
import fcntl
except ImportError:
__A = None
# Backward compatibility
# ------------------------------------------------
try:
TimeoutError
except NameError:
__A = OSError
# Data
# ------------------------------------------------
__A = [
'''Timeout''',
'''BaseFileLock''',
'''WindowsFileLock''',
'''UnixFileLock''',
'''SoftFileLock''',
'''FileLock''',
]
__A = '''3.0.12'''
__A = None
def _SCREAMING_SNAKE_CASE ( ) -> str:
"""simple docstring"""
global _logger
__snake_case : str = _logger or logging.getLogger(__name__ )
return _logger
class a_ ( UpperCamelCase__ ):
def __init__(self , __a) -> List[str]:
"""simple docstring"""
__snake_case : int = lock_file
return None
def __str__(self) -> str:
"""simple docstring"""
__snake_case : List[Any] = F"""The file lock \'{self.lock_file}\' could not be acquired."""
return temp
class a_ :
def __init__(self , __a) -> Tuple:
"""simple docstring"""
__snake_case : Optional[int] = lock
return None
def __enter__(self) -> List[Any]:
"""simple docstring"""
return self.lock
def __exit__(self , __a , __a , __a) -> List[Any]:
"""simple docstring"""
self.lock.release()
return None
class a_ :
def __init__(self , __a , __a=-1 , __a=None) -> List[Any]:
"""simple docstring"""
__snake_case : List[Any] = max_filename_length if max_filename_length is not None else 2_5_5
# Hash the filename if it's too long
__snake_case : int = self.hash_filename_if_too_long(_a , _a)
# The path to the lock file.
__snake_case : Optional[int] = lock_file
# The file descriptor for the *_lock_file* as it is returned by the
# os.open() function.
# This file lock is only NOT None, if the object currently holds the
# lock.
__snake_case : Optional[int] = None
# The default timeout value.
__snake_case : Union[str, Any] = timeout
# We use this lock primarily for the lock counter.
__snake_case : str = threading.Lock()
# The lock counter is used for implementing the nested locking
# mechanism. Whenever the lock is acquired, the counter is increased and
# the lock is only released, when this value is 0 again.
__snake_case : str = 0
return None
@property
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
return self._lock_file
@property
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
return self._timeout
@timeout.setter
def SCREAMING_SNAKE_CASE__ (self , __a) -> Optional[int]:
"""simple docstring"""
__snake_case : Dict = float(_a)
return None
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
raise NotImplementedError()
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
raise NotImplementedError()
@property
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
return self._lock_file_fd is not None
def SCREAMING_SNAKE_CASE__ (self , __a=None , __a=0.05) -> Dict:
"""simple docstring"""
if timeout is None:
__snake_case : Tuple = self.timeout
# Increment the number right at the beginning.
# We can still undo it, if something fails.
with self._thread_lock:
self._lock_counter += 1
__snake_case : Optional[int] = id(self)
__snake_case : str = self._lock_file
__snake_case : Tuple = time.time()
try:
while True:
with self._thread_lock:
if not self.is_locked:
logger().debug(F"""Attempting to acquire lock {lock_id} on {lock_filename}""")
self._acquire()
if self.is_locked:
logger().debug(F"""Lock {lock_id} acquired on {lock_filename}""")
break
elif timeout >= 0 and time.time() - start_time > timeout:
logger().debug(F"""Timeout on acquiring lock {lock_id} on {lock_filename}""")
raise Timeout(self._lock_file)
else:
logger().debug(
F"""Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...""")
time.sleep(_a)
except: # noqa
# Something did go wrong, so decrement the counter.
with self._thread_lock:
__snake_case : List[Any] = max(0 , self._lock_counter - 1)
raise
return _Acquire_ReturnProxy(lock=self)
def SCREAMING_SNAKE_CASE__ (self , __a=False) -> Optional[int]:
"""simple docstring"""
with self._thread_lock:
if self.is_locked:
self._lock_counter -= 1
if self._lock_counter == 0 or force:
__snake_case : Optional[Any] = id(self)
__snake_case : str = self._lock_file
logger().debug(F"""Attempting to release lock {lock_id} on {lock_filename}""")
self._release()
__snake_case : Tuple = 0
logger().debug(F"""Lock {lock_id} released on {lock_filename}""")
return None
def __enter__(self) -> Any:
"""simple docstring"""
self.acquire()
return self
def __exit__(self , __a , __a , __a) -> int:
"""simple docstring"""
self.release()
return None
def __del__(self) -> List[Any]:
"""simple docstring"""
self.release(force=_a)
return None
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> str:
"""simple docstring"""
__snake_case : Optional[Any] = os.path.basename(_a)
if len(_a) > max_length and max_length > 0:
__snake_case : Dict = os.path.dirname(_a)
__snake_case : Any = str(hash(_a))
__snake_case : Tuple = filename[: max_length - len(_a) - 8] + """...""" + hashed_filename + """.lock"""
return os.path.join(_a , _a)
else:
return path
class a_ ( UpperCamelCase__ ):
def __init__(self , __a , __a=-1 , __a=None) -> Union[str, Any]:
"""simple docstring"""
from .file_utils import relative_to_absolute_path
super().__init__(_a , timeout=_a , max_filename_length=_a)
__snake_case : Optional[Any] = """\\\\?\\""" + relative_to_absolute_path(self.lock_file)
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case : List[str] = os.O_RDWR | os.O_CREAT | os.O_TRUNC
try:
__snake_case : Optional[Any] = os.open(self._lock_file , _a)
except OSError:
pass
else:
try:
msvcrt.locking(_a , msvcrt.LK_NBLCK , 1)
except OSError:
os.close(_a)
else:
__snake_case : str = fd
return None
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : str = self._lock_file_fd
__snake_case : Any = None
msvcrt.locking(_a , msvcrt.LK_UNLCK , 1)
os.close(_a)
try:
os.remove(self._lock_file)
# Probably another instance of the application
# that acquired the file lock.
except OSError:
pass
return None
class a_ ( UpperCamelCase__ ):
def __init__(self , __a , __a=-1 , __a=None) -> Optional[int]:
"""simple docstring"""
__snake_case : List[Any] = os.statvfs(os.path.dirname(_a)).f_namemax
super().__init__(_a , timeout=_a , max_filename_length=_a)
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : Any = os.O_RDWR | os.O_CREAT | os.O_TRUNC
__snake_case : Any = os.open(self._lock_file , _a)
try:
fcntl.flock(_a , fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
os.close(_a)
else:
__snake_case : Dict = fd
return None
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Any = self._lock_file_fd
__snake_case : Dict = None
fcntl.flock(_a , fcntl.LOCK_UN)
os.close(_a)
return None
class a_ ( UpperCamelCase__ ):
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case : Dict = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
try:
__snake_case : Optional[Any] = os.open(self._lock_file , _a)
except OSError:
pass
else:
__snake_case : str = fd
return None
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
os.close(self._lock_file_fd)
__snake_case : Dict = None
try:
os.remove(self._lock_file)
# The file is already deleted and that's what we want.
except OSError:
pass
return None
__A = None
if msvcrt:
__A = WindowsFileLock
elif fcntl:
__A = UnixFileLock
else:
__A = SoftFileLock
if warnings is not None:
warnings.warn('''only soft file lock is available''') | 710 |
'''simple docstring'''
from functools import lru_cache
@lru_cache
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
if num < 0:
raise ValueError('Number should not be negative.' )
return 1 if num in (0, 1) else num * factorial(num - 1 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 61 | 0 |
'''simple docstring'''
import argparse
import json
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation
def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> List[Any]:
"""simple docstring"""
__snake_case : Optional[int] = 3_84
if "tiny" in model_name:
__snake_case : Any = [3, 3, 9, 3]
__snake_case : Union[str, Any] = [96, 1_92, 3_84, 7_68]
if "small" in model_name:
__snake_case : int = [3, 3, 27, 3]
__snake_case : Dict = [96, 1_92, 3_84, 7_68]
if "base" in model_name:
__snake_case : Tuple = [3, 3, 27, 3]
__snake_case : List[Any] = [1_28, 2_56, 5_12, 10_24]
__snake_case : Union[str, Any] = 5_12
if "large" in model_name:
__snake_case : int = [3, 3, 27, 3]
__snake_case : Union[str, Any] = [1_92, 3_84, 7_68, 15_36]
__snake_case : Optional[Any] = 7_68
if "xlarge" in model_name:
__snake_case : Dict = [3, 3, 27, 3]
__snake_case : str = [2_56, 5_12, 10_24, 20_48]
__snake_case : List[str] = 10_24
# set label information
__snake_case : Any = 1_50
__snake_case : Optional[int] = '''huggingface/label-files'''
__snake_case : Union[str, Any] = '''ade20k-id2label.json'''
__snake_case : List[Any] = json.load(open(hf_hub_download(__UpperCamelCase , __UpperCamelCase , repo_type='dataset' ) , 'r' ) )
__snake_case : Any = {int(__UpperCamelCase ): v for k, v in idalabel.items()}
__snake_case : Any = {v: k for k, v in idalabel.items()}
__snake_case : int = ConvNextConfig(
depths=__UpperCamelCase , hidden_sizes=__UpperCamelCase , out_features=['stage1', 'stage2', 'stage3', 'stage4'] )
__snake_case : int = UperNetConfig(
backbone_config=__UpperCamelCase , auxiliary_in_channels=__UpperCamelCase , num_labels=__UpperCamelCase , idalabel=__UpperCamelCase , labelaid=__UpperCamelCase , )
return config
def _SCREAMING_SNAKE_CASE ( A : Dict ) -> Dict:
"""simple docstring"""
__snake_case : Optional[Any] = []
# fmt: off
# stem
rename_keys.append(('backbone.downsample_layers.0.0.weight', 'backbone.embeddings.patch_embeddings.weight') )
rename_keys.append(('backbone.downsample_layers.0.0.bias', 'backbone.embeddings.patch_embeddings.bias') )
rename_keys.append(('backbone.downsample_layers.0.1.weight', 'backbone.embeddings.layernorm.weight') )
rename_keys.append(('backbone.downsample_layers.0.1.bias', 'backbone.embeddings.layernorm.bias') )
# stages
for i in range(len(config.backbone_config.depths ) ):
for j in range(config.backbone_config.depths[i] ):
rename_keys.append((F"""backbone.stages.{i}.{j}.gamma""", F"""backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter""") )
rename_keys.append((F"""backbone.stages.{i}.{j}.depthwise_conv.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.dwconv.weight""") )
rename_keys.append((F"""backbone.stages.{i}.{j}.depthwise_conv.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.dwconv.bias""") )
rename_keys.append((F"""backbone.stages.{i}.{j}.norm.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.layernorm.weight""") )
rename_keys.append((F"""backbone.stages.{i}.{j}.norm.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.layernorm.bias""") )
rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv1.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight""") )
rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv1.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias""") )
rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv2.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight""") )
rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv2.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias""") )
if i > 0:
rename_keys.append((F"""backbone.downsample_layers.{i}.0.weight""", F"""backbone.encoder.stages.{i}.downsampling_layer.0.weight""") )
rename_keys.append((F"""backbone.downsample_layers.{i}.0.bias""", F"""backbone.encoder.stages.{i}.downsampling_layer.0.bias""") )
rename_keys.append((F"""backbone.downsample_layers.{i}.1.weight""", F"""backbone.encoder.stages.{i}.downsampling_layer.1.weight""") )
rename_keys.append((F"""backbone.downsample_layers.{i}.1.bias""", F"""backbone.encoder.stages.{i}.downsampling_layer.1.bias""") )
rename_keys.append((F"""backbone.norm{i}.weight""", F"""backbone.hidden_states_norms.stage{i+1}.weight""") )
rename_keys.append((F"""backbone.norm{i}.bias""", F"""backbone.hidden_states_norms.stage{i+1}.bias""") )
# decode head
rename_keys.extend(
[
('decode_head.conv_seg.weight', 'decode_head.classifier.weight'),
('decode_head.conv_seg.bias', 'decode_head.classifier.bias'),
('auxiliary_head.conv_seg.weight', 'auxiliary_head.classifier.weight'),
('auxiliary_head.conv_seg.bias', 'auxiliary_head.classifier.bias'),
] )
# fmt: on
return rename_keys
def _SCREAMING_SNAKE_CASE ( A : Any , A : List[Any] , A : Optional[int] ) -> Dict:
"""simple docstring"""
__snake_case : Optional[Any] = dct.pop(__UpperCamelCase )
__snake_case : Dict = val
def _SCREAMING_SNAKE_CASE ( A : List[Any] , A : str , A : Optional[Any] ) -> Tuple:
"""simple docstring"""
__snake_case : int = {
'''upernet-convnext-tiny''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth''',
'''upernet-convnext-small''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth''',
'''upernet-convnext-base''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth''',
'''upernet-convnext-large''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth''',
'''upernet-convnext-xlarge''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth''',
}
__snake_case : Dict = model_name_to_url[model_name]
__snake_case : str = torch.hub.load_state_dict_from_url(__UpperCamelCase , map_location='cpu' )['''state_dict''']
__snake_case : Dict = get_upernet_config(__UpperCamelCase )
__snake_case : Union[str, Any] = UperNetForSemanticSegmentation(__UpperCamelCase )
model.eval()
# replace "bn" => "batch_norm"
for key in state_dict.copy().keys():
__snake_case : int = state_dict.pop(__UpperCamelCase )
if "bn" in key:
__snake_case : Union[str, Any] = key.replace('bn' , 'batch_norm' )
__snake_case : Union[str, Any] = val
# rename keys
__snake_case : List[str] = create_rename_keys(__UpperCamelCase )
for src, dest in rename_keys:
rename_key(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
model.load_state_dict(__UpperCamelCase )
# verify on image
__snake_case : List[Any] = '''https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg'''
__snake_case : int = Image.open(requests.get(__UpperCamelCase , stream=__UpperCamelCase ).raw ).convert('RGB' )
__snake_case : Union[str, Any] = SegformerImageProcessor()
__snake_case : Union[str, Any] = processor(__UpperCamelCase , return_tensors='pt' ).pixel_values
with torch.no_grad():
__snake_case : Dict = model(__UpperCamelCase )
if model_name == "upernet-convnext-tiny":
__snake_case : Union[str, Any] = torch.tensor(
[[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] )
elif model_name == "upernet-convnext-small":
__snake_case : List[str] = torch.tensor(
[[-8.8236, -8.8236, -8.6771], [-8.8236, -8.8236, -8.6771], [-8.7638, -8.7638, -8.6240]] )
elif model_name == "upernet-convnext-base":
__snake_case : Any = torch.tensor(
[[-8.8558, -8.8558, -8.6905], [-8.8558, -8.8558, -8.6905], [-8.7669, -8.7669, -8.6021]] )
elif model_name == "upernet-convnext-large":
__snake_case : Union[str, Any] = torch.tensor(
[[-8.6660, -8.6660, -8.6210], [-8.6660, -8.6660, -8.6210], [-8.6310, -8.6310, -8.5964]] )
elif model_name == "upernet-convnext-xlarge":
__snake_case : List[Any] = torch.tensor(
[[-8.4980, -8.4980, -8.3977], [-8.4980, -8.4980, -8.3977], [-8.4379, -8.4379, -8.3412]] )
print('Logits:' , outputs.logits[0, 0, :3, :3] )
assert torch.allclose(outputs.logits[0, 0, :3, :3] , __UpperCamelCase , atol=1e-4 )
print('Looks ok!' )
if pytorch_dump_folder_path is not None:
print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" )
model.save_pretrained(__UpperCamelCase )
print(F"""Saving processor to {pytorch_dump_folder_path}""" )
processor.save_pretrained(__UpperCamelCase )
if push_to_hub:
print(F"""Pushing model and processor for {model_name} to hub""" )
model.push_to_hub(F"""openmmlab/{model_name}""" )
processor.push_to_hub(F"""openmmlab/{model_name}""" )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--model_name''',
default='''upernet-convnext-tiny''',
type=str,
choices=[f'''upernet-convnext-{size}''' for size in ['''tiny''', '''small''', '''base''', '''large''', '''xlarge''']],
help='''Name of the ConvNext UperNet model you\'d like to convert.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
)
parser.add_argument(
'''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
)
__A = parser.parse_args()
convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub) | 711 |
'''simple docstring'''
import unittest
import torch
from diffusers import VQModel
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism
from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ):
_snake_case = VQModel
_snake_case = """sample"""
@property
def SCREAMING_SNAKE_CASE__ (self , __a=(3_2, 3_2)) -> str:
"""simple docstring"""
__snake_case : Dict = 4
__snake_case : Optional[int] = 3
__snake_case : str = floats_tensor((batch_size, num_channels) + sizes).to(__a)
return {"sample": image}
@property
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
return (3, 3_2, 3_2)
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
return (3, 3_2, 3_2)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[Any] = {
'block_out_channels': [3_2, 6_4],
'in_channels': 3,
'out_channels': 3,
'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'],
'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'],
'latent_channels': 3,
}
__snake_case : List[Any] = self.dummy_input
return init_dict, inputs_dict
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case ,__snake_case : List[Any] = VQModel.from_pretrained('fusing/vqgan-dummy' , output_loading_info=__a)
self.assertIsNotNone(__a)
self.assertEqual(len(loading_info['missing_keys']) , 0)
model.to(__a)
__snake_case : Any = model(**self.dummy_input)
assert image is not None, "Make sure output is not None"
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : Union[str, Any] = VQModel.from_pretrained('fusing/vqgan-dummy')
model.to(__a).eval()
torch.manual_seed(0)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(0)
__snake_case : Tuple = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size)
__snake_case : Optional[int] = image.to(__a)
with torch.no_grad():
__snake_case : List[Any] = model(__a).sample
__snake_case : int = output[0, -1, -3:, -3:].flatten().cpu()
# fmt: off
__snake_case : int = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143])
# fmt: on
self.assertTrue(torch.allclose(__a , __a , atol=1E-3)) | 61 | 0 |
'''simple docstring'''
import warnings
from ...utils import logging
from .image_processing_glpn import GLPNImageProcessor
__A = logging.get_logger(__name__)
class a_ ( lowerCAmelCase__ ):
def __init__(self , *__a , **__a) -> None:
"""simple docstring"""
warnings.warn(
'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'
' use GLPNImageProcessor instead.' , _lowerCamelCase , )
super().__init__(*_lowerCamelCase , **_lowerCamelCase) | 712 |
'''simple docstring'''
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
__A = logging.getLogger(__name__)
@dataclass
class a_ :
_snake_case = field(
metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} )
_snake_case = field(
default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} )
_snake_case = 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.
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , )
@dataclass
class a_ :
_snake_case = field(
metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , )
_snake_case = field(
default=128 , metadata={
"""help""": (
"""The maximum total input sequence length after tokenization. Sequences longer """
"""than this will be truncated, sequences shorter will be padded."""
)
} , )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} )
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
# 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.
__snake_case : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
__snake_case ,__snake_case ,__snake_case : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
__snake_case ,__snake_case ,__snake_case : int = 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.' )
__snake_case : List[str] = import_module('tasks' )
try:
__snake_case : Any = getattr(A , model_args.task_type )
__snake_case : TokenClassificationTask = 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' , A )
# Set seed
set_seed(training_args.seed )
# Prepare CONLL-2003 task
__snake_case : Optional[Any] = token_classification_task.get_labels(data_args.labels )
__snake_case : Dict[int, str] = dict(enumerate(A ) )
__snake_case : Optional[Any] = len(A )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
__snake_case : Any = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=A , idalabel=A , labelaid={label: i for i, label in enumerate(A )} , cache_dir=model_args.cache_dir , )
__snake_case : List[str] = 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 , )
__snake_case : Optional[int] = AutoModelForTokenClassification.from_pretrained(
model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=A , cache_dir=model_args.cache_dir , )
# Get datasets
__snake_case : List[Any] = (
TokenClassificationDataset(
token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , 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
)
__snake_case : int = (
TokenClassificationDataset(
token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , 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(A : np.ndarray , A : np.ndarray ) -> Tuple[List[int], List[int]]:
__snake_case : str = np.argmax(A , axis=2 )
__snake_case ,__snake_case : int = preds.shape
__snake_case : Dict = [[] for _ in range(A )]
__snake_case : Union[str, Any] = [[] for _ in range(A )]
for i in range(A ):
for j in range(A ):
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(A : EvalPrediction ) -> Dict:
__snake_case ,__snake_case : Any = align_predictions(p.predictions , p.label_ids )
return {
"accuracy_score": accuracy_score(A , A ),
"precision": precision_score(A , A ),
"recall": recall_score(A , A ),
"f1": fa_score(A , A ),
}
# Data collator
__snake_case : Optional[int] = DataCollatorWithPadding(A , pad_to_multiple_of=8 ) if training_args.fpaa else None
# Initialize our Trainer
__snake_case : Optional[Any] = Trainer(
model=A , args=A , train_dataset=A , eval_dataset=A , compute_metrics=A , data_collator=A , )
# 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
__snake_case : List[Any] = {}
if training_args.do_eval:
logger.info('*** Evaluate ***' )
__snake_case : List[str] = trainer.evaluate()
__snake_case : Tuple = os.path.join(training_args.output_dir , 'eval_results.txt' )
if trainer.is_world_process_zero():
with open(A , 'w' ) as writer:
logger.info('***** Eval results *****' )
for key, value in result.items():
logger.info(' %s = %s' , A , A )
writer.write('%s = %s\n' % (key, value) )
results.update(A )
# Predict
if training_args.do_predict:
__snake_case : str = TokenClassificationDataset(
token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , )
__snake_case ,__snake_case ,__snake_case : str = trainer.predict(A )
__snake_case ,__snake_case : List[str] = align_predictions(A , A )
__snake_case : Optional[int] = os.path.join(training_args.output_dir , 'test_results.txt' )
if trainer.is_world_process_zero():
with open(A , 'w' ) as writer:
for key, value in metrics.items():
logger.info(' %s = %s' , A , A )
writer.write('%s = %s\n' % (key, value) )
# Save predictions
__snake_case : List[str] = os.path.join(training_args.output_dir , 'test_predictions.txt' )
if trainer.is_world_process_zero():
with open(A , 'w' ) as writer:
with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f:
token_classification_task.write_predictions_to_file(A , A , A )
return results
def _SCREAMING_SNAKE_CASE ( A : int ) -> Any:
"""simple docstring"""
# For xla_spawn (TPUs)
main()
if __name__ == "__main__":
main() | 61 | 0 |
'''simple docstring'''
import requests
from bsa import BeautifulSoup
def _SCREAMING_SNAKE_CASE ( A : str = "AAPL" ) -> str:
"""simple docstring"""
__snake_case : Dict = F"""https://in.finance.yahoo.com/quote/{symbol}?s={symbol}"""
__snake_case : int = BeautifulSoup(requests.get(__snake_case ).text , 'html.parser' )
__snake_case : int = "My(6px) Pos(r) smartphone_Mt(6px)"
return soup.find('div' , class_=class_ ).find('span' ).text
if __name__ == "__main__":
for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split():
print(f'''Current {symbol:<4} stock price is {stock_price(symbol):>8}''') | 713 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : list ) -> list:
"""simple docstring"""
__snake_case : Tuple = False
while is_sorted is False: # Until all the indices are traversed keep looping
__snake_case : Optional[Any] = True
for i in range(0 , len(A ) - 1 , 2 ): # iterating over all even indices
if input_list[i] > input_list[i + 1]:
__snake_case ,__snake_case : int = input_list[i + 1], input_list[i]
# swapping if elements not in order
__snake_case : List[Any] = False
for i in range(1 , len(A ) - 1 , 2 ): # iterating over all odd indices
if input_list[i] > input_list[i + 1]:
__snake_case ,__snake_case : Tuple = input_list[i + 1], input_list[i]
# swapping if elements not in order
__snake_case : Any = False
return input_list
if __name__ == "__main__":
print('''Enter list to be sorted''')
__A = [int(x) for x in input().split()]
# inputing elements of the list in one line
__A = odd_even_sort(input_list)
print('''The sorted list is''')
print(sorted_list) | 61 | 0 |
'''simple docstring'''
import json
import os
import shutil
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError
from transformers import AutoConfig, BertConfig, GPTaConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
sys.path.append(str(Path(__file__).parent.parent / '''utils'''))
from test_module.custom_configuration import CustomConfig # noqa E402
__A = {
'''return_dict''': False,
'''output_hidden_states''': True,
'''output_attentions''': True,
'''torchscript''': True,
'''torch_dtype''': '''float16''',
'''use_bfloat16''': True,
'''tf_legacy_loss''': True,
'''pruned_heads''': {'''a''': 1},
'''tie_word_embeddings''': False,
'''is_decoder''': True,
'''cross_attention_hidden_size''': 1_2_8,
'''add_cross_attention''': True,
'''tie_encoder_decoder''': True,
'''max_length''': 5_0,
'''min_length''': 3,
'''do_sample''': True,
'''early_stopping''': True,
'''num_beams''': 3,
'''num_beam_groups''': 3,
'''diversity_penalty''': 0.5,
'''temperature''': 2.0,
'''top_k''': 1_0,
'''top_p''': 0.7,
'''typical_p''': 0.2,
'''repetition_penalty''': 0.8,
'''length_penalty''': 0.8,
'''no_repeat_ngram_size''': 5,
'''encoder_no_repeat_ngram_size''': 5,
'''bad_words_ids''': [1, 2, 3],
'''num_return_sequences''': 3,
'''chunk_size_feed_forward''': 5,
'''output_scores''': True,
'''return_dict_in_generate''': True,
'''forced_bos_token_id''': 2,
'''forced_eos_token_id''': 3,
'''remove_invalid_values''': True,
'''architectures''': ['''BertModel'''],
'''finetuning_task''': '''translation''',
'''id2label''': {0: '''label'''},
'''label2id''': {'''label''': '''0'''},
'''tokenizer_class''': '''BertTokenizerFast''',
'''prefix''': '''prefix''',
'''bos_token_id''': 6,
'''pad_token_id''': 7,
'''eos_token_id''': 8,
'''sep_token_id''': 9,
'''decoder_start_token_id''': 1_0,
'''exponential_decay_length_penalty''': (5, 1.01),
'''suppress_tokens''': [0, 1],
'''begin_suppress_tokens''': 2,
'''task_specific_params''': {'''translation''': '''some_params'''},
'''problem_type''': '''regression''',
}
@is_staging_test
class a_ ( unittest.TestCase ):
@classmethod
def SCREAMING_SNAKE_CASE__ (cls) -> Optional[Any]:
"""simple docstring"""
__snake_case : Optional[Any] = TOKEN
HfFolder.save_token(__A)
@classmethod
def SCREAMING_SNAKE_CASE__ (cls) -> List[str]:
"""simple docstring"""
try:
delete_repo(token=cls._token , repo_id='test-config')
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id='valid_org/test-config-org')
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id='test-dynamic-config')
except HTTPError:
pass
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
__snake_case : Dict = BertConfig(
vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7)
config.push_to_hub('test-config' , use_auth_token=self._token)
__snake_case : Dict = BertConfig.from_pretrained(F"""{USER}/test-config""")
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(__A , getattr(__A , __A))
# Reset repo
delete_repo(token=self._token , repo_id='test-config')
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(__A , repo_id='test-config' , push_to_hub=__A , use_auth_token=self._token)
__snake_case : List[str] = BertConfig.from_pretrained(F"""{USER}/test-config""")
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(__A , getattr(__A , __A))
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Optional[int] = BertConfig(
vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7)
config.push_to_hub('valid_org/test-config-org' , use_auth_token=self._token)
__snake_case : Any = BertConfig.from_pretrained('valid_org/test-config-org')
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(__A , getattr(__A , __A))
# Reset repo
delete_repo(token=self._token , repo_id='valid_org/test-config-org')
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
__A , repo_id='valid_org/test-config-org' , push_to_hub=__A , use_auth_token=self._token)
__snake_case : Tuple = BertConfig.from_pretrained('valid_org/test-config-org')
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(__A , getattr(__A , __A))
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
CustomConfig.register_for_auto_class()
__snake_case : Any = CustomConfig(attribute=4_2)
config.push_to_hub('test-dynamic-config' , use_auth_token=self._token)
# This has added the proper auto_map field to the config
self.assertDictEqual(config.auto_map , {'AutoConfig': 'custom_configuration.CustomConfig'})
__snake_case : Optional[Any] = AutoConfig.from_pretrained(F"""{USER}/test-dynamic-config""" , trust_remote_code=__A)
# Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module
self.assertEqual(new_config.__class__.__name__ , 'CustomConfig')
self.assertEqual(new_config.attribute , 4_2)
class a_ ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : Union[str, Any] = GPTaConfig()
# attempt to modify each of int/float/bool/str config records and verify they were updated
__snake_case : Tuple = c.n_embd + 1 # int
__snake_case : List[Any] = c.resid_pdrop + 1.0 # float
__snake_case : Any = not c.scale_attn_weights # bool
__snake_case : Dict = c.summary_type + 'foo' # str
c.update_from_string(
F"""n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}""")
self.assertEqual(__A , c.n_embd , 'mismatch for key: n_embd')
self.assertEqual(__A , c.resid_pdrop , 'mismatch for key: resid_pdrop')
self.assertEqual(__A , c.scale_attn_weights , 'mismatch for key: scale_attn_weights')
self.assertEqual(__A , c.summary_type , 'mismatch for key: summary_type')
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
__snake_case : List[str] = PretrainedConfig()
__snake_case : Optional[int] = [key for key in base_config.__dict__ if key not in config_common_kwargs]
# If this part of the test fails, you have arguments to addin config_common_kwargs above.
self.assertListEqual(
__A , ['is_encoder_decoder', '_name_or_path', '_commit_hash', 'transformers_version'])
__snake_case : Tuple = [key for key, value in config_common_kwargs.items() if value == getattr(__A , __A)]
if len(__A) > 0:
raise ValueError(
'The following keys are set with the default values in'
' `test_configuration_common.config_common_kwargs` pick another value for them:'
F""" {", ".join(__A)}.""")
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
with self.assertRaises(__A):
# config is in subfolder, the following should not work without specifying the subfolder
__snake_case : List[Any] = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert-subfolder')
__snake_case : Tuple = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert-subfolder' , subfolder='bert')
self.assertIsNotNone(__A)
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
__snake_case : List[Any] = mock.Mock()
__snake_case : Dict = 5_0_0
__snake_case : Tuple = {}
__snake_case : int = HTTPError
__snake_case : str = {}
# Download this model to make sure it's in the cache.
__snake_case : int = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert')
# Under the mock environment we get a 500 error when trying to reach the model.
with mock.patch('requests.Session.request' , return_value=__A) as mock_head:
__snake_case : Union[str, Any] = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert')
# This check we did call the fake head request
mock_head.assert_called()
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : List[Any] = BertConfig.from_pretrained(
'https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json')
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : Union[str, Any] = AutoConfig.from_pretrained('bert-base-cased')
__snake_case : Union[str, Any] = ['config.4.0.0.json']
with tempfile.TemporaryDirectory() as tmp_dir:
configuration.save_pretrained(__A)
__snake_case : List[str] = 2
json.dump(configuration.to_dict() , open(os.path.join(__A , 'config.4.0.0.json') , 'w'))
# This should pick the new configuration file as the version of Transformers is > 4.0.0
__snake_case : Tuple = AutoConfig.from_pretrained(__A)
self.assertEqual(new_configuration.hidden_size , 2)
# Will need to be adjusted if we reach v42 and this test is still here.
# Should pick the old configuration file as the version of Transformers is < 4.42.0
__snake_case : Optional[int] = ['config.42.0.0.json']
__snake_case : Union[str, Any] = 7_6_8
configuration.save_pretrained(__A)
shutil.move(os.path.join(__A , 'config.4.0.0.json') , os.path.join(__A , 'config.42.0.0.json'))
__snake_case : Union[str, Any] = AutoConfig.from_pretrained(__A)
self.assertEqual(new_configuration.hidden_size , 7_6_8)
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : Optional[Any] = 'hf-internal-testing/test-two-configs'
import transformers as new_transformers
__snake_case : Dict = 'v4.0.0'
__snake_case ,__snake_case : List[Any] = new_transformers.models.auto.AutoConfig.from_pretrained(
__A , return_unused_kwargs=__A)
self.assertEqual(new_configuration.hidden_size , 2)
# This checks `_configuration_file` ia not kept in the kwargs by mistake.
self.assertDictEqual(__A , {})
# Testing an older version by monkey-patching the version in the module it's used.
import transformers as old_transformers
__snake_case : int = 'v3.0.0'
__snake_case : str = old_transformers.models.auto.AutoConfig.from_pretrained(__A)
self.assertEqual(old_configuration.hidden_size , 7_6_8) | 714 |
'''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 _SCREAMING_SNAKE_CASE ( A : int , A : str , A : LevitConfig , A : Path , A : bool = True ) -> Dict:
"""simple docstring"""
print(F"""Converting {name}...""" )
with torch.no_grad():
if hidden_sizes == 1_28:
if name[-1] == "S":
__snake_case : Optional[int] = timm.create_model('levit_128s' , pretrained=A )
else:
__snake_case : Tuple = timm.create_model('levit_128' , pretrained=A )
if hidden_sizes == 1_92:
__snake_case : int = timm.create_model('levit_192' , pretrained=A )
if hidden_sizes == 2_56:
__snake_case : List[Any] = timm.create_model('levit_256' , pretrained=A )
if hidden_sizes == 3_84:
__snake_case : int = timm.create_model('levit_384' , pretrained=A )
from_model.eval()
__snake_case : str = LevitForImageClassificationWithTeacher(A ).eval()
__snake_case : int = OrderedDict()
__snake_case : Optional[Any] = from_model.state_dict()
__snake_case : Tuple = list(from_model.state_dict().keys() )
__snake_case : List[str] = list(our_model.state_dict().keys() )
print(len(A ) , len(A ) )
for i in range(len(A ) ):
__snake_case : Optional[int] = weights[og_keys[i]]
our_model.load_state_dict(A )
__snake_case : Tuple = torch.randn((2, 3, 2_24, 2_24) )
__snake_case : Union[str, Any] = from_model(A )
__snake_case : List[str] = our_model(A ).logits
assert torch.allclose(A , A ), "The model logits don't match the original one."
__snake_case : int = name
print(A )
if push_to_hub:
our_model.save_pretrained(save_directory / checkpoint_name )
__snake_case : int = LevitImageProcessor()
image_processor.save_pretrained(save_directory / checkpoint_name )
print(F"""Pushed {checkpoint_name}""" )
def _SCREAMING_SNAKE_CASE ( A : Path , A : str = None , A : bool = True ) -> List[Any]:
"""simple docstring"""
__snake_case : Optional[Any] = 'imagenet-1k-id2label.json'
__snake_case : Tuple = 10_00
__snake_case : Dict = (1, num_labels)
__snake_case : List[str] = 'huggingface/label-files'
__snake_case : Any = num_labels
__snake_case : str = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) )
__snake_case : Any = {int(A ): v for k, v in idalabel.items()}
__snake_case : int = idalabel
__snake_case : Union[str, Any] = {v: k for k, v in idalabel.items()}
__snake_case : Optional[int] = partial(A , num_labels=A , idalabel=A , labelaid=A )
__snake_case : Dict = {
'levit-128S': 1_28,
'levit-128': 1_28,
'levit-192': 1_92,
'levit-256': 2_56,
'levit-384': 3_84,
}
__snake_case : Union[str, Any] = {
'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) | 61 | 0 |
'''simple docstring'''
import json
import os
import tempfile
import unittest
import numpy as np
from datasets import load_dataset
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
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import ImageGPTImageProcessor
class a_ ( unittest.TestCase ):
def __init__(self , __a , __a=7 , __a=3 , __a=1_8 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , ) -> List[Any]:
"""simple docstring"""
__snake_case : Tuple = size if size is not None else {'height': 1_8, 'width': 1_8}
__snake_case : Dict = parent
__snake_case : Union[str, Any] = batch_size
__snake_case : int = num_channels
__snake_case : int = image_size
__snake_case : Optional[Any] = min_resolution
__snake_case : Tuple = max_resolution
__snake_case : Dict = do_resize
__snake_case : str = size
__snake_case : List[Any] = do_normalize
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return {
# here we create 2 clusters for the sake of simplicity
"clusters": np.asarray(
[
[0.8_866_443_634_033_203, 0.6_618_829_369_544_983, 0.3_891_746_401_786_804],
[-0.6_042_559_146_881_104, -0.02_295_008_860_528_469, 0.5_423_797_369_003_296],
]),
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
}
@require_torch
@require_vision
class a_ ( UpperCamelCase__ , unittest.TestCase ):
_snake_case = ImageGPTImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case : List[str] = ImageGPTImageProcessingTester(self)
@property
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__A , 'clusters'))
self.assertTrue(hasattr(__A , 'do_resize'))
self.assertTrue(hasattr(__A , 'size'))
self.assertTrue(hasattr(__A , 'do_normalize'))
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'height': 1_8, 'width': 1_8})
__snake_case : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2)
self.assertEqual(image_processor.size , {'height': 4_2, 'width': 4_2})
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
__snake_case : Dict = self.image_processing_class(**self.image_processor_dict)
__snake_case : Any = json.loads(image_processor.to_json_string())
for key, value in self.image_processor_dict.items():
if key == "clusters":
self.assertTrue(np.array_equal(__A , obj[key]))
else:
self.assertEqual(obj[key] , __A)
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : List[str] = self.image_processing_class(**self.image_processor_dict)
with tempfile.TemporaryDirectory() as tmpdirname:
__snake_case : Any = os.path.join(__A , 'image_processor.json')
image_processor_first.to_json_file(__A)
__snake_case : Any = self.image_processing_class.from_json_file(__A).to_dict()
__snake_case : Optional[Any] = image_processor_first.to_dict()
for key, value in image_processor_first.items():
if key == "clusters":
self.assertTrue(np.array_equal(__A , image_processor_second[key]))
else:
self.assertEqual(image_processor_first[key] , __A)
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Dict = self.image_processing_class(**self.image_processor_dict)
with tempfile.TemporaryDirectory() as tmpdirname:
image_processor_first.save_pretrained(__A)
__snake_case : int = self.image_processing_class.from_pretrained(__A).to_dict()
__snake_case : List[str] = image_processor_first.to_dict()
for key, value in image_processor_first.items():
if key == "clusters":
self.assertTrue(np.array_equal(__A , image_processor_second[key]))
else:
self.assertEqual(image_processor_first[key] , __A)
@unittest.skip('ImageGPT requires clusters at initialization')
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
pass
def _SCREAMING_SNAKE_CASE ( ) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[int] = load_dataset('hf-internal-testing/fixtures_image_utils' , split='test' )
__snake_case : str = Image.open(dataset[4]['file'] )
__snake_case : List[str] = Image.open(dataset[5]['file'] )
__snake_case : Union[str, Any] = [imagea, imagea]
return images
@require_vision
@require_torch
class a_ ( unittest.TestCase ):
@slow
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Any = ImageGPTImageProcessor.from_pretrained('openai/imagegpt-small')
__snake_case : Optional[int] = prepare_images()
# test non-batched
__snake_case : List[Any] = image_processing(images[0] , return_tensors='pt')
self.assertIsInstance(encoding.input_ids , torch.LongTensor)
self.assertEqual(encoding.input_ids.shape , (1, 1_0_2_4))
__snake_case : Dict = [3_0_6, 1_9_1, 1_9_1]
self.assertEqual(encoding.input_ids[0, :3].tolist() , __A)
# test batched
__snake_case : Optional[int] = image_processing(__A , return_tensors='pt')
self.assertIsInstance(encoding.input_ids , torch.LongTensor)
self.assertEqual(encoding.input_ids.shape , (2, 1_0_2_4))
__snake_case : Dict = [3_0_3, 1_3, 1_3]
self.assertEqual(encoding.input_ids[1, -3:].tolist() , __A) | 715 |
'''simple docstring'''
import inspect
import unittest
from typing import List
import numpy as np
from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFEfficientFormerForImageClassification,
TFEfficientFormerForImageClassificationWithTeacher,
TFEfficientFormerModel,
)
from transformers.models.efficientformer.modeling_tf_efficientformer import (
TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_vision_available():
from PIL import Image
from transformers import EfficientFormerImageProcessor
class a_ :
def __init__(self , __a , __a = 1_3 , __a = 6_4 , __a = 2 , __a = 3 , __a = 3 , __a = True , __a = True , __a = 1_2_8 , __a=[1_6, 3_2, 6_4, 1_2_8] , __a = 7 , __a = 4 , __a = 3_7 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 1_0 , __a = 0.02 , __a = 2 , __a = 1 , __a = 1_2_8 , __a = [2, 2, 2, 2] , __a = 2 , __a = 2 , ) -> str:
"""simple docstring"""
__snake_case : Optional[Any] = parent
__snake_case : Optional[int] = batch_size
__snake_case : Optional[Any] = image_size
__snake_case : Optional[int] = patch_size
__snake_case : Optional[Any] = num_channels
__snake_case : Optional[Any] = is_training
__snake_case : Tuple = use_labels
__snake_case : Optional[int] = hidden_size
__snake_case : Any = num_hidden_layers
__snake_case : List[str] = num_attention_heads
__snake_case : Tuple = intermediate_size
__snake_case : List[str] = hidden_act
__snake_case : Dict = hidden_dropout_prob
__snake_case : Any = attention_probs_dropout_prob
__snake_case : Dict = type_sequence_label_size
__snake_case : str = initializer_range
__snake_case : int = encoder_stride
__snake_case : List[str] = num_attention_outputs
__snake_case : Optional[Any] = embed_dim
__snake_case : Optional[Any] = embed_dim + 1
__snake_case : List[str] = resolution
__snake_case : Optional[int] = depths
__snake_case : List[Any] = hidden_sizes
__snake_case : List[str] = dim
__snake_case : Union[str, Any] = mlp_expansion_ratio
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
__snake_case : List[str] = None
if self.use_labels:
__snake_case : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size)
__snake_case : Tuple = self.get_config()
return config, pixel_values, labels
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return EfficientFormerConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , )
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Optional[int]:
"""simple docstring"""
__snake_case : Union[str, Any] = TFEfficientFormerModel(config=__a)
__snake_case : int = model(__a , training=__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple:
"""simple docstring"""
__snake_case : Dict = self.type_sequence_label_size
__snake_case : List[Any] = TFEfficientFormerForImageClassification(__a)
__snake_case : Optional[int] = model(__a , labels=__a , training=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size))
# test greyscale images
__snake_case : List[Any] = 1
__snake_case : List[Any] = TFEfficientFormerForImageClassification(__a)
__snake_case : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
__snake_case : str = model(__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size))
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : Union[str, Any] = self.prepare_config_and_inputs()
__snake_case ,__snake_case ,__snake_case : Union[str, Any] = config_and_inputs
__snake_case : Optional[int] = {'pixel_values': pixel_values}
return config, inputs_dict
@require_tf
class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ):
_snake_case = (
(
TFEfficientFormerModel,
TFEfficientFormerForImageClassificationWithTeacher,
TFEfficientFormerForImageClassification,
)
if is_tf_available()
else ()
)
_snake_case = (
{
"""feature-extraction""": TFEfficientFormerModel,
"""image-classification""": (
TFEfficientFormerForImageClassification,
TFEfficientFormerForImageClassificationWithTeacher,
),
}
if is_tf_available()
else {}
)
_snake_case = False
_snake_case = False
_snake_case = False
_snake_case = False
_snake_case = False
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Dict = TFEfficientFormerModelTester(self)
__snake_case : List[Any] = ConfigTester(
self , config_class=__a , has_text_modality=__a , hidden_size=3_7)
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
self.config_tester.run_common_tests()
@unittest.skip(reason='EfficientFormer does not use inputs_embeds')
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
pass
@unittest.skip(reason='EfficientFormer does not support input and output embeddings')
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case ,__snake_case : str = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case : Optional[int] = model_class(__a)
__snake_case : Union[str, Any] = inspect.signature(model.call)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__snake_case : Optional[int] = [*signature.parameters.keys()]
__snake_case : Dict = ['pixel_values']
self.assertListEqual(arg_names[:1] , __a)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
def check_hidden_states_output(__a , __a , __a):
__snake_case : str = model_class(__a)
__snake_case : List[Any] = model(**self._prepare_for_class(__a , __a) , training=__a)
__snake_case : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
__snake_case : Optional[Any] = getattr(
self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1)
self.assertEqual(len(__a) , __a)
if hasattr(self.model_tester , 'encoder_seq_length'):
__snake_case : List[Any] = self.model_tester.encoder_seq_length
if hasattr(self.model_tester , 'chunk_length') and self.model_tester.chunk_length > 1:
__snake_case : str = seq_length * self.model_tester.chunk_length
else:
__snake_case : Optional[int] = self.model_tester.seq_length
self.assertListEqual(
list(hidden_states[-1].shape[-2:]) , [seq_length, self.model_tester.hidden_size] , )
if config.is_encoder_decoder:
__snake_case : List[Any] = outputs.decoder_hidden_states
self.asseretIsInstance(__a , (list, tuple))
self.assertEqual(len(__a) , __a)
__snake_case : List[str] = getattr(self.model_tester , 'seq_length' , __a)
__snake_case : Tuple = getattr(self.model_tester , 'decoder_seq_length' , __a)
self.assertListEqual(
list(hidden_states[-1].shape[-2:]) , [decoder_seq_length, self.model_tester.hidden_size] , )
__snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case : List[str] = True
check_hidden_states_output(__a , __a , __a)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__snake_case : str = True
check_hidden_states_output(__a , __a , __a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a=False) -> int:
"""simple docstring"""
__snake_case : Optional[int] = super()._prepare_for_class(__a , __a , return_labels=__a)
if return_labels:
if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
del inputs_dict["labels"]
return inputs_dict
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
@unittest.skip(reason='EfficientFormer does not implement masked image modeling yet')
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*__a)
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*__a)
@slow
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__snake_case : Any = TFEfficientFormerModel.from_pretrained(__a)
self.assertIsNotNone(__a)
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case : Tuple = True
__snake_case : Optional[Any] = getattr(self.model_tester , 'seq_length' , __a)
__snake_case : List[Any] = getattr(self.model_tester , 'encoder_seq_length' , __a)
__snake_case : Tuple = getattr(self.model_tester , 'key_length' , __a)
__snake_case : Optional[Any] = getattr(self.model_tester , 'chunk_length' , __a)
if chunk_length is not None and hasattr(self.model_tester , 'num_hashes'):
__snake_case : str = encoder_seq_length * self.model_tester.num_hashes
for model_class in self.all_model_classes:
__snake_case : Optional[Any] = True
__snake_case : Dict = False
__snake_case : Optional[int] = True
__snake_case : Dict = model_class(__a)
__snake_case : Tuple = model(**self._prepare_for_class(__a , __a) , training=__a)
__snake_case : Union[str, Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(__a) , self.model_tester.num_attention_outputs)
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
__snake_case : Dict = True
__snake_case : str = model_class(__a)
__snake_case : str = model(**self._prepare_for_class(__a , __a) , training=__a)
__snake_case : Tuple = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(__a) , self.model_tester.num_attention_outputs)
if chunk_length is not None:
self.assertListEqual(
list(attentions[0].shape[-4:]) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , )
else:
self.assertListEqual(
list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , )
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case ,__snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
# Prepare our model
__snake_case : Tuple = model_class(__a)
# These are maximally general inputs for the model, with multiple None dimensions
# Hopefully this will catch any conditionals that fail for flexible shapes
__snake_case : Optional[Any] = {
key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=__a)
for key, val in model.input_signature.items()
if key in model.dummy_inputs
}
__snake_case : Tuple = model(__a)
self.assertTrue(outputs_dict is not None)
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
__snake_case : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_tf
@require_vision
class a_ ( unittest.TestCase ):
@cached_property
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return (
EfficientFormerImageProcessor.from_pretrained('snap-research/efficientformer-l1-300')
if is_vision_available()
else None
)
@slow
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case : List[str] = TFEfficientFormerForImageClassification.from_pretrained('snap-research/efficientformer-l1-300')
__snake_case : Optional[int] = self.default_image_processor
__snake_case : List[Any] = prepare_img()
__snake_case : List[Any] = image_processor(images=__a , return_tensors='tf')
# forward pass
__snake_case : List[str] = model(**__a , training=__a)
# verify the logits
__snake_case : str = tf.TensorShape((1, 1_0_0_0))
self.assertEqual(outputs.logits.shape , __a)
__snake_case : Any = tf.constant([-0.0_555, 0.4_825, -0.0_852])
self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4))
@slow
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[Any] = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
'snap-research/efficientformer-l1-300')
__snake_case : List[Any] = self.default_image_processor
__snake_case : Union[str, Any] = prepare_img()
__snake_case : List[Any] = image_processor(images=__a , return_tensors='tf')
# forward pass
__snake_case : Optional[int] = model(**__a , training=__a)
# verify the logits
__snake_case : Optional[int] = tf.TensorShape((1, 1_0_0_0))
self.assertEqual(outputs.logits.shape , __a)
__snake_case : List[str] = tf.constant([-0.1_312, 0.4_353, -1.0_499])
self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4)) | 61 | 0 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : Any ) -> Any:
"""simple docstring"""
__snake_case : int = ''
for ch in key:
if ch == " " or ch not in key_no_dups and ch.isalpha():
key_no_dups += ch
return key_no_dups
def _SCREAMING_SNAKE_CASE ( A : List[str] ) -> Tuple:
"""simple docstring"""
__snake_case : int = [chr(i + 65 ) for i in range(26 )]
# Remove duplicate characters from key
__snake_case : List[str] = remove_duplicates(key.upper() )
__snake_case : Any = len(_UpperCAmelCase )
# First fill cipher with key characters
__snake_case : List[Any] = {alphabet[i]: char for i, char in enumerate(_UpperCAmelCase )}
# Then map remaining characters in alphabet to
# the alphabet from the beginning
for i in range(len(_UpperCAmelCase ) , 26 ):
__snake_case : Tuple = alphabet[i - offset]
# Ensure we are not mapping letters to letters previously mapped
while char in key:
offset -= 1
__snake_case : Optional[Any] = alphabet[i - offset]
__snake_case : Union[str, Any] = char
return cipher_alphabet
def _SCREAMING_SNAKE_CASE ( A : List[Any] , A : str ) -> Tuple:
"""simple docstring"""
return "".join(cipher_map.get(_UpperCAmelCase , _UpperCAmelCase ) for ch in message.upper() )
def _SCREAMING_SNAKE_CASE ( A : Union[str, Any] , A : List[Any] ) -> Union[str, Any]:
"""simple docstring"""
__snake_case : List[Any] = {v: k for k, v in cipher_map.items()}
return "".join(rev_cipher_map.get(_UpperCAmelCase , _UpperCAmelCase ) for ch in message.upper() )
def _SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]:
"""simple docstring"""
__snake_case : List[Any] = input('Enter message to encode or decode: ' ).strip()
__snake_case : Optional[Any] = input('Enter keyword: ' ).strip()
__snake_case : List[str] = input('Encipher or decipher? E/D:' ).strip()[0].lower()
try:
__snake_case : Any = {'e': encipher, 'd': decipher}[option]
except KeyError:
raise KeyError('invalid input option' )
__snake_case : Tuple = create_cipher_map(_UpperCAmelCase )
print(func(_UpperCAmelCase , _UpperCAmelCase ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main() | 716 |
'''simple docstring'''
__A = {str(digit): digit**5 for digit in range(1_0)}
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
return sum(DIGITS_FIFTH_POWER[digit] for digit in str(A ) )
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
return sum(
number
for number in range(10_00 , 1_00_00_00 )
if number == digits_fifth_powers_sum(A ) )
if __name__ == "__main__":
print(solution()) | 61 | 0 |
'''simple docstring'''
import argparse
from typing import List
import evaluate
import numpy as np
import torch
from datasets import DatasetDict, load_dataset
# New Code #
# We'll be using StratifiedKFold for this example
from sklearn.model_selection import StratifiedKFold
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 how to perform Cross Validation,
# 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
#
########################################################################
__A = 1_6
__A = 3_2
def _SCREAMING_SNAKE_CASE ( A : Optional[int] , A : List[Any] , A : str , A : List[Any] , A : Optional[Any] = 16 ) -> Dict:
"""simple docstring"""
__snake_case : Optional[Any] = AutoTokenizer.from_pretrained('bert-base-cased' )
__snake_case : List[Any] = DatasetDict(
{
'train': dataset['train'].select(_lowercase ),
'validation': dataset['train'].select(_lowercase ),
'test': dataset['validation'],
} )
def tokenize_function(A : List[str] ):
# max_length=None => use the model max length (it's actually the default)
__snake_case : Optional[int] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_lowercase , max_length=_lowercase )
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():
__snake_case : Optional[Any] = datasets.map(
_lowercase , batched=_lowercase , 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
__snake_case : Optional[int] = tokenized_datasets.rename_column('label' , 'labels' )
def collate_fn(A : int ):
# On TPU it's best to pad everything to the same length or training will be very slow.
__snake_case : Union[str, Any] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
__snake_case : str = 16
elif accelerator.mixed_precision != "no":
__snake_case : Optional[int] = 8
else:
__snake_case : List[str] = None
return tokenizer.pad(
_lowercase , padding='longest' , max_length=_lowercase , pad_to_multiple_of=_lowercase , return_tensors='pt' , )
# Instantiate dataloaders.
__snake_case : List[str] = DataLoader(
tokenized_datasets['train'] , shuffle=_lowercase , collate_fn=_lowercase , batch_size=_lowercase )
__snake_case : str = DataLoader(
tokenized_datasets['validation'] , shuffle=_lowercase , collate_fn=_lowercase , batch_size=_lowercase )
__snake_case : Union[str, Any] = DataLoader(
tokenized_datasets['test'] , shuffle=_lowercase , collate_fn=_lowercase , batch_size=_lowercase )
return train_dataloader, eval_dataloader, test_dataloader
def _SCREAMING_SNAKE_CASE ( A : Dict , A : Tuple ) -> Union[str, Any]:
"""simple docstring"""
__snake_case : Optional[Any] = []
# Download the dataset
__snake_case : int = load_dataset('glue' , 'mrpc' )
# Create our splits
__snake_case : Tuple = StratifiedKFold(n_splits=int(args.num_folds ) )
# Initialize accelerator
__snake_case : str = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
__snake_case : Dict = config['lr']
__snake_case : int = int(config['num_epochs'] )
__snake_case : Union[str, Any] = int(config['seed'] )
__snake_case : str = int(config['batch_size'] )
__snake_case : int = evaluate.load('glue' , 'mrpc' )
# If the batch size is too big we use gradient accumulation
__snake_case : Optional[Any] = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
__snake_case : Dict = batch_size // MAX_GPU_BATCH_SIZE
__snake_case : Optional[Any] = MAX_GPU_BATCH_SIZE
set_seed(_lowercase )
# New Code #
# Create our folds:
__snake_case : Any = kfold.split(np.zeros(datasets['train'].num_rows ) , datasets['train']['label'] )
__snake_case : str = []
# Iterate over them
for i, (train_idxs, valid_idxs) in enumerate(_lowercase ):
__snake_case ,__snake_case ,__snake_case : Any = get_fold_dataloaders(
_lowercase , _lowercase , _lowercase , _lowercase , )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
__snake_case : Tuple = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_lowercase )
# 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).
__snake_case : str = model.to(accelerator.device )
# Instantiate optimizer
__snake_case : str = AdamW(params=model.parameters() , lr=_lowercase )
# Instantiate scheduler
__snake_case : Optional[Any] = get_linear_schedule_with_warmup(
optimizer=_lowercase , num_warmup_steps=1_00 , num_training_steps=(len(_lowercase ) * 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.
__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case : List[str] = accelerator.prepare(
_lowercase , _lowercase , _lowercase , _lowercase , _lowercase )
# Now we train the model
for epoch in range(_lowercase ):
model.train()
for step, batch in enumerate(_lowercase ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
__snake_case : str = model(**_lowercase )
__snake_case : Any = outputs.loss
__snake_case : Union[str, Any] = loss / gradient_accumulation_steps
accelerator.backward(_lowercase )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(_lowercase ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
__snake_case : Tuple = model(**_lowercase )
__snake_case : Optional[Any] = outputs.logits.argmax(dim=-1 )
__snake_case ,__snake_case : List[str] = accelerator.gather_for_metrics((predictions, batch['labels']) )
metric.add_batch(
predictions=_lowercase , references=_lowercase , )
__snake_case : int = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(F"""epoch {epoch}:""" , _lowercase )
# New Code #
# We also run predictions on the test set at the very end
__snake_case : Optional[int] = []
for step, batch in enumerate(_lowercase ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
__snake_case : Optional[Any] = model(**_lowercase )
__snake_case : Tuple = outputs.logits
__snake_case ,__snake_case : Optional[int] = accelerator.gather_for_metrics((predictions, batch['labels']) )
fold_predictions.append(predictions.cpu() )
if i == 0:
# We need all of the test predictions
test_references.append(references.cpu() )
# Use accelerator.print to print only on the main process.
test_predictions.append(torch.cat(_lowercase , dim=0 ) )
# We now need to release all our memory and get rid of the current model, optimizer, etc
accelerator.free_memory()
# New Code #
# Finally we check the accuracy of our folded results:
__snake_case : Any = torch.cat(_lowercase , dim=0 )
__snake_case : Dict = torch.stack(_lowercase , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 )
__snake_case : str = metric.compute(predictions=_lowercase , references=_lowercase )
accelerator.print('Average test metrics from all folds:' , _lowercase )
def _SCREAMING_SNAKE_CASE ( ) -> List[Any]:
"""simple docstring"""
__snake_case : str = argparse.ArgumentParser(description='Simple example of training script.' )
parser.add_argument(
'--mixed_precision' , type=_lowercase , default=_lowercase , 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.' )
# New Code #
parser.add_argument('--num_folds' , type=_lowercase , default=3 , help='The number of splits to perform across the dataset' )
__snake_case : List[Any] = parser.parse_args()
__snake_case : List[Any] = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16}
training_function(_lowercase , _lowercase )
if __name__ == "__main__":
main() | 717 |
'''simple docstring'''
from __future__ import annotations
from collections import deque
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any
@dataclass
class a_ :
_snake_case = 42
_snake_case = None
_snake_case = None
def _SCREAMING_SNAKE_CASE ( ) -> Node | None:
"""simple docstring"""
__snake_case : str = Node(1 )
__snake_case : Tuple = Node(2 )
__snake_case : Optional[int] = Node(3 )
__snake_case : List[str] = Node(4 )
__snake_case : List[str] = Node(5 )
return tree
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return [root.data, *preorder(root.left ), *preorder(root.right )] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return postorder(root.left ) + postorder(root.right ) + [root.data] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return [*inorder(root.left ), root.data, *inorder(root.right )] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> int:
"""simple docstring"""
return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
if root is None:
return output
__snake_case : Optional[int] = deque([root] )
while process_queue:
__snake_case : List[str] = process_queue.popleft()
output.append(node.data )
if node.left:
process_queue.append(node.left )
if node.right:
process_queue.append(node.right )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
def populate_output(A : Node | None , A : int ) -> None:
if not root:
return
if level == 1:
output.append(root.data )
elif level > 1:
populate_output(root.left , level - 1 )
populate_output(root.right , level - 1 )
populate_output(A , A )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
def populate_output(A : Node | None , A : int ) -> None:
if root is None:
return
if level == 1:
output.append(root.data )
elif level > 1:
populate_output(root.right , level - 1 )
populate_output(root.left , level - 1 )
populate_output(A , A )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None] | list[Any]:
"""simple docstring"""
if root is None:
return []
__snake_case : list[Sequence[Node | None]] = []
__snake_case : List[Any] = 0
__snake_case : int = height(A )
for h in range(1 , height_tree + 1 ):
if not flag:
output.append(get_nodes_from_left_to_right(A , A ) )
__snake_case : int = 1
else:
output.append(get_nodes_from_right_to_left(A , A ) )
__snake_case : Tuple = 0
return output
def _SCREAMING_SNAKE_CASE ( ) -> None: # Main function for testing.
"""simple docstring"""
__snake_case : Optional[int] = make_tree()
print(F"""In-order Traversal: {inorder(A )}""" )
print(F"""Pre-order Traversal: {preorder(A )}""" )
print(F"""Post-order Traversal: {postorder(A )}""" , '\n' )
print(F"""Height of Tree: {height(A )}""" , '\n' )
print('Complete Level Order Traversal: ' )
print(level_order(A ) , '\n' )
print('Level-wise order Traversal: ' )
for level in range(1 , height(A ) + 1 ):
print(F"""Level {level}:""" , get_nodes_from_left_to_right(A , level=A ) )
print('\nZigZag order Traversal: ' )
print(zigzag(A ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main() | 61 | 0 |
'''simple docstring'''
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'''microsoft/git-base''': '''https://huggingface.co/microsoft/git-base/resolve/main/config.json''',
}
class a_ ( __snake_case ):
_snake_case = """git_vision_model"""
def __init__(self , __a=7_6_8 , __a=3_0_7_2 , __a=1_2 , __a=1_2 , __a=3 , __a=2_2_4 , __a=1_6 , __a="quick_gelu" , __a=1E-5 , __a=0.0 , __a=0.02 , **__a , ) -> Tuple:
"""simple docstring"""
super().__init__(**_lowercase)
__snake_case : str = hidden_size
__snake_case : Optional[int] = intermediate_size
__snake_case : Optional[int] = num_hidden_layers
__snake_case : str = num_attention_heads
__snake_case : str = num_channels
__snake_case : Any = patch_size
__snake_case : int = image_size
__snake_case : str = initializer_range
__snake_case : Any = attention_dropout
__snake_case : List[str] = layer_norm_eps
__snake_case : List[str] = hidden_act
@classmethod
def SCREAMING_SNAKE_CASE__ (cls , __a , **__a) -> List[Any]:
"""simple docstring"""
cls._set_token_in_kwargs(_lowercase)
__snake_case : int = cls.get_config_dict(_lowercase , **_lowercase)
# get the vision config dict if we are loading from GITConfig
if config_dict.get('model_type') == "git":
__snake_case : Union[str, Any] = 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(_lowercase , **_lowercase)
class a_ ( __snake_case ):
_snake_case = """git"""
def __init__(self , __a=None , __a=3_0_5_2_2 , __a=7_6_8 , __a=6 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.1 , __a=0.1 , __a=1_0_2_4 , __a=0.02 , __a=1E-12 , __a=0 , __a="absolute" , __a=True , __a=False , __a=1_0_1 , __a=1_0_2 , __a=None , **__a , ) -> Tuple:
"""simple docstring"""
super().__init__(bos_token_id=_lowercase , eos_token_id=_lowercase , pad_token_id=_lowercase , **_lowercase)
if vision_config is None:
__snake_case : Dict = {}
logger.info('vision_config is None. initializing the GitVisionConfig with default values.')
__snake_case : Union[str, Any] = GitVisionConfig(**_lowercase)
__snake_case : Tuple = vocab_size
__snake_case : Tuple = hidden_size
__snake_case : Optional[int] = num_hidden_layers
__snake_case : int = num_attention_heads
__snake_case : List[Any] = hidden_act
__snake_case : Optional[Any] = intermediate_size
__snake_case : Optional[Any] = hidden_dropout_prob
__snake_case : List[Any] = attention_probs_dropout_prob
__snake_case : Tuple = max_position_embeddings
__snake_case : int = initializer_range
__snake_case : Dict = layer_norm_eps
__snake_case : Dict = position_embedding_type
__snake_case : List[str] = use_cache
__snake_case : int = tie_word_embeddings
__snake_case : int = num_image_with_embedding
__snake_case : List[str] = bos_token_id
__snake_case : Union[str, Any] = eos_token_id
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Dict = copy.deepcopy(self.__dict__)
__snake_case : Optional[Any] = self.vision_config.to_dict()
__snake_case : Tuple = self.__class__.model_type
return output | 718 |
'''simple docstring'''
from __future__ import annotations
import math
import random
from collections.abc import Collection
from typing import overload
class a_ :
def __init__(self , __a = None) -> None:
"""simple docstring"""
if components is None:
__snake_case : List[str] = []
__snake_case : Optional[int] = list(__a)
def __len__(self) -> int:
"""simple docstring"""
return len(self.__components)
def __str__(self) -> str:
"""simple docstring"""
return "(" + ",".join(map(__a , self.__components)) + ")"
def __add__(self , __a) -> Vector:
"""simple docstring"""
__snake_case : Optional[Any] = len(self)
if size == len(__a):
__snake_case : Optional[int] = [self.__components[i] + other.component(__a) for i in range(__a)]
return Vector(__a)
else:
raise Exception('must have the same size')
def __sub__(self , __a) -> Vector:
"""simple docstring"""
__snake_case : Optional[Any] = len(self)
if size == len(__a):
__snake_case : Optional[int] = [self.__components[i] - other.component(__a) for i in range(__a)]
return Vector(__a)
else: # error case
raise Exception('must have the same size')
@overload
def __mul__(self , __a) -> Vector:
"""simple docstring"""
...
@overload
def __mul__(self , __a) -> float:
"""simple docstring"""
...
def __mul__(self , __a) -> float | Vector:
"""simple docstring"""
if isinstance(__a , (float, int)):
__snake_case : str = [c * other for c in self.__components]
return Vector(__a)
elif isinstance(__a , __a) and len(self) == len(__a):
__snake_case : List[Any] = len(self)
__snake_case : Dict = [self.__components[i] * other.component(__a) for i in range(__a)]
return sum(__a)
else: # error case
raise Exception('invalid operand!')
def SCREAMING_SNAKE_CASE__ (self) -> Vector:
"""simple docstring"""
return Vector(self.__components)
def SCREAMING_SNAKE_CASE__ (self , __a) -> float:
"""simple docstring"""
if isinstance(__a , __a) and -len(self.__components) <= i < len(self.__components):
return self.__components[i]
else:
raise Exception('index out of range')
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> None:
"""simple docstring"""
assert -len(self.__components) <= pos < len(self.__components)
__snake_case : int = value
def SCREAMING_SNAKE_CASE__ (self) -> float:
"""simple docstring"""
if len(self.__components) == 0:
raise Exception('Vector is empty')
__snake_case : Tuple = [c**2 for c in self.__components]
return math.sqrt(sum(__a))
def SCREAMING_SNAKE_CASE__ (self , __a , __a = False) -> float:
"""simple docstring"""
__snake_case : Tuple = self * other
__snake_case : Optional[int] = self.euclidean_length() * other.euclidean_length()
if deg:
return math.degrees(math.acos(num / den))
else:
return math.acos(num / den)
def _SCREAMING_SNAKE_CASE ( A : int ) -> Vector:
"""simple docstring"""
assert isinstance(A , A )
return Vector([0] * dimension )
def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> Vector:
"""simple docstring"""
assert isinstance(A , A ) and (isinstance(A , A ))
__snake_case : Any = [0] * dimension
__snake_case : int = 1
return Vector(A )
def _SCREAMING_SNAKE_CASE ( A : float , A : Vector , A : Vector ) -> Vector:
"""simple docstring"""
assert (
isinstance(A , A )
and isinstance(A , A )
and (isinstance(A , (int, float) ))
)
return x * scalar + y
def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int ) -> Vector:
"""simple docstring"""
random.seed(A )
__snake_case : List[Any] = [random.randint(A , A ) for _ in range(A )]
return Vector(A )
class a_ :
def __init__(self , __a , __a , __a) -> None:
"""simple docstring"""
__snake_case : Union[str, Any] = matrix
__snake_case : int = w
__snake_case : str = h
def __str__(self) -> str:
"""simple docstring"""
__snake_case : Dict = ''
for i in range(self.__height):
ans += "|"
for j in range(self.__width):
if j < self.__width - 1:
ans += str(self.__matrix[i][j]) + ","
else:
ans += str(self.__matrix[i][j]) + "|\n"
return ans
def __add__(self , __a) -> Matrix:
"""simple docstring"""
if self.__width == other.width() and self.__height == other.height():
__snake_case : Tuple = []
for i in range(self.__height):
__snake_case : List[Any] = [
self.__matrix[i][j] + other.component(__a , __a)
for j in range(self.__width)
]
matrix.append(__a)
return Matrix(__a , self.__width , self.__height)
else:
raise Exception('matrix must have the same dimension!')
def __sub__(self , __a) -> Matrix:
"""simple docstring"""
if self.__width == other.width() and self.__height == other.height():
__snake_case : str = []
for i in range(self.__height):
__snake_case : List[str] = [
self.__matrix[i][j] - other.component(__a , __a)
for j in range(self.__width)
]
matrix.append(__a)
return Matrix(__a , self.__width , self.__height)
else:
raise Exception('matrices must have the same dimension!')
@overload
def __mul__(self , __a) -> Matrix:
"""simple docstring"""
...
@overload
def __mul__(self , __a) -> Vector:
"""simple docstring"""
...
def __mul__(self , __a) -> Vector | Matrix:
"""simple docstring"""
if isinstance(__a , __a): # matrix-vector
if len(__a) == self.__width:
__snake_case : Tuple = zero_vector(self.__height)
for i in range(self.__height):
__snake_case : Union[str, Any] = [
self.__matrix[i][j] * other.component(__a)
for j in range(self.__width)
]
ans.change_component(__a , sum(__a))
return ans
else:
raise Exception(
'vector must have the same size as the '
'number of columns of the matrix!')
elif isinstance(__a , (int, float)): # matrix-scalar
__snake_case : str = [
[self.__matrix[i][j] * other for j in range(self.__width)]
for i in range(self.__height)
]
return Matrix(__a , self.__width , self.__height)
return None
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return self.__height
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return self.__width
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float:
"""simple docstring"""
if 0 <= x < self.__height and 0 <= y < self.__width:
return self.__matrix[x][y]
else:
raise Exception('change_component: indices out of bounds')
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> None:
"""simple docstring"""
if 0 <= x < self.__height and 0 <= y < self.__width:
__snake_case : List[Any] = value
else:
raise Exception('change_component: indices out of bounds')
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float:
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square')
__snake_case : List[Any] = self.__matrix[:x] + self.__matrix[x + 1 :]
for i in range(len(__a)):
__snake_case : Tuple = minor[i][:y] + minor[i][y + 1 :]
return Matrix(__a , self.__width - 1 , self.__height - 1).determinant()
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float:
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square')
if 0 <= x < self.__height and 0 <= y < self.__width:
return (-1) ** (x + y) * self.minor(__a , __a)
else:
raise Exception('Indices out of bounds')
def SCREAMING_SNAKE_CASE__ (self) -> float:
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square')
if self.__height < 1:
raise Exception('Matrix has no element')
elif self.__height == 1:
return self.__matrix[0][0]
elif self.__height == 2:
return (
self.__matrix[0][0] * self.__matrix[1][1]
- self.__matrix[0][1] * self.__matrix[1][0]
)
else:
__snake_case : Any = [
self.__matrix[0][y] * self.cofactor(0 , __a) for y in range(self.__width)
]
return sum(__a)
def _SCREAMING_SNAKE_CASE ( A : int ) -> Matrix:
"""simple docstring"""
__snake_case : list[list[float]] = [[0] * n for _ in range(A )]
return Matrix(A , A , A )
def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int , A : int ) -> Matrix:
"""simple docstring"""
random.seed(A )
__snake_case : list[list[float]] = [
[random.randint(A , A ) for _ in range(A )] for _ in range(A )
]
return Matrix(A , A , A ) | 61 | 0 |
'''simple docstring'''
from functools import lru_cache
@lru_cache
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
if num < 0:
raise ValueError('Number should not be negative.' )
return 1 if num in (0, 1) else num * factorial(num - 1 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 719 |
'''simple docstring'''
import contextlib
import importlib
import io
import unittest
import transformers
# Try to import everything from transformers to ensure every object can be loaded.
from transformers import * # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available
if is_torch_available():
from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification
if is_tf_available():
from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification
if is_flax_available():
from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification
__A = DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co
__A = '''main'''
# Default branch name
__A = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
__A = '''aaaaaaa'''
# This commit does not exist, so we should 404.
__A = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
__A = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''
@contextlib.contextmanager
def _SCREAMING_SNAKE_CASE ( ) -> List[Any]:
"""simple docstring"""
print('Welcome!' )
yield
print('Bye!' )
@contextlib.contextmanager
def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]:
"""simple docstring"""
print('Bonjour!' )
yield
print('Au revoir!' )
class a_ ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
assert transformers.__spec__ is not None
assert importlib.util.find_spec('transformers') is not None
class a_ ( unittest.TestCase ):
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> int:
"""simple docstring"""
with ContextManagers([]):
print('Transformers are awesome!')
# The print statement adds a new line at the end of the output
self.assertEqual(mock_stdout.getvalue() , 'Transformers are awesome!\n')
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]:
"""simple docstring"""
with ContextManagers([context_en()]):
print('Transformers are awesome!')
# The output should be wrapped with an English welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , 'Welcome!\nTransformers are awesome!\nBye!\n')
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple:
"""simple docstring"""
with ContextManagers([context_fr(), context_en()]):
print('Transformers are awesome!')
# The output should be wrapped with an English and French welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , 'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n')
@require_torch
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
self.assertEqual(find_labels(__a) , ['labels'])
self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label'])
self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions'])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , ['labels'])
@require_tf
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
self.assertEqual(find_labels(__a) , ['labels'])
self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label'])
self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions'])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , ['labels'])
@require_flax
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
self.assertEqual(find_labels(__a) , [])
self.assertEqual(find_labels(__a) , [])
self.assertEqual(find_labels(__a) , [])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , []) | 61 | 0 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> int:
"""simple docstring"""
return int((input_a, input_a).count(0 ) != 0 )
def _SCREAMING_SNAKE_CASE ( ) -> None:
"""simple docstring"""
assert nand_gate(0 , 0 ) == 1
assert nand_gate(0 , 1 ) == 1
assert nand_gate(1 , 0 ) == 1
assert nand_gate(1 , 1 ) == 0
if __name__ == "__main__":
print(nand_gate(0, 0))
print(nand_gate(0, 1))
print(nand_gate(1, 0))
print(nand_gate(1, 1)) | 720 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__A = {'''configuration_timm_backbone''': ['''TimmBackboneConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ['''TimmBackbone''']
if TYPE_CHECKING:
from .configuration_timm_backbone import TimmBackboneConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_timm_backbone import TimmBackbone
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 61 | 0 |
'''simple docstring'''
import secrets
from random import shuffle
from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation
def _SCREAMING_SNAKE_CASE ( A : int = 8 ) -> Union[str, Any]:
"""simple docstring"""
__snake_case : int = ascii_letters + digits + punctuation
return "".join(secrets.choice(_lowerCamelCase ) for _ in range(_lowerCamelCase ) )
def _SCREAMING_SNAKE_CASE ( A : str , A : int ) -> str:
"""simple docstring"""
# Password Generator = full boot with random_number, random_letters, and
# random_character FUNCTIONS
# Put your code here...
i -= len(_lowerCamelCase )
__snake_case : List[Any] = i // 3
__snake_case : str = i % 3
# chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) +
# random_number(digits, i / 3) + random_characters(punctuation, i / 3)
__snake_case : List[str] = (
chars_incl
+ random(_lowerCamelCase , quotient + remainder )
+ random(_lowerCamelCase , _lowerCamelCase )
+ random(_lowerCamelCase , _lowerCamelCase )
)
__snake_case : List[Any] = list(_lowerCamelCase )
shuffle(_lowerCamelCase )
return "".join(_lowerCamelCase )
# random is a generalised function for letters, characters and numbers
def _SCREAMING_SNAKE_CASE ( A : str , A : int ) -> Tuple:
"""simple docstring"""
return "".join(secrets.choice(_lowerCamelCase ) for _ in range(_lowerCamelCase ) )
def _SCREAMING_SNAKE_CASE ( A : Dict , A : str ) -> Optional[int]:
"""simple docstring"""
pass # Put your code here...
def _SCREAMING_SNAKE_CASE ( A : Union[str, Any] , A : Optional[Any] ) -> Dict:
"""simple docstring"""
pass # Put your code here...
def _SCREAMING_SNAKE_CASE ( A : int , A : str ) -> Any:
"""simple docstring"""
pass # Put your code here...
def _SCREAMING_SNAKE_CASE ( A : str , A : int = 8 ) -> List[Any]:
"""simple docstring"""
if len(_lowerCamelCase ) < min_length:
# Your Password must be at least 8 characters long
return False
__snake_case : Dict = any(char in ascii_uppercase for char in password )
__snake_case : Dict = any(char in ascii_lowercase for char in password )
__snake_case : Union[str, Any] = any(char in digits for char in password )
__snake_case : Tuple = any(char in punctuation for char in password )
return upper and lower and num and spec_char
# Passwords should contain UPPERCASE, lowerase
# numbers, and special characters
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
__snake_case : List[Any] = int(input('Please indicate the max length of your password: ' ).strip() )
__snake_case : str = input(
'Please indicate the characters that must be in your password: ' ).strip()
print('Password generated:' , password_generator(_lowerCamelCase ) )
print(
'Alternative Password generated:' , alternative_password_generator(_lowerCamelCase , _lowerCamelCase ) , )
print('[If you are thinking of using this passsword, You better save it.]' )
if __name__ == "__main__":
main() | 721 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
__snake_case : str = 1
for i in range(1 , num + 1 ):
fact *= i
return fact
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
__snake_case : Union[str, Any] = 0
while number > 0:
__snake_case : Dict = number % 10
sum_of_digits += last_digit
__snake_case : Union[str, Any] = number // 10 # Removing the last_digit from the given number
return sum_of_digits
def _SCREAMING_SNAKE_CASE ( A : int = 1_00 ) -> int:
"""simple docstring"""
__snake_case : List[Any] = factorial(A )
__snake_case : Dict = split_and_add(A )
return result
if __name__ == "__main__":
print(solution(int(input('''Enter the Number: ''').strip()))) | 61 | 0 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
"""kssteven/ibert-roberta-base""": """https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json""",
"""kssteven/ibert-roberta-large""": """https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json""",
"""kssteven/ibert-roberta-large-mnli""": (
"""https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json"""
),
}
class a_ ( snake_case_ ):
_snake_case = """ibert"""
def __init__(self , __a=3_0_5_2_2 , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_1_2 , __a=2 , __a=0.02 , __a=1E-12 , __a=1 , __a=0 , __a=2 , __a="absolute" , __a=False , __a="none" , **__a , ) -> Union[str, Any]:
"""simple docstring"""
super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a)
__snake_case : Union[str, Any] = vocab_size
__snake_case : Dict = hidden_size
__snake_case : Any = num_hidden_layers
__snake_case : Optional[int] = num_attention_heads
__snake_case : Optional[int] = hidden_act
__snake_case : int = intermediate_size
__snake_case : Dict = hidden_dropout_prob
__snake_case : str = attention_probs_dropout_prob
__snake_case : Dict = max_position_embeddings
__snake_case : int = type_vocab_size
__snake_case : Union[str, Any] = initializer_range
__snake_case : int = layer_norm_eps
__snake_case : Tuple = position_embedding_type
__snake_case : List[Any] = quant_mode
__snake_case : List[Any] = force_dequant
class a_ ( snake_case_ ):
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
if self.task == "multiple-choice":
__snake_case : Tuple = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
__snake_case : Union[str, Any] = {0: 'batch', 1: 'sequence'}
return OrderedDict(
[
('input_ids', dynamic_axis),
('attention_mask', dynamic_axis),
]) | 700 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import ChineseCLIPImageProcessor
class a_ ( unittest.TestCase ):
def __init__(self , __a , __a=7 , __a=3 , __a=1_8 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=None , __a=True , __a=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __a=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __a=True , ) -> List[Any]:
"""simple docstring"""
__snake_case : Tuple = size if size is not None else {'height': 2_2_4, 'width': 2_2_4}
__snake_case : Any = crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8}
__snake_case : Optional[int] = parent
__snake_case : Dict = batch_size
__snake_case : str = num_channels
__snake_case : Optional[Any] = image_size
__snake_case : Optional[int] = min_resolution
__snake_case : Tuple = max_resolution
__snake_case : Optional[int] = do_resize
__snake_case : Optional[int] = size
__snake_case : Union[str, Any] = do_center_crop
__snake_case : List[Any] = crop_size
__snake_case : int = do_normalize
__snake_case : Optional[Any] = image_mean
__snake_case : str = image_std
__snake_case : Optional[Any] = do_convert_rgb
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_convert_rgb": self.do_convert_rgb,
}
def SCREAMING_SNAKE_CASE__ (self , __a=False , __a=False , __a=False) -> List[str]:
"""simple docstring"""
assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"
if equal_resolution:
__snake_case : Optional[int] = []
for i in range(self.batch_size):
image_inputs.append(
np.random.randint(
2_5_5 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta))
else:
__snake_case : Dict = []
for i in range(self.batch_size):
__snake_case ,__snake_case : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution) , 2)
image_inputs.append(np.random.randint(2_5_5 , size=(self.num_channels, width, height) , dtype=np.uinta))
if not numpify and not torchify:
# PIL expects the channel dimension as last dimension
__snake_case : int = [Image.fromarray(np.moveaxis(__a , 0 , -1)) for x in image_inputs]
if torchify:
__snake_case : List[Any] = [torch.from_numpy(__a) for x in image_inputs]
return image_inputs
@require_torch
@require_vision
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = ChineseCLIPImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Union[str, Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=__a)
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : int = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , 'do_resize'))
self.assertTrue(hasattr(__a , 'size'))
self.assertTrue(hasattr(__a , 'do_center_crop'))
self.assertTrue(hasattr(__a , 'center_crop'))
self.assertTrue(hasattr(__a , 'do_normalize'))
self.assertTrue(hasattr(__a , 'image_mean'))
self.assertTrue(hasattr(__a , 'image_std'))
self.assertTrue(hasattr(__a , 'do_convert_rgb'))
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'height': 2_2_4, 'width': 2_2_4})
self.assertEqual(image_processor.crop_size , {'height': 1_8, 'width': 1_8})
__snake_case : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4)
self.assertEqual(image_processor.size , {'shortest_edge': 4_2})
self.assertEqual(image_processor.crop_size , {'height': 8_4, 'width': 8_4})
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
__snake_case : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
__snake_case : int = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : List[Any] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
__snake_case : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=__a , numpify=__a)
for image in image_inputs:
self.assertIsInstance(__a , np.ndarray)
# Test not batched input
__snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : int = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Any = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
__snake_case : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__a , torchify=__a)
for image in image_inputs:
self.assertIsInstance(__a , torch.Tensor)
# Test not batched input
__snake_case : Any = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : Union[str, Any] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
@require_torch
@require_vision
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = ChineseCLIPImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[Any] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__a)
__snake_case : List[Any] = 3
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Any = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , 'do_resize'))
self.assertTrue(hasattr(__a , 'size'))
self.assertTrue(hasattr(__a , 'do_center_crop'))
self.assertTrue(hasattr(__a , 'center_crop'))
self.assertTrue(hasattr(__a , 'do_normalize'))
self.assertTrue(hasattr(__a , 'image_mean'))
self.assertTrue(hasattr(__a , 'image_std'))
self.assertTrue(hasattr(__a , 'do_convert_rgb'))
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
__snake_case : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
__snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.expected_encoded_image_num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : Optional[int] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.expected_encoded_image_num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , ) | 61 | 0 |
'''simple docstring'''
import unittest
from queue import Empty
from threading import Thread
from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available
from transformers.testing_utils import CaptureStdout, require_torch, torch_device
from ..test_modeling_common import ids_tensor
if is_torch_available():
import torch
from transformers import AutoModelForCausalLM
@require_torch
class a_ ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case : List[str] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2')
__snake_case : Dict = AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2').to(lowercase__)
__snake_case : Optional[Any] = -1
__snake_case : int = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(lowercase__)
__snake_case : Union[str, Any] = model.generate(lowercase__ , max_new_tokens=1_0 , do_sample=lowercase__)
__snake_case : Dict = tokenizer.decode(greedy_ids[0])
with CaptureStdout() as cs:
__snake_case : Any = TextStreamer(lowercase__)
model.generate(lowercase__ , max_new_tokens=1_0 , do_sample=lowercase__ , streamer=lowercase__)
# The greedy text should be printed to stdout, except for the final "\n" in the streamer
__snake_case : Tuple = cs.out[:-1]
self.assertEqual(lowercase__ , lowercase__)
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : Optional[int] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2')
__snake_case : Optional[int] = AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2').to(lowercase__)
__snake_case : List[Any] = -1
__snake_case : Union[str, Any] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(lowercase__)
__snake_case : Union[str, Any] = model.generate(lowercase__ , max_new_tokens=1_0 , do_sample=lowercase__)
__snake_case : Tuple = tokenizer.decode(greedy_ids[0])
__snake_case : Dict = TextIteratorStreamer(lowercase__)
__snake_case : Dict = {"input_ids": input_ids, "max_new_tokens": 1_0, "do_sample": False, "streamer": streamer}
__snake_case : int = Thread(target=model.generate , kwargs=lowercase__)
thread.start()
__snake_case : Tuple = ""
for new_text in streamer:
streamer_text += new_text
self.assertEqual(lowercase__ , lowercase__)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
__snake_case : Any = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2')
__snake_case : Union[str, Any] = AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2').to(lowercase__)
__snake_case : Union[str, Any] = -1
__snake_case : Tuple = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(lowercase__)
__snake_case : int = model.generate(lowercase__ , max_new_tokens=1_0 , do_sample=lowercase__)
__snake_case : Tuple = greedy_ids[:, input_ids.shape[1] :]
__snake_case : Tuple = tokenizer.decode(new_greedy_ids[0])
with CaptureStdout() as cs:
__snake_case : List[str] = TextStreamer(lowercase__ , skip_prompt=lowercase__)
model.generate(lowercase__ , max_new_tokens=1_0 , do_sample=lowercase__ , streamer=lowercase__)
# The greedy text should be printed to stdout, except for the final "\n" in the streamer
__snake_case : List[str] = cs.out[:-1]
self.assertEqual(lowercase__ , lowercase__)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
__snake_case : str = AutoTokenizer.from_pretrained('distilgpt2')
__snake_case : List[str] = AutoModelForCausalLM.from_pretrained('distilgpt2').to(lowercase__)
__snake_case : List[str] = -1
__snake_case : Tuple = torch.ones((1, 5) , device=lowercase__).long() * model.config.bos_token_id
with CaptureStdout() as cs:
__snake_case : List[str] = TextStreamer(lowercase__ , skip_special_tokens=lowercase__)
model.generate(lowercase__ , max_new_tokens=1 , do_sample=lowercase__ , streamer=lowercase__)
# The prompt contains a special token, so the streamer should not print it. As such, the output text, when
# re-tokenized, must only contain one token
__snake_case : Optional[int] = cs.out[:-1] # Remove the final "\n"
__snake_case : Dict = tokenizer(lowercase__ , return_tensors='pt')
self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1))
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
__snake_case : Any = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2')
__snake_case : Tuple = AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2').to(lowercase__)
__snake_case : str = -1
__snake_case : Optional[int] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size).to(lowercase__)
__snake_case : Tuple = TextIteratorStreamer(lowercase__ , timeout=0.001)
__snake_case : Dict = {"input_ids": input_ids, "max_new_tokens": 1_0, "do_sample": False, "streamer": streamer}
__snake_case : Optional[Any] = Thread(target=model.generate , kwargs=lowercase__)
thread.start()
# The streamer will timeout after 0.001 seconds, so an exception will be raised
with self.assertRaises(lowercase__):
__snake_case : Dict = ""
for new_text in streamer:
streamer_text += new_text | 701 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json''',
# See all ViT MSN models at https://huggingface.co/models?filter=vit_msn
}
class a_ ( UpperCamelCase_ ):
_snake_case = """vit_msn"""
def __init__(self , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-06 , __a=2_2_4 , __a=1_6 , __a=3 , __a=True , **__a , ) -> Any:
"""simple docstring"""
super().__init__(**__a)
__snake_case : List[str] = hidden_size
__snake_case : Optional[int] = num_hidden_layers
__snake_case : Optional[Any] = num_attention_heads
__snake_case : str = intermediate_size
__snake_case : List[str] = hidden_act
__snake_case : List[Any] = hidden_dropout_prob
__snake_case : Tuple = attention_probs_dropout_prob
__snake_case : List[str] = initializer_range
__snake_case : Optional[int] = layer_norm_eps
__snake_case : Dict = image_size
__snake_case : int = patch_size
__snake_case : Dict = num_channels
__snake_case : Tuple = qkv_bias | 61 | 0 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : Union[str, Any] ) -> bool:
"""simple docstring"""
return number & 1 == 0
if __name__ == "__main__":
import doctest
doctest.testmod() | 702 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : float , A : list[float] ) -> float:
"""simple docstring"""
if discount_rate < 0:
raise ValueError('Discount rate cannot be negative' )
if not cash_flows:
raise ValueError('Cash flows list cannot be empty' )
__snake_case : List[str] = sum(
cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(A ) )
return round(A , ndigits=2 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 61 | 0 |
'''simple docstring'''
from typing import List, Optional, Tuple, Union
import torch
from ...utils import logging, randn_tensor
from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline
__A = logging.get_logger(__name__) # pylint: disable=invalid-name
class a_ ( __A ):
def __init__(self , __a , __a) -> Any:
"""simple docstring"""
super().__init__()
self.register_modules(unet=__a , scheduler=__a)
@torch.no_grad()
def __call__(self , __a = 1 , __a = 1_0_0 , __a = None , __a = None , __a = True , ) -> str:
"""simple docstring"""
if audio_length_in_s is None:
__snake_case : Union[str, Any] = self.unet.config.sample_size / self.unet.config.sample_rate
__snake_case : Optional[Any] = audio_length_in_s * self.unet.config.sample_rate
__snake_case : int = 2 ** len(self.unet.up_blocks)
if sample_size < 3 * down_scale_factor:
raise ValueError(
F"""{audio_length_in_s} is too small. Make sure it\'s bigger or equal to"""
F""" {3 * down_scale_factor / self.unet.config.sample_rate}.""")
__snake_case : str = int(__a)
if sample_size % down_scale_factor != 0:
__snake_case : Dict = (
(audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1
) * down_scale_factor
logger.info(
F"""{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled"""
F""" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising"""
' process.')
__snake_case : Any = int(__a)
__snake_case : Union[str, Any] = next(iter(self.unet.parameters())).dtype
__snake_case : List[Any] = (batch_size, self.unet.config.in_channels, sample_size)
if isinstance(__a , __a) and len(__a) != batch_size:
raise ValueError(
F"""You have passed a list of generators of length {len(__a)}, but requested an effective batch"""
F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""")
__snake_case : List[str] = randn_tensor(__a , generator=__a , device=self.device , dtype=__a)
# set step values
self.scheduler.set_timesteps(__a , device=audio.device)
__snake_case : Optional[int] = self.scheduler.timesteps.to(__a)
for t in self.progress_bar(self.scheduler.timesteps):
# 1. predict noise model_output
__snake_case : int = self.unet(__a , __a).sample
# 2. compute previous image: x_t -> t_t-1
__snake_case : Union[str, Any] = self.scheduler.step(__a , __a , __a).prev_sample
__snake_case : Optional[int] = audio.clamp(-1 , 1).float().cpu().numpy()
__snake_case : Optional[Any] = audio[:, :, :original_sample_size]
if not return_dict:
return (audio,)
return AudioPipelineOutput(audios=__a) | 703 |
'''simple docstring'''
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__) | 61 | 0 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : Optional[int] ) -> Any:
"""simple docstring"""
if not isinstance(__snake_case , __snake_case ):
raise TypeError('Input value must be an \'int\' type' )
__snake_case : Union[str, Any] = 0
while number:
position += 1
number >>= 1
return position
if __name__ == "__main__":
import doctest
doctest.testmod() | 704 |
'''simple docstring'''
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run
import sys
import warnings
from os.path import abspath, dirname, join
# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
__A = abspath(join(dirname(dirname(__file__)), '''src'''))
sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='''ignore''', category=FutureWarning)
def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> str:
"""simple docstring"""
from diffusers.utils.testing_utils import pytest_addoption_shared
pytest_addoption_shared(A )
def _SCREAMING_SNAKE_CASE ( A : int ) -> Optional[int]:
"""simple docstring"""
from diffusers.utils.testing_utils import pytest_terminal_summary_main
__snake_case : Any = terminalreporter.config.getoption('--make-reports' )
if make_reports:
pytest_terminal_summary_main(A , id=A ) | 61 | 0 |
'''simple docstring'''
from __future__ import annotations
import math
def _SCREAMING_SNAKE_CASE ( A : Any , A : str , A : str , A : List[str] , A : List[str] ) -> str:
"""simple docstring"""
if depth < 0:
raise ValueError('Depth cannot be less than 0' )
if len(lowerCAmelCase__ ) == 0:
raise ValueError('Scores cannot be empty' )
if depth == height:
return scores[node_index]
if is_max:
return max(
minimax(depth + 1 , node_index * 2 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) , minimax(depth + 1 , node_index * 2 + 1 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) , )
return min(
minimax(depth + 1 , node_index * 2 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) , minimax(depth + 1 , node_index * 2 + 1 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) , )
def _SCREAMING_SNAKE_CASE ( ) -> Optional[int]:
"""simple docstring"""
__snake_case : Union[str, Any] = [90, 23, 6, 33, 21, 65, 1_23, 3_44_23]
__snake_case : Union[str, Any] = math.log(len(lowerCAmelCase__ ) , 2 )
print('Optimal value : ' , end='' )
print(minimax(0 , 0 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 705 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
__A = {
'''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''],
'''tokenization_biogpt''': ['''BioGptTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''BioGptForCausalLM''',
'''BioGptForTokenClassification''',
'''BioGptForSequenceClassification''',
'''BioGptModel''',
'''BioGptPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig
from .tokenization_biogpt import BioGptTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_biogpt import (
BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST,
BioGptForCausalLM,
BioGptForSequenceClassification,
BioGptForTokenClassification,
BioGptModel,
BioGptPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 61 | 0 |
'''simple docstring'''
# limitations under the License.
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401
from .utils import deprecate
deprecate(
'''pipelines_utils''',
'''0.22.0''',
'''Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.''',
standard_warn=False,
stacklevel=3,
) | 706 |
'''simple docstring'''
from packaging import version
from .import_utils import is_accelerate_available
if is_accelerate_available():
import accelerate
def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> int:
"""simple docstring"""
if not is_accelerate_available():
return method
__snake_case : Optional[Any] = version.parse(accelerate.__version__ ).base_version
if version.parse(A ) < version.parse('0.17.0' ):
return method
def wrapper(self : Optional[Any] , *A : Optional[Any] , **A : Optional[int] ):
if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ):
self._hf_hook.pre_forward(self )
return method(self , *A , **A )
return wrapper | 61 | 0 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> int:
"""simple docstring"""
return "".join([hex(_snake_case )[2:].zfill(2 ).upper() for byte in list(_snake_case )] )
def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> List[str]:
"""simple docstring"""
if (len(_snake_case ) % 2) != 0:
raise ValueError(
'Base16 encoded data is invalid:\nData does not have an even number of hex digits.' )
# Check the character set - the standard base16 alphabet
# is uppercase according to RFC3548 section 6
if not set(_snake_case ) <= set('0123456789ABCDEF' ):
raise ValueError(
'Base16 encoded data is invalid:\nData is not uppercase hex or it contains invalid characters.' )
# For every two hexadecimal digits (= a byte), turn it into an integer.
# Then, string the result together into bytes, and return it.
return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(_snake_case ) , 2 ) )
if __name__ == "__main__":
import doctest
doctest.testmod() | 707 |
'''simple docstring'''
import unittest
from transformers import load_tool
from transformers.utils import is_torch_available
if is_torch_available():
import torch
from transformers.testing_utils import require_torch
from .test_tools_common import ToolTesterMixin
@require_torch
class a_ ( unittest.TestCase , UpperCamelCase_ ):
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[str] = load_tool('text-to-speech')
self.tool.setup()
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : Dict = self.tool('hey')
__snake_case : List[Any] = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , ))
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : Any = self.tool('hey')
__snake_case : Any = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , )) | 61 | 0 |
'''simple docstring'''
import json
from typing import List, Optional, Tuple
from tokenizers import pre_tokenizers, processors
from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bart import BartTokenizer
__A = logging.get_logger(__name__)
__A = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}
# See all BART models at https://huggingface.co/models?filter=bart
__A = {
'vocab_file': {
'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json',
'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json',
'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json',
'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json',
'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json',
'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json',
},
'merges_file': {
'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt',
'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt',
'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt',
'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt',
'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt',
'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt',
},
'tokenizer_file': {
'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json',
'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json',
'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json',
'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json',
'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json',
'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json',
},
}
__A = {
'facebook/bart-base': 1_0_2_4,
'facebook/bart-large': 1_0_2_4,
'facebook/bart-large-mnli': 1_0_2_4,
'facebook/bart-large-cnn': 1_0_2_4,
'facebook/bart-large-xsum': 1_0_2_4,
'yjernite/bart_eli5': 1_0_2_4,
}
class a_ ( lowerCAmelCase__ ):
_snake_case = VOCAB_FILES_NAMES
_snake_case = PRETRAINED_VOCAB_FILES_MAP
_snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_snake_case = ["input_ids", "attention_mask"]
_snake_case = BartTokenizer
def __init__(self , __a=None , __a=None , __a=None , __a="replace" , __a="<s>" , __a="</s>" , __a="</s>" , __a="<s>" , __a="<unk>" , __a="<pad>" , __a="<mask>" , __a=False , __a=True , **__a , ) -> Any:
"""simple docstring"""
super().__init__(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , tokenizer_file=_SCREAMING_SNAKE_CASE , errors=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , trim_offsets=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
__snake_case : Optional[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
if pre_tok_state.get('add_prefix_space' , _SCREAMING_SNAKE_CASE) != add_prefix_space:
__snake_case : Union[str, Any] = getattr(_SCREAMING_SNAKE_CASE , pre_tok_state.pop('type'))
__snake_case : Tuple = add_prefix_space
__snake_case : List[str] = pre_tok_class(**_SCREAMING_SNAKE_CASE)
__snake_case : Optional[Any] = add_prefix_space
# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
__snake_case : Union[str, Any] = 'post_processor'
__snake_case : Union[str, Any] = getattr(self.backend_tokenizer , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE)
if tokenizer_component_instance:
__snake_case : Optional[Any] = json.loads(tokenizer_component_instance.__getstate__())
# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
if "sep" in state:
__snake_case : Any = tuple(state['sep'])
if "cls" in state:
__snake_case : Any = tuple(state['cls'])
__snake_case : List[Any] = False
if state.get('add_prefix_space' , _SCREAMING_SNAKE_CASE) != add_prefix_space:
__snake_case : int = add_prefix_space
__snake_case : Dict = True
if state.get('trim_offsets' , _SCREAMING_SNAKE_CASE) != trim_offsets:
__snake_case : Dict = trim_offsets
__snake_case : Any = True
if changes_to_apply:
__snake_case : Any = getattr(_SCREAMING_SNAKE_CASE , state.pop('type'))
__snake_case : Optional[int] = component_class(**_SCREAMING_SNAKE_CASE)
setattr(self.backend_tokenizer , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE)
@property
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
if self._mask_token is None:
if self.verbose:
logger.error('Using mask_token, but it is not set yet.')
return None
return str(self._mask_token)
@mask_token.setter
def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple:
"""simple docstring"""
__snake_case : List[str] = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) else value
__snake_case : Tuple = value
def SCREAMING_SNAKE_CASE__ (self , *__a , **__a) -> BatchEncoding:
"""simple docstring"""
__snake_case : List[Any] = kwargs.get('is_split_into_words' , _SCREAMING_SNAKE_CASE)
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
'to use it with pretokenized inputs.')
return super()._batch_encode_plus(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE)
def SCREAMING_SNAKE_CASE__ (self , *__a , **__a) -> BatchEncoding:
"""simple docstring"""
__snake_case : List[str] = kwargs.get('is_split_into_words' , _SCREAMING_SNAKE_CASE)
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
'to use it with pretokenized inputs.')
return super()._encode_plus(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE)
def SCREAMING_SNAKE_CASE__ (self , __a , __a = None) -> Tuple[str]:
"""simple docstring"""
__snake_case : str = self._tokenizer.model.save(_SCREAMING_SNAKE_CASE , name=_SCREAMING_SNAKE_CASE)
return tuple(_SCREAMING_SNAKE_CASE)
def SCREAMING_SNAKE_CASE__ (self , __a , __a=None) -> str:
"""simple docstring"""
__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 SCREAMING_SNAKE_CASE__ (self , __a , __a = None) -> List[int]:
"""simple docstring"""
__snake_case : Dict = [self.sep_token_id]
__snake_case : 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 + sep + token_ids_a + sep) * [0] | 708 |
'''simple docstring'''
import math
class a_ :
def __init__(self , __a=0) -> Any: # a graph with Node 0,1,...,N-1
"""simple docstring"""
__snake_case : List[str] = n
__snake_case : Tuple = [
[math.inf for j in range(0 , __a)] for i in range(0 , __a)
] # adjacency matrix for weight
__snake_case : Union[str, Any] = [
[math.inf for j in range(0 , __a)] for i in range(0 , __a)
] # dp[i][j] stores minimum distance from i to j
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple:
"""simple docstring"""
__snake_case : Union[str, Any] = w
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
for k in range(0 , self.n):
for i in range(0 , self.n):
for j in range(0 , self.n):
__snake_case : List[Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j])
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Optional[int]:
"""simple docstring"""
return self.dp[u][v]
if __name__ == "__main__":
__A = Graph(5)
graph.add_edge(0, 2, 9)
graph.add_edge(0, 4, 1_0)
graph.add_edge(1, 3, 5)
graph.add_edge(2, 3, 7)
graph.add_edge(3, 0, 1_0)
graph.add_edge(3, 1, 2)
graph.add_edge(3, 2, 1)
graph.add_edge(3, 4, 6)
graph.add_edge(4, 1, 3)
graph.add_edge(4, 2, 4)
graph.add_edge(4, 3, 9)
graph.floyd_warshall()
graph.show_min(1, 4)
graph.show_min(0, 3) | 61 | 0 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'google/canine-s': 'https://huggingface.co/google/canine-s/resolve/main/config.json',
# See all CANINE models at https://huggingface.co/models?filter=canine
}
class a_ ( _A ):
_snake_case = """canine"""
def __init__(self , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.1 , __a=0.1 , __a=1_6_3_8_4 , __a=1_6 , __a=0.02 , __a=1E-12 , __a=0 , __a=0XE_000 , __a=0XE_001 , __a=4 , __a=4 , __a=8 , __a=1_6_3_8_4 , __a=1_2_8 , **__a , ) -> Optional[int]:
super().__init__(pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__)
__snake_case : Any = max_position_embeddings
__snake_case : List[Any] = hidden_size
__snake_case : int = num_hidden_layers
__snake_case : List[Any] = num_attention_heads
__snake_case : List[Any] = intermediate_size
__snake_case : List[Any] = hidden_act
__snake_case : Any = hidden_dropout_prob
__snake_case : str = attention_probs_dropout_prob
__snake_case : int = initializer_range
__snake_case : List[str] = type_vocab_size
__snake_case : Optional[Any] = layer_norm_eps
# Character config:
__snake_case : Tuple = downsampling_rate
__snake_case : List[str] = upsampling_kernel_size
__snake_case : List[str] = num_hash_functions
__snake_case : List[str] = num_hash_buckets
__snake_case : Any = local_transformer_stride | 709 |
'''simple docstring'''
from typing import Dict, List, Optional, Union
import numpy as np
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,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_vision_available():
import PIL
__A = logging.get_logger(__name__)
class a_ ( UpperCamelCase_ ):
_snake_case = ["""pixel_values"""]
def __init__(self , __a = True , __a = None , __a = None , __a = PILImageResampling.BILINEAR , __a = True , __a = 1 / 2_5_5 , __a = True , __a = None , __a = None , **__a , ) -> None:
"""simple docstring"""
super().__init__(**__a)
__snake_case : Tuple = size if size is not None else {'shortest_edge': 3_8_4}
__snake_case : List[Any] = get_size_dict(__a , default_to_square=__a)
__snake_case : int = do_resize
__snake_case : List[str] = size
# Default value set here for backwards compatibility where the value in config is None
__snake_case : Any = crop_pct if crop_pct is not None else 2_2_4 / 2_5_6
__snake_case : Tuple = resample
__snake_case : Dict = do_rescale
__snake_case : Any = rescale_factor
__snake_case : str = do_normalize
__snake_case : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
__snake_case : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = PILImageResampling.BICUBIC , __a = None , **__a , ) -> np.ndarray:
"""simple docstring"""
__snake_case : Dict = get_size_dict(__a , default_to_square=__a)
if "shortest_edge" not in size:
raise ValueError(F"""Size dictionary must contain 'shortest_edge' key. Got {size.keys()}""")
__snake_case : List[str] = size['shortest_edge']
if shortest_edge < 3_8_4:
# maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
__snake_case : Any = int(shortest_edge / crop_pct)
__snake_case : Any = get_resize_output_image_size(__a , size=__a , default_to_square=__a)
__snake_case : int = resize(image=__a , size=__a , resample=__a , data_format=__a , **__a)
# then crop to (shortest_edge, shortest_edge)
return center_crop(image=__a , size=(shortest_edge, shortest_edge) , data_format=__a , **__a)
else:
# warping (no cropping) when evaluated at 384 or larger
return resize(
__a , size=(shortest_edge, shortest_edge) , resample=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> Any:
"""simple docstring"""
return rescale(__a , scale=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray:
"""simple docstring"""
return normalize(__a , mean=__a , std=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image:
"""simple docstring"""
__snake_case : Optional[int] = do_resize if do_resize is not None else self.do_resize
__snake_case : Dict = crop_pct if crop_pct is not None else self.crop_pct
__snake_case : Tuple = resample if resample is not None else self.resample
__snake_case : Any = do_rescale if do_rescale is not None else self.do_rescale
__snake_case : Any = rescale_factor if rescale_factor is not None else self.rescale_factor
__snake_case : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize
__snake_case : Optional[int] = image_mean if image_mean is not None else self.image_mean
__snake_case : Optional[Any] = image_std if image_std is not None else self.image_std
__snake_case : List[str] = size if size is not None else self.size
__snake_case : Any = get_size_dict(__a , default_to_square=__a)
__snake_case : Dict = make_list_of_images(__a)
if not valid_images(__a):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.')
if do_resize and size is None or resample is None:
raise ValueError('Size and resample must be specified if do_resize is True.')
if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None:
raise ValueError('crop_pct must be specified if size < 384.')
if do_rescale and rescale_factor is None:
raise ValueError('Rescale factor must be specified if do_rescale is True.')
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('Image mean and std must be specified if do_normalize is True.')
# All transformations expect numpy arrays.
__snake_case : Tuple = [to_numpy_array(__a) for image in images]
if do_resize:
__snake_case : Optional[int] = [self.resize(image=__a , size=__a , crop_pct=__a , resample=__a) for image in images]
if do_rescale:
__snake_case : Optional[int] = [self.rescale(image=__a , scale=__a) for image in images]
if do_normalize:
__snake_case : Any = [self.normalize(image=__a , mean=__a , std=__a) for image in images]
__snake_case : Dict = [to_channel_dimension_format(__a , __a) for image in images]
__snake_case : Union[str, Any] = {'pixel_values': images}
return BatchFeature(data=__a , tensor_type=__a) | 61 | 0 |
import gc
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer
from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
class a_ ( snake_case__ , unittest.TestCase ):
_snake_case = ShapEPipeline
_snake_case = ['''prompt''']
_snake_case = ['''prompt''']
_snake_case = [
'''num_images_per_prompt''',
'''num_inference_steps''',
'''generator''',
'''latents''',
'''guidance_scale''',
'''frame_size''',
'''output_type''',
'''return_dict''',
]
_snake_case = False
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
return 3_2
@property
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
return 3_2
@property
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
return self.time_input_dim * 4
@property
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
return 8
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')
return tokenizer
@property
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : Optional[int] = 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=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , )
return CLIPTextModelWithProjection(_A)
@property
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : int = {
'num_attention_heads': 2,
'attention_head_dim': 1_6,
'embedding_dim': self.time_input_dim,
'num_embeddings': 3_2,
'embedding_proj_dim': self.text_embedder_hidden_size,
'time_embed_dim': self.time_embed_dim,
'num_layers': 1,
'clip_embed_dim': self.time_input_dim * 2,
'additional_embeddings': 0,
'time_embed_act_fn': 'gelu',
'norm_in_type': 'layer',
'encoder_hid_proj_type': None,
'added_emb_type': None,
}
__snake_case : Optional[Any] = PriorTransformer(**_A)
return model
@property
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : List[str] = {
'param_shapes': (
(self.renderer_dim, 9_3),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
),
'd_latent': self.time_input_dim,
'd_hidden': self.renderer_dim,
'n_output': 1_2,
'background': (
0.1,
0.1,
0.1,
),
}
__snake_case : List[Any] = ShapERenderer(**_A)
return model
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : List[str] = self.dummy_prior
__snake_case : Optional[int] = self.dummy_text_encoder
__snake_case : List[Any] = self.dummy_tokenizer
__snake_case : str = self.dummy_renderer
__snake_case : List[Any] = HeunDiscreteScheduler(
beta_schedule='exp' , num_train_timesteps=1_0_2_4 , prediction_type='sample' , use_karras_sigmas=_A , clip_sample=_A , clip_sample_range=1.0 , )
__snake_case : Any = {
'prior': prior,
'text_encoder': text_encoder,
'tokenizer': tokenizer,
'renderer': renderer,
'scheduler': scheduler,
}
return components
def SCREAMING_SNAKE_CASE__ (self , __a , __a=0) -> int:
"""simple docstring"""
if str(_A).startswith('mps'):
__snake_case : List[Any] = torch.manual_seed(_A)
else:
__snake_case : Dict = torch.Generator(device=_A).manual_seed(_A)
__snake_case : int = {
'prompt': 'horse',
'generator': generator,
'num_inference_steps': 1,
'frame_size': 3_2,
'output_type': 'np',
}
return inputs
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Tuple = 'cpu'
__snake_case : Any = self.get_dummy_components()
__snake_case : Tuple = self.pipeline_class(**_A)
__snake_case : List[str] = pipe.to(_A)
pipe.set_progress_bar_config(disable=_A)
__snake_case : Tuple = pipe(**self.get_dummy_inputs(_A))
__snake_case : int = output.images[0]
__snake_case : str = image[0, -3:, -3:, -1]
assert image.shape == (2_0, 3_2, 3_2, 3)
__snake_case : Any = np.array(
[
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
self._test_inference_batch_consistent(batch_sizes=[1, 2])
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
__snake_case : List[str] = torch_device == 'cpu'
__snake_case : Any = True
self._test_inference_batch_single_identical(
batch_size=2 , test_max_difference=_A , relax_max_difference=_A , )
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
__snake_case : Any = self.get_dummy_components()
__snake_case : Any = self.pipeline_class(**_A)
__snake_case : Dict = pipe.to(_A)
pipe.set_progress_bar_config(disable=_A)
__snake_case : Any = 1
__snake_case : Dict = 2
__snake_case : Tuple = self.get_dummy_inputs(_A)
for key in inputs.keys():
if key in self.batch_params:
__snake_case : Optional[int] = batch_size * [inputs[key]]
__snake_case : Optional[int] = pipe(**_A , num_images_per_prompt=_A)[0]
assert images.shape[0] == batch_size * num_images_per_prompt
@slow
@require_torch_gpu
class a_ ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
__snake_case : List[str] = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/shap_e/test_shap_e_np_out.npy')
__snake_case : Dict = ShapEPipeline.from_pretrained('openai/shap-e')
__snake_case : int = pipe.to(_A)
pipe.set_progress_bar_config(disable=_A)
__snake_case : str = torch.Generator(device=_A).manual_seed(0)
__snake_case : Tuple = pipe(
'a shark' , generator=_A , guidance_scale=1_5.0 , num_inference_steps=6_4 , frame_size=6_4 , output_type='np' , ).images[0]
assert images.shape == (2_0, 6_4, 6_4, 3)
assert_mean_pixel_difference(_A , _A) | 710 |
'''simple docstring'''
from functools import lru_cache
@lru_cache
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
if num < 0:
raise ValueError('Number should not be negative.' )
return 1 if num in (0, 1) else num * factorial(num - 1 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 61 | 0 |
'''simple docstring'''
import argparse
import os
import re
import torch
from flax.traverse_util import flatten_dict
from tax import checkpoints
from transformers import (
AutoTokenizer,
PixaStructConfig,
PixaStructForConditionalGeneration,
PixaStructImageProcessor,
PixaStructProcessor,
PixaStructTextConfig,
PixaStructVisionConfig,
)
def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> Dict:
"""simple docstring"""
__snake_case : Optional[Any] = checkpoints.load_tax_checkpoint(__snake_case )
__snake_case : Dict = flatten_dict(__snake_case )
return flax_params
def _SCREAMING_SNAKE_CASE ( A : Optional[int] ) -> Optional[Any]:
"""simple docstring"""
__snake_case : List[Any] = {}
__snake_case : Tuple = {
'token_embedder': 'embeddings',
'encoder_norm': 'layernorm',
'kernel': 'weight',
'.out': '.output',
'scale': 'weight',
'embedders_0.pos_embedding': 'row_embedder.weight',
'embedders_1.pos_embedding': 'column_embedder.weight',
}
__snake_case : Optional[Any] = {
'query': 'attention.query',
'key': 'attention.key',
'value': 'attention.value',
'output.dense': 'output',
'encoder_decoder_attention.o': 'encoder_decoder_attention.attention.o',
'pre_self_attention_layer_norm': 'self_attention.layer_norm',
'pre_cross_attention_layer_norm': 'encoder_decoder_attention.layer_norm',
'mlp.': 'mlp.DenseReluDense.',
'pre_mlp_layer_norm': 'mlp.layer_norm',
'self_attention.o': 'self_attention.attention.o',
'decoder.embeddings.embedding': 'decoder.embed_tokens.weight',
'decoder.relpos_bias.rel_embedding': 'decoder.layer.0.self_attention.attention.relative_attention_bias.weight',
'decoder.decoder_norm.weight': 'decoder.final_layer_norm.weight',
'decoder.logits_dense.weight': 'decoder.lm_head.weight',
}
for key in flax_dict.keys():
if "target" in key:
# remove the first prefix from the key
__snake_case : Union[str, Any] = '.'.join(key[1:] )
# rename the key
for old, new in CONVERSION_MAPPING.items():
__snake_case : Any = new_key.replace(__snake_case , __snake_case )
if "decoder" in new_key:
for old, new in DECODER_CONVERSION_MAPPING.items():
__snake_case : Optional[int] = new_key.replace(__snake_case , __snake_case )
if "layers" in new_key and "decoder" not in new_key:
# use regex to replace the layer number
__snake_case : Dict = re.sub(R'layers_(\d+)' , R'layer.\1' , __snake_case )
__snake_case : Optional[int] = new_key.replace('encoder' , 'encoder.encoder' )
elif "layers" in new_key and "decoder" in new_key:
# use regex to replace the layer number
__snake_case : List[str] = re.sub(R'layers_(\d+)' , R'layer.\1' , __snake_case )
__snake_case : Optional[int] = flax_dict[key]
__snake_case : str = {}
# convert converted_dict into torch format
for key in converted_dict.keys():
if ("embed_tokens" not in key) and ("embedder" not in key):
__snake_case : List[Any] = torch.from_numpy(converted_dict[key].T )
else:
__snake_case : Optional[Any] = torch.from_numpy(converted_dict[key] )
return converted_torch_dict
def _SCREAMING_SNAKE_CASE ( A : Optional[Any] , A : Any , A : str=False , A : Dict=False ) -> Any:
"""simple docstring"""
__snake_case : List[Any] = get_flax_param(__snake_case )
if not use_large:
__snake_case : Tuple = PixaStructVisionConfig()
__snake_case : Optional[Any] = PixaStructTextConfig()
else:
__snake_case : List[Any] = PixaStructVisionConfig(
hidden_size=15_36 , d_ff=39_68 , num_attention_heads=24 , num_hidden_layers=18 )
__snake_case : Any = PixaStructTextConfig(hidden_size=15_36 , d_ff=39_68 , num_heads=24 , num_layers=18 )
__snake_case : List[Any] = PixaStructConfig(
vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=__snake_case )
__snake_case : Any = PixaStructForConditionalGeneration(__snake_case )
__snake_case : Dict = rename_and_convert_flax_params(__snake_case )
model.load_state_dict(__snake_case )
__snake_case : Union[str, Any] = AutoTokenizer.from_pretrained('ybelkada/test-pix2struct-tokenizer' )
__snake_case : Dict = PixaStructImageProcessor()
__snake_case : Optional[Any] = PixaStructProcessor(image_processor=__snake_case , tokenizer=__snake_case )
if use_large:
__snake_case : Optional[Any] = 40_96
__snake_case : Optional[int] = True
# mkdir if needed
os.makedirs(__snake_case , exist_ok=__snake_case )
model.save_pretrained(__snake_case )
processor.save_pretrained(__snake_case )
print('Model saved in {}'.format(__snake_case ) )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument('''--t5x_checkpoint_path''', default=None, type=str, help='''Path to the original T5x checkpoint.''')
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument('''--use_large''', action='''store_true''', help='''Use large model.''')
parser.add_argument('''--is_vqa''', action='''store_true''', help='''Use large model.''')
__A = parser.parse_args()
convert_pixastruct_original_pytorch_checkpoint_to_hf(
args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large
) | 711 |
'''simple docstring'''
import unittest
import torch
from diffusers import VQModel
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism
from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ):
_snake_case = VQModel
_snake_case = """sample"""
@property
def SCREAMING_SNAKE_CASE__ (self , __a=(3_2, 3_2)) -> str:
"""simple docstring"""
__snake_case : Dict = 4
__snake_case : Optional[int] = 3
__snake_case : str = floats_tensor((batch_size, num_channels) + sizes).to(__a)
return {"sample": image}
@property
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
return (3, 3_2, 3_2)
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
return (3, 3_2, 3_2)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[Any] = {
'block_out_channels': [3_2, 6_4],
'in_channels': 3,
'out_channels': 3,
'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'],
'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'],
'latent_channels': 3,
}
__snake_case : List[Any] = self.dummy_input
return init_dict, inputs_dict
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case ,__snake_case : List[Any] = VQModel.from_pretrained('fusing/vqgan-dummy' , output_loading_info=__a)
self.assertIsNotNone(__a)
self.assertEqual(len(loading_info['missing_keys']) , 0)
model.to(__a)
__snake_case : Any = model(**self.dummy_input)
assert image is not None, "Make sure output is not None"
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : Union[str, Any] = VQModel.from_pretrained('fusing/vqgan-dummy')
model.to(__a).eval()
torch.manual_seed(0)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(0)
__snake_case : Tuple = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size)
__snake_case : Optional[int] = image.to(__a)
with torch.no_grad():
__snake_case : List[Any] = model(__a).sample
__snake_case : int = output[0, -1, -3:, -3:].flatten().cpu()
# fmt: off
__snake_case : int = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143])
# fmt: on
self.assertTrue(torch.allclose(__a , __a , atol=1E-3)) | 61 | 0 |
'''simple docstring'''
import unittest
from pathlib import Path
from shutil import copyfile
from transformers import SPIECE_UNDERLINE, is_sentencepiece_available
from transformers.models.speech_to_text import SpeechaTextTokenizer
from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
__A = get_tests_dir('''fixtures/test_sentencepiece.model''')
if is_sentencepiece_available():
import sentencepiece as sp
__A = 5
__A = 1_0
@require_sentencepiece
@require_tokenizers
class a_ ( lowercase_ , unittest.TestCase ):
_snake_case = SpeechaTextTokenizer
_snake_case = False
_snake_case = True
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
super().setUp()
__snake_case : int = sp.SentencePieceProcessor()
spm_model.Load(lowerCamelCase_)
__snake_case : Dict = ["""<s>""", """<pad>""", """</s>""", """<unk>"""]
vocab += [spm_model.IdToPiece(id_) for id_ in range(len(lowerCamelCase_))]
__snake_case : Tuple = dict(zip(lowerCamelCase_ , range(len(lowerCamelCase_))))
__snake_case : Optional[int] = Path(self.tmpdirname)
save_json(lowerCamelCase_ , save_dir / VOCAB_FILES_NAMES['vocab_file'])
if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
copyfile(lowerCamelCase_ , save_dir / VOCAB_FILES_NAMES['spm_file'])
__snake_case : List[str] = SpeechaTextTokenizer.from_pretrained(self.tmpdirname)
tokenizer.save_pretrained(self.tmpdirname)
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : str = """<pad>"""
__snake_case : Union[str, Any] = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase_) , lowerCamelCase_)
self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase_) , lowerCamelCase_)
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : int = list(self.get_tokenizer().get_vocab().keys())
self.assertEqual(vocab_keys[0] , '<s>')
self.assertEqual(vocab_keys[1] , '<pad>')
self.assertEqual(vocab_keys[-1] , 'j')
self.assertEqual(len(lowerCamelCase_) , 1_0_0_1)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_1)
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case : str = SpeechaTextTokenizer.from_pretrained(self.tmpdirname)
__snake_case : List[str] = tokenizer.tokenize('This is a test')
self.assertListEqual(lowerCamelCase_ , ['▁This', '▁is', '▁a', '▁t', 'est'])
self.assertListEqual(
tokenizer.convert_tokens_to_ids(lowerCamelCase_) , [2_8_9, 5_0, 1_4, 1_7_4, 3_8_6] , )
__snake_case : str = tokenizer.tokenize('I was born in 92000, and this is falsé.')
self.assertListEqual(
lowerCamelCase_ , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.'] , )
__snake_case : Optional[Any] = tokenizer.convert_tokens_to_ids(lowerCamelCase_)
self.assertListEqual(lowerCamelCase_ , [1_2, 2_5, 8_8, 5_9, 2_8, 2_3, 1_1, 4, 6_0_6, 3_5_1, 3_5_1, 3_5_1, 7, 1_6, 7_0, 5_0, 7_6, 8_4, 1_0, 4, 8])
__snake_case : List[str] = tokenizer.convert_ids_to_tokens(lowerCamelCase_)
self.assertListEqual(
lowerCamelCase_ , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.'] , )
@slow
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
__snake_case : List[str] = {"""input_ids""": [[3_7_9_1, 7_9_7, 3_1, 1_1, 6_4, 7_9_7, 3_1, 2_4_2_9, 4_3_3, 1_2, 1_1_7_6, 1_2, 2_0, 7_8_6, 9_1_5, 1_4_2, 2_4_1_3, 2_4_0, 3_7, 3_2_3_8, 7_9_7, 3_1, 1_1, 3_5, 9_3, 9_1_5, 1_4_2, 2_4_1_3, 2_4_0, 3_7, 5_5_4_0, 5_6_7, 1_2_7_6, 9_3, 3_7, 6_1_0, 4_0, 6_2, 4_5_5, 6_5_7, 1_0_4_2, 1_2_3, 7_8_0, 1_7_7, 3_7, 3_0_9, 2_4_1, 1_2_9_8, 5_1_4, 2_0, 2_9_2, 2_7_3_7, 1_1_4, 2_4_6_9, 2_4_1, 8_5, 6_4, 3_0_2, 5_4_8, 5_2_8, 4_2_3, 4, 5_0_9, 4_0_6, 4_2_3, 3_7, 6_0_1, 4, 7_7_7, 3_0_2, 5_4_8, 5_2_8, 4_2_3, 2_8_4, 4, 3_3_8_8, 5_1_1, 4_5_9, 4, 3_5_5_5, 4_0, 3_2_1, 3_0_2, 7_0_5, 4, 3_3_8_8, 5_1_1, 5_8_3, 3_2_6, 5, 5, 5, 6_2, 3_3_1_0, 5_6_0, 1_7_7, 2_6_8_0, 2_1_7, 1_5_0_8, 3_2, 3_1, 8_5_3, 4_1_8, 6_4, 5_8_3, 5_1_1, 1_6_0_5, 6_2, 3_5, 9_3, 5_6_0, 1_7_7, 2_6_8_0, 2_1_7, 1_5_0_8, 1_5_2_1, 6_4, 5_8_3, 5_1_1, 5_1_9, 6_2, 2_0, 1_5_1_5, 7_6_4, 2_0, 1_4_9, 2_6_1, 5_6_2_5, 7_9_7_2, 2_0, 5_5_4_0, 5_6_7, 1_2_7_6, 9_3, 3_9_2_5, 1_6_7_5, 1_1, 1_5, 8_0_2, 7_9_7_2, 5_7_6, 2_1_7, 1_5_0_8, 1_1, 3_5, 9_3, 1_2_5_3, 2_4_4_1, 1_5, 2_8_9, 6_5_2, 3_1, 4_1_6, 3_2_1, 3_8_4_2, 1_1_5, 4_0, 9_1_1, 8, 4_7_6, 6_1_9, 4, 3_8_0, 1_4_2, 4_2_3, 3_3_5, 2_4_0, 3_5, 9_3, 2_6_4, 8, 1_1, 3_3_5, 5_6_9, 4_2_0, 1_6_3, 5, 2], [2_6_0, 5_4_8, 5_2_8, 4_2_3, 2_0, 4_5_1, 2_0, 2_6_8_1, 1_1_5_3, 3_4_3_4, 2_0, 5_5_4_0, 3_7, 5_6_7, 1_2_6, 1_2_5_3, 2_4_4_1, 3_3_7_6, 4_4_9, 2_1_0, 4_3_1, 1_5_6_3, 1_7_7, 7_6_7, 5_5_4_0, 1_1, 1_2_0_3, 4_7_2, 1_1, 2_9_5_3, 6_8_5, 2_8_5, 3_6_4, 7_0_6, 1_1_5_3, 2_0, 6_7_9_9, 2_0, 2_8_6_9, 2_0, 4_4_6_4, 1_2_6, 4_0, 2_4_2_9, 2_0, 1_0_4_0, 8_6_6, 2_6_6_4, 4_1_8, 2_0, 3_1_8, 2_0, 1_7_2_6, 1_8_6, 2_0, 2_6_5, 5_2_2, 3_5, 9_3, 2_1_9_1, 4_6_3_4, 2_0, 1_0_4_0, 1_2, 6_7_9_9, 1_5, 2_2_8, 2_3_5_6, 1_4_2, 3_1, 1_1, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2_5_7_5, 2_6_6_6, 6_8_4, 1_5_8_2, 1_1_7_6, 1_2, 6_2_7, 1_4_9, 6_1_9, 2_0, 4_9_0_2, 5_6_3, 1_1, 2_0, 1_4_9, 2_6_1, 3_4_2_0, 2_3_5_6, 1_7_4, 1_4_2, 4_7_1_4, 1_3_1, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=lowerCamelCase_ , model_name='facebook/s2t-small-mustc-en-de-st' , revision='a14f04cf0776c02f62a8cb800cf7909e15ea23ad' , )
@require_sentencepiece
class a_ ( unittest.TestCase ):
_snake_case = """valhalla/s2t_mustc_multilinguial_medium"""
_snake_case = """C\'est trop cool"""
_snake_case = """Esto es genial"""
@classmethod
def SCREAMING_SNAKE_CASE__ (cls) -> Tuple:
"""simple docstring"""
__snake_case : SpeechaTextTokenizer = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name)
return cls
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
self.assertEqual(self.tokenizer.lang_code_to_id['pt'] , 4)
self.assertEqual(self.tokenizer.lang_code_to_id['ru'] , 6)
self.assertEqual(self.tokenizer.lang_code_to_id['it'] , 9)
self.assertEqual(self.tokenizer.lang_code_to_id['de'] , 1_1)
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
self.assertEqual(self.tokenizer.vocab_size , 1_0_0_0_0)
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
self.assertIn(lowerCamelCase_ , self.tokenizer.all_special_ids)
__snake_case : Dict = [ES_CODE, 4, 1_6_0_1, 4_7, 7_6_4_7, 2]
__snake_case : Tuple = self.tokenizer.decode(lowerCamelCase_ , skip_special_tokens=lowerCamelCase_)
__snake_case : Optional[int] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowerCamelCase_)
self.assertEqual(lowerCamelCase_ , lowerCamelCase_)
self.assertNotIn(self.tokenizer.eos_token , lowerCamelCase_)
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case : Any = """fr"""
__snake_case : str = self.tokenizer(self.french_text).input_ids
self.assertEqual(encoded[0] , lowerCamelCase_)
self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id)
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : Optional[int] = """fr"""
self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE])
__snake_case : Optional[Any] = """es"""
self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE]) | 712 |
'''simple docstring'''
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
__A = logging.getLogger(__name__)
@dataclass
class a_ :
_snake_case = field(
metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} )
_snake_case = field(
default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} )
_snake_case = 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.
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , )
@dataclass
class a_ :
_snake_case = field(
metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , )
_snake_case = field(
default=128 , metadata={
"""help""": (
"""The maximum total input sequence length after tokenization. Sequences longer """
"""than this will be truncated, sequences shorter will be padded."""
)
} , )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} )
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
# 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.
__snake_case : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
__snake_case ,__snake_case ,__snake_case : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
__snake_case ,__snake_case ,__snake_case : int = 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.' )
__snake_case : List[str] = import_module('tasks' )
try:
__snake_case : Any = getattr(A , model_args.task_type )
__snake_case : TokenClassificationTask = 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' , A )
# Set seed
set_seed(training_args.seed )
# Prepare CONLL-2003 task
__snake_case : Optional[Any] = token_classification_task.get_labels(data_args.labels )
__snake_case : Dict[int, str] = dict(enumerate(A ) )
__snake_case : Optional[Any] = len(A )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
__snake_case : Any = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=A , idalabel=A , labelaid={label: i for i, label in enumerate(A )} , cache_dir=model_args.cache_dir , )
__snake_case : List[str] = 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 , )
__snake_case : Optional[int] = AutoModelForTokenClassification.from_pretrained(
model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=A , cache_dir=model_args.cache_dir , )
# Get datasets
__snake_case : List[Any] = (
TokenClassificationDataset(
token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , 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
)
__snake_case : int = (
TokenClassificationDataset(
token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , 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(A : np.ndarray , A : np.ndarray ) -> Tuple[List[int], List[int]]:
__snake_case : str = np.argmax(A , axis=2 )
__snake_case ,__snake_case : int = preds.shape
__snake_case : Dict = [[] for _ in range(A )]
__snake_case : Union[str, Any] = [[] for _ in range(A )]
for i in range(A ):
for j in range(A ):
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(A : EvalPrediction ) -> Dict:
__snake_case ,__snake_case : Any = align_predictions(p.predictions , p.label_ids )
return {
"accuracy_score": accuracy_score(A , A ),
"precision": precision_score(A , A ),
"recall": recall_score(A , A ),
"f1": fa_score(A , A ),
}
# Data collator
__snake_case : Optional[int] = DataCollatorWithPadding(A , pad_to_multiple_of=8 ) if training_args.fpaa else None
# Initialize our Trainer
__snake_case : Optional[Any] = Trainer(
model=A , args=A , train_dataset=A , eval_dataset=A , compute_metrics=A , data_collator=A , )
# 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
__snake_case : List[Any] = {}
if training_args.do_eval:
logger.info('*** Evaluate ***' )
__snake_case : List[str] = trainer.evaluate()
__snake_case : Tuple = os.path.join(training_args.output_dir , 'eval_results.txt' )
if trainer.is_world_process_zero():
with open(A , 'w' ) as writer:
logger.info('***** Eval results *****' )
for key, value in result.items():
logger.info(' %s = %s' , A , A )
writer.write('%s = %s\n' % (key, value) )
results.update(A )
# Predict
if training_args.do_predict:
__snake_case : str = TokenClassificationDataset(
token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , )
__snake_case ,__snake_case ,__snake_case : str = trainer.predict(A )
__snake_case ,__snake_case : List[str] = align_predictions(A , A )
__snake_case : Optional[int] = os.path.join(training_args.output_dir , 'test_results.txt' )
if trainer.is_world_process_zero():
with open(A , 'w' ) as writer:
for key, value in metrics.items():
logger.info(' %s = %s' , A , A )
writer.write('%s = %s\n' % (key, value) )
# Save predictions
__snake_case : List[str] = os.path.join(training_args.output_dir , 'test_predictions.txt' )
if trainer.is_world_process_zero():
with open(A , 'w' ) as writer:
with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f:
token_classification_task.write_predictions_to_file(A , A , A )
return results
def _SCREAMING_SNAKE_CASE ( A : int ) -> Any:
"""simple docstring"""
# For xla_spawn (TPUs)
main()
if __name__ == "__main__":
main() | 61 | 0 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : int ) -> str:
"""simple docstring"""
return sum(i for i in range(1 , number // 2 + 1 ) if number % i == 0 ) == number
if __name__ == "__main__":
print('''Program to check whether a number is a Perfect number or not...''')
__A = int(input('''Enter number: ''').strip())
print(f'''{number} is {'' if perfect(number) else 'not '}a Perfect Number.''') | 713 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : list ) -> list:
"""simple docstring"""
__snake_case : Tuple = False
while is_sorted is False: # Until all the indices are traversed keep looping
__snake_case : Optional[Any] = True
for i in range(0 , len(A ) - 1 , 2 ): # iterating over all even indices
if input_list[i] > input_list[i + 1]:
__snake_case ,__snake_case : int = input_list[i + 1], input_list[i]
# swapping if elements not in order
__snake_case : List[Any] = False
for i in range(1 , len(A ) - 1 , 2 ): # iterating over all odd indices
if input_list[i] > input_list[i + 1]:
__snake_case ,__snake_case : Tuple = input_list[i + 1], input_list[i]
# swapping if elements not in order
__snake_case : Any = False
return input_list
if __name__ == "__main__":
print('''Enter list to be sorted''')
__A = [int(x) for x in input().split()]
# inputing elements of the list in one line
__A = odd_even_sort(input_list)
print('''The sorted list is''')
print(sorted_list) | 61 | 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 | 714 |
'''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 _SCREAMING_SNAKE_CASE ( A : int , A : str , A : LevitConfig , A : Path , A : bool = True ) -> Dict:
"""simple docstring"""
print(F"""Converting {name}...""" )
with torch.no_grad():
if hidden_sizes == 1_28:
if name[-1] == "S":
__snake_case : Optional[int] = timm.create_model('levit_128s' , pretrained=A )
else:
__snake_case : Tuple = timm.create_model('levit_128' , pretrained=A )
if hidden_sizes == 1_92:
__snake_case : int = timm.create_model('levit_192' , pretrained=A )
if hidden_sizes == 2_56:
__snake_case : List[Any] = timm.create_model('levit_256' , pretrained=A )
if hidden_sizes == 3_84:
__snake_case : int = timm.create_model('levit_384' , pretrained=A )
from_model.eval()
__snake_case : str = LevitForImageClassificationWithTeacher(A ).eval()
__snake_case : int = OrderedDict()
__snake_case : Optional[Any] = from_model.state_dict()
__snake_case : Tuple = list(from_model.state_dict().keys() )
__snake_case : List[str] = list(our_model.state_dict().keys() )
print(len(A ) , len(A ) )
for i in range(len(A ) ):
__snake_case : Optional[int] = weights[og_keys[i]]
our_model.load_state_dict(A )
__snake_case : Tuple = torch.randn((2, 3, 2_24, 2_24) )
__snake_case : Union[str, Any] = from_model(A )
__snake_case : List[str] = our_model(A ).logits
assert torch.allclose(A , A ), "The model logits don't match the original one."
__snake_case : int = name
print(A )
if push_to_hub:
our_model.save_pretrained(save_directory / checkpoint_name )
__snake_case : int = LevitImageProcessor()
image_processor.save_pretrained(save_directory / checkpoint_name )
print(F"""Pushed {checkpoint_name}""" )
def _SCREAMING_SNAKE_CASE ( A : Path , A : str = None , A : bool = True ) -> List[Any]:
"""simple docstring"""
__snake_case : Optional[Any] = 'imagenet-1k-id2label.json'
__snake_case : Tuple = 10_00
__snake_case : Dict = (1, num_labels)
__snake_case : List[str] = 'huggingface/label-files'
__snake_case : Any = num_labels
__snake_case : str = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) )
__snake_case : Any = {int(A ): v for k, v in idalabel.items()}
__snake_case : int = idalabel
__snake_case : Union[str, Any] = {v: k for k, v in idalabel.items()}
__snake_case : Optional[int] = partial(A , num_labels=A , idalabel=A , labelaid=A )
__snake_case : Dict = {
'levit-128S': 1_28,
'levit-128': 1_28,
'levit-192': 1_92,
'levit-256': 2_56,
'levit-384': 3_84,
}
__snake_case : Union[str, Any] = {
'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) | 61 | 0 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : Dict ) -> int:
"""simple docstring"""
__snake_case : Any = [1]
__snake_case ,__snake_case ,__snake_case : List[Any] = 0, 0, 0
__snake_case : List[Any] = ugly_nums[ia] * 2
__snake_case : List[Any] = ugly_nums[ia] * 3
__snake_case : Optional[int] = ugly_nums[ia] * 5
for _ in range(1 , a__ ):
__snake_case : Optional[Any] = min(a__ , a__ , a__ )
ugly_nums.append(a__ )
if next_num == next_a:
ia += 1
__snake_case : Tuple = ugly_nums[ia] * 2
if next_num == next_a:
ia += 1
__snake_case : str = ugly_nums[ia] * 3
if next_num == next_a:
ia += 1
__snake_case : Union[str, Any] = ugly_nums[ia] * 5
return ugly_nums[-1]
if __name__ == "__main__":
from doctest import testmod
testmod(verbose=True)
print(f'''{ugly_numbers(2_0_0) = }''') | 715 |
'''simple docstring'''
import inspect
import unittest
from typing import List
import numpy as np
from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFEfficientFormerForImageClassification,
TFEfficientFormerForImageClassificationWithTeacher,
TFEfficientFormerModel,
)
from transformers.models.efficientformer.modeling_tf_efficientformer import (
TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_vision_available():
from PIL import Image
from transformers import EfficientFormerImageProcessor
class a_ :
def __init__(self , __a , __a = 1_3 , __a = 6_4 , __a = 2 , __a = 3 , __a = 3 , __a = True , __a = True , __a = 1_2_8 , __a=[1_6, 3_2, 6_4, 1_2_8] , __a = 7 , __a = 4 , __a = 3_7 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 1_0 , __a = 0.02 , __a = 2 , __a = 1 , __a = 1_2_8 , __a = [2, 2, 2, 2] , __a = 2 , __a = 2 , ) -> str:
"""simple docstring"""
__snake_case : Optional[Any] = parent
__snake_case : Optional[int] = batch_size
__snake_case : Optional[Any] = image_size
__snake_case : Optional[int] = patch_size
__snake_case : Optional[Any] = num_channels
__snake_case : Optional[Any] = is_training
__snake_case : Tuple = use_labels
__snake_case : Optional[int] = hidden_size
__snake_case : Any = num_hidden_layers
__snake_case : List[str] = num_attention_heads
__snake_case : Tuple = intermediate_size
__snake_case : List[str] = hidden_act
__snake_case : Dict = hidden_dropout_prob
__snake_case : Any = attention_probs_dropout_prob
__snake_case : Dict = type_sequence_label_size
__snake_case : str = initializer_range
__snake_case : int = encoder_stride
__snake_case : List[str] = num_attention_outputs
__snake_case : Optional[Any] = embed_dim
__snake_case : Optional[Any] = embed_dim + 1
__snake_case : List[str] = resolution
__snake_case : Optional[int] = depths
__snake_case : List[Any] = hidden_sizes
__snake_case : List[str] = dim
__snake_case : Union[str, Any] = mlp_expansion_ratio
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
__snake_case : List[str] = None
if self.use_labels:
__snake_case : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size)
__snake_case : Tuple = self.get_config()
return config, pixel_values, labels
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return EfficientFormerConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , )
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Optional[int]:
"""simple docstring"""
__snake_case : Union[str, Any] = TFEfficientFormerModel(config=__a)
__snake_case : int = model(__a , training=__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple:
"""simple docstring"""
__snake_case : Dict = self.type_sequence_label_size
__snake_case : List[Any] = TFEfficientFormerForImageClassification(__a)
__snake_case : Optional[int] = model(__a , labels=__a , training=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size))
# test greyscale images
__snake_case : List[Any] = 1
__snake_case : List[Any] = TFEfficientFormerForImageClassification(__a)
__snake_case : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
__snake_case : str = model(__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size))
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : Union[str, Any] = self.prepare_config_and_inputs()
__snake_case ,__snake_case ,__snake_case : Union[str, Any] = config_and_inputs
__snake_case : Optional[int] = {'pixel_values': pixel_values}
return config, inputs_dict
@require_tf
class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ):
_snake_case = (
(
TFEfficientFormerModel,
TFEfficientFormerForImageClassificationWithTeacher,
TFEfficientFormerForImageClassification,
)
if is_tf_available()
else ()
)
_snake_case = (
{
"""feature-extraction""": TFEfficientFormerModel,
"""image-classification""": (
TFEfficientFormerForImageClassification,
TFEfficientFormerForImageClassificationWithTeacher,
),
}
if is_tf_available()
else {}
)
_snake_case = False
_snake_case = False
_snake_case = False
_snake_case = False
_snake_case = False
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Dict = TFEfficientFormerModelTester(self)
__snake_case : List[Any] = ConfigTester(
self , config_class=__a , has_text_modality=__a , hidden_size=3_7)
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
self.config_tester.run_common_tests()
@unittest.skip(reason='EfficientFormer does not use inputs_embeds')
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
pass
@unittest.skip(reason='EfficientFormer does not support input and output embeddings')
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case ,__snake_case : str = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case : Optional[int] = model_class(__a)
__snake_case : Union[str, Any] = inspect.signature(model.call)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__snake_case : Optional[int] = [*signature.parameters.keys()]
__snake_case : Dict = ['pixel_values']
self.assertListEqual(arg_names[:1] , __a)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
def check_hidden_states_output(__a , __a , __a):
__snake_case : str = model_class(__a)
__snake_case : List[Any] = model(**self._prepare_for_class(__a , __a) , training=__a)
__snake_case : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
__snake_case : Optional[Any] = getattr(
self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1)
self.assertEqual(len(__a) , __a)
if hasattr(self.model_tester , 'encoder_seq_length'):
__snake_case : List[Any] = self.model_tester.encoder_seq_length
if hasattr(self.model_tester , 'chunk_length') and self.model_tester.chunk_length > 1:
__snake_case : str = seq_length * self.model_tester.chunk_length
else:
__snake_case : Optional[int] = self.model_tester.seq_length
self.assertListEqual(
list(hidden_states[-1].shape[-2:]) , [seq_length, self.model_tester.hidden_size] , )
if config.is_encoder_decoder:
__snake_case : List[Any] = outputs.decoder_hidden_states
self.asseretIsInstance(__a , (list, tuple))
self.assertEqual(len(__a) , __a)
__snake_case : List[str] = getattr(self.model_tester , 'seq_length' , __a)
__snake_case : Tuple = getattr(self.model_tester , 'decoder_seq_length' , __a)
self.assertListEqual(
list(hidden_states[-1].shape[-2:]) , [decoder_seq_length, self.model_tester.hidden_size] , )
__snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case : List[str] = True
check_hidden_states_output(__a , __a , __a)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__snake_case : str = True
check_hidden_states_output(__a , __a , __a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a=False) -> int:
"""simple docstring"""
__snake_case : Optional[int] = super()._prepare_for_class(__a , __a , return_labels=__a)
if return_labels:
if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
del inputs_dict["labels"]
return inputs_dict
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
@unittest.skip(reason='EfficientFormer does not implement masked image modeling yet')
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*__a)
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*__a)
@slow
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__snake_case : Any = TFEfficientFormerModel.from_pretrained(__a)
self.assertIsNotNone(__a)
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case : Tuple = True
__snake_case : Optional[Any] = getattr(self.model_tester , 'seq_length' , __a)
__snake_case : List[Any] = getattr(self.model_tester , 'encoder_seq_length' , __a)
__snake_case : Tuple = getattr(self.model_tester , 'key_length' , __a)
__snake_case : Optional[Any] = getattr(self.model_tester , 'chunk_length' , __a)
if chunk_length is not None and hasattr(self.model_tester , 'num_hashes'):
__snake_case : str = encoder_seq_length * self.model_tester.num_hashes
for model_class in self.all_model_classes:
__snake_case : Optional[Any] = True
__snake_case : Dict = False
__snake_case : Optional[int] = True
__snake_case : Dict = model_class(__a)
__snake_case : Tuple = model(**self._prepare_for_class(__a , __a) , training=__a)
__snake_case : Union[str, Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(__a) , self.model_tester.num_attention_outputs)
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
__snake_case : Dict = True
__snake_case : str = model_class(__a)
__snake_case : str = model(**self._prepare_for_class(__a , __a) , training=__a)
__snake_case : Tuple = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(__a) , self.model_tester.num_attention_outputs)
if chunk_length is not None:
self.assertListEqual(
list(attentions[0].shape[-4:]) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , )
else:
self.assertListEqual(
list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , )
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case ,__snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
# Prepare our model
__snake_case : Tuple = model_class(__a)
# These are maximally general inputs for the model, with multiple None dimensions
# Hopefully this will catch any conditionals that fail for flexible shapes
__snake_case : Optional[Any] = {
key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=__a)
for key, val in model.input_signature.items()
if key in model.dummy_inputs
}
__snake_case : Tuple = model(__a)
self.assertTrue(outputs_dict is not None)
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
__snake_case : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_tf
@require_vision
class a_ ( unittest.TestCase ):
@cached_property
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return (
EfficientFormerImageProcessor.from_pretrained('snap-research/efficientformer-l1-300')
if is_vision_available()
else None
)
@slow
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case : List[str] = TFEfficientFormerForImageClassification.from_pretrained('snap-research/efficientformer-l1-300')
__snake_case : Optional[int] = self.default_image_processor
__snake_case : List[Any] = prepare_img()
__snake_case : List[Any] = image_processor(images=__a , return_tensors='tf')
# forward pass
__snake_case : List[str] = model(**__a , training=__a)
# verify the logits
__snake_case : str = tf.TensorShape((1, 1_0_0_0))
self.assertEqual(outputs.logits.shape , __a)
__snake_case : Any = tf.constant([-0.0_555, 0.4_825, -0.0_852])
self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4))
@slow
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[Any] = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
'snap-research/efficientformer-l1-300')
__snake_case : List[Any] = self.default_image_processor
__snake_case : Union[str, Any] = prepare_img()
__snake_case : List[Any] = image_processor(images=__a , return_tensors='tf')
# forward pass
__snake_case : Optional[int] = model(**__a , training=__a)
# verify the logits
__snake_case : Optional[int] = tf.TensorShape((1, 1_0_0_0))
self.assertEqual(outputs.logits.shape , __a)
__snake_case : List[str] = tf.constant([-0.1_312, 0.4_353, -1.0_499])
self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4)) | 61 | 0 |
'''simple docstring'''
from __future__ import annotations
import copy
import inspect
import unittest
import numpy as np
from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property
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 import (
TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
LayoutLMvaConfig,
TFLayoutLMvaForQuestionAnswering,
TFLayoutLMvaForSequenceClassification,
TFLayoutLMvaForTokenClassification,
TFLayoutLMvaModel,
)
if is_vision_available():
from PIL import Image
from transformers import LayoutLMvaImageProcessor
class a_ :
def __init__(self , __a , __a=2 , __a=3 , __a=4 , __a=2 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=9_9 , __a=3_6 , __a=2 , __a=4 , __a=3_7 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_1_2 , __a=1_6 , __a=2 , __a=0.02 , __a=6 , __a=6 , __a=3 , __a=4 , __a=None , __a=1_0_0_0 , ) -> Any:
"""simple docstring"""
__snake_case : Dict = parent
__snake_case : int = batch_size
__snake_case : List[Any] = num_channels
__snake_case : Optional[int] = image_size
__snake_case : Optional[int] = patch_size
__snake_case : Tuple = is_training
__snake_case : Optional[int] = use_input_mask
__snake_case : int = use_token_type_ids
__snake_case : str = use_labels
__snake_case : Dict = vocab_size
__snake_case : int = hidden_size
__snake_case : List[str] = num_hidden_layers
__snake_case : List[Any] = num_attention_heads
__snake_case : Optional[Any] = intermediate_size
__snake_case : Dict = hidden_act
__snake_case : Any = hidden_dropout_prob
__snake_case : str = attention_probs_dropout_prob
__snake_case : str = max_position_embeddings
__snake_case : List[Any] = type_vocab_size
__snake_case : Tuple = type_sequence_label_size
__snake_case : Optional[int] = initializer_range
__snake_case : str = coordinate_size
__snake_case : Tuple = shape_size
__snake_case : Any = num_labels
__snake_case : List[str] = num_choices
__snake_case : Tuple = scope
__snake_case : List[str] = range_bbox
# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
__snake_case : Union[str, Any] = text_seq_length
__snake_case : Optional[int] = (image_size // patch_size) ** 2 + 1
__snake_case : Optional[Any] = self.text_seq_length + self.image_seq_length
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : List[str] = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size)
__snake_case : Any = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox)
__snake_case : Union[str, Any] = bbox.numpy()
# Ensure that bbox is legal
for i in range(bbox.shape[0]):
for j in range(bbox.shape[1]):
if bbox[i, j, 3] < bbox[i, j, 1]:
__snake_case : int = bbox[i, j, 3]
__snake_case : int = bbox[i, j, 1]
__snake_case : Optional[Any] = tmp_coordinate
if bbox[i, j, 2] < bbox[i, j, 0]:
__snake_case : int = bbox[i, j, 2]
__snake_case : str = bbox[i, j, 0]
__snake_case : Union[str, Any] = tmp_coordinate
__snake_case : Any = tf.constant(lowerCAmelCase_)
__snake_case : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
__snake_case : Optional[Any] = None
if self.use_input_mask:
__snake_case : int = random_attention_mask([self.batch_size, self.text_seq_length])
__snake_case : Tuple = None
if self.use_token_type_ids:
__snake_case : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size)
__snake_case : Tuple = None
__snake_case : int = None
if self.use_labels:
__snake_case : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size)
__snake_case : Any = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels)
__snake_case : str = LayoutLMvaConfig(
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 , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , )
return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a , __a , __a) -> Any:
"""simple docstring"""
__snake_case : List[Any] = TFLayoutLMvaModel(config=lowerCAmelCase_)
# text + image
__snake_case : str = model(lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , training=lowerCAmelCase_)
__snake_case : str = model(
lowerCAmelCase_ , bbox=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , training=lowerCAmelCase_ , )
__snake_case : List[Any] = model(lowerCAmelCase_ , bbox=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , training=lowerCAmelCase_)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
# text only
__snake_case : Dict = model(lowerCAmelCase_ , training=lowerCAmelCase_)
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size))
# image only
__snake_case : Dict = model({'pixel_values': pixel_values} , training=lowerCAmelCase_)
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size))
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a , __a , __a , __a) -> List[str]:
"""simple docstring"""
__snake_case : Any = self.num_labels
__snake_case : Union[str, Any] = TFLayoutLMvaForSequenceClassification(config=lowerCAmelCase_)
__snake_case : List[str] = model(
lowerCAmelCase_ , bbox=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ , training=lowerCAmelCase_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a , __a , __a , __a) -> Union[str, Any]:
"""simple docstring"""
__snake_case : Any = self.num_labels
__snake_case : Any = TFLayoutLMvaForTokenClassification(config=lowerCAmelCase_)
__snake_case : Tuple = model(
lowerCAmelCase_ , bbox=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ , training=lowerCAmelCase_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels))
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a , __a , __a , __a) -> int:
"""simple docstring"""
__snake_case : Union[str, Any] = 2
__snake_case : int = TFLayoutLMvaForQuestionAnswering(config=lowerCAmelCase_)
__snake_case : Optional[Any] = model(
lowerCAmelCase_ , bbox=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , start_positions=lowerCAmelCase_ , end_positions=lowerCAmelCase_ , training=lowerCAmelCase_ , )
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 SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
__snake_case : Tuple = self.prepare_config_and_inputs()
((__snake_case) ,(__snake_case) ,(__snake_case) ,(__snake_case) ,(__snake_case) ,(__snake_case) ,(__snake_case) ,(__snake_case)) : Any = config_and_inputs
__snake_case : Tuple = {
'input_ids': input_ids,
'bbox': bbox,
'pixel_values': pixel_values,
'token_type_ids': token_type_ids,
'attention_mask': input_mask,
}
return config, inputs_dict
@require_tf
class a_ ( __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase ):
_snake_case = (
(
TFLayoutLMvaModel,
TFLayoutLMvaForQuestionAnswering,
TFLayoutLMvaForSequenceClassification,
TFLayoutLMvaForTokenClassification,
)
if is_tf_available()
else ()
)
_snake_case = (
{'''document-question-answering''': TFLayoutLMvaForQuestionAnswering, '''feature-extraction''': TFLayoutLMvaModel}
if is_tf_available()
else {}
)
_snake_case = False
_snake_case = False
_snake_case = False
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a , __a) -> Any:
"""simple docstring"""
return True
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a=False) -> dict:
"""simple docstring"""
__snake_case : Tuple = copy.deepcopy(lowerCAmelCase_)
if model_class in get_values(lowerCAmelCase_):
__snake_case : str = {
k: tf.tile(tf.expand_dims(lowerCAmelCase_ , 1) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1))
if isinstance(lowerCAmelCase_ , tf.Tensor) and v.ndim > 0
else v
for k, v in inputs_dict.items()
}
if return_labels:
if model_class in get_values(lowerCAmelCase_):
__snake_case : Union[str, Any] = tf.ones(self.model_tester.batch_size , dtype=tf.intaa)
elif model_class in get_values(lowerCAmelCase_):
__snake_case : List[str] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa)
__snake_case : List[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa)
elif model_class in get_values(lowerCAmelCase_):
__snake_case : str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa)
elif model_class in get_values(lowerCAmelCase_):
__snake_case : Any = tf.zeros(
(self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa)
return inputs_dict
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
__snake_case : Tuple = TFLayoutLMvaModelTester(self)
__snake_case : List[Any] = ConfigTester(self , config_class=lowerCAmelCase_ , hidden_size=3_7)
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case ,__snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case : Optional[Any] = model_class(lowerCAmelCase_)
if getattr(lowerCAmelCase_ , 'hf_compute_loss' , lowerCAmelCase_):
# The number of elements in the loss should be the same as the number of elements in the label
__snake_case : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowerCAmelCase_ , return_labels=lowerCAmelCase_)
__snake_case : Union[str, Any] = prepared_for_class[
sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=lowerCAmelCase_)[0]
]
__snake_case : Tuple = added_label.shape.as_list()[:1]
# Test that model correctly compute the loss with kwargs
__snake_case : Tuple = self._prepare_for_class(inputs_dict.copy() , lowerCAmelCase_ , return_labels=lowerCAmelCase_)
__snake_case : Tuple = prepared_for_class.pop('input_ids')
__snake_case : Dict = model(lowerCAmelCase_ , **lowerCAmelCase_)[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])
# Test that model correctly compute the loss when we mask some positions
__snake_case : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowerCAmelCase_ , return_labels=lowerCAmelCase_)
__snake_case : Optional[Any] = prepared_for_class.pop('input_ids')
if "labels" in prepared_for_class:
__snake_case : Optional[Any] = prepared_for_class['labels'].numpy()
if len(labels.shape) > 1 and labels.shape[1] != 1:
__snake_case : Any = -1_0_0
__snake_case : int = tf.convert_to_tensor(lowerCAmelCase_)
__snake_case : Optional[int] = model(lowerCAmelCase_ , **lowerCAmelCase_)[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])
self.assertTrue(not np.any(np.isnan(loss.numpy())))
# Test that model correctly compute the loss with a dict
__snake_case : Dict = self._prepare_for_class(inputs_dict.copy() , lowerCAmelCase_ , return_labels=lowerCAmelCase_)
__snake_case : List[str] = model(lowerCAmelCase_)[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])
# Test that model correctly compute the loss with a tuple
__snake_case : Optional[int] = self._prepare_for_class(inputs_dict.copy() , lowerCAmelCase_ , return_labels=lowerCAmelCase_)
# Get keys that were added with the _prepare_for_class function
__snake_case : Optional[int] = prepared_for_class.keys() - inputs_dict.keys()
__snake_case : str = inspect.signature(model.call).parameters
__snake_case : int = list(signature.keys())
# Create a dictionary holding the location of the tensors in the tuple
__snake_case : Any = {0: 'input_ids'}
for label_key in label_keys:
__snake_case : Optional[int] = signature_names.index(lowerCAmelCase_)
__snake_case : List[Any] = label_key
__snake_case : Optional[Any] = sorted(tuple_index_mapping.items())
# Initialize a list with their default values, update the values and convert to a tuple
__snake_case : Optional[Any] = []
for name in signature_names:
if name != "kwargs":
list_input.append(signature[name].default)
for index, value in sorted_tuple_index_mapping:
__snake_case : Tuple = prepared_for_class[value]
__snake_case : Optional[int] = tuple(lowerCAmelCase_)
# Send to model
__snake_case : Tuple = model(tuple_input[:-1])[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
(
(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,
) : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
(
(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,
) : Any = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
__snake_case : List[str] = type
self.model_tester.create_and_check_model(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_)
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
(
(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,
) : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_)
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
(
(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,
) : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_)
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
(
(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,(
__snake_case
) ,
) : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_)
@slow
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__snake_case : int = TFLayoutLMvaModel.from_pretrained(lowerCAmelCase_)
self.assertIsNotNone(lowerCAmelCase_)
def _SCREAMING_SNAKE_CASE ( ) -> str:
"""simple docstring"""
__snake_case : Any = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_tf
class a_ ( unittest.TestCase ):
@cached_property
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
return LayoutLMvaImageProcessor(apply_ocr=lowerCAmelCase_) if is_vision_available() else None
@slow
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case : Tuple = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base')
__snake_case : Dict = self.default_image_processor
__snake_case : str = prepare_img()
__snake_case : int = image_processor(images=lowerCAmelCase_ , return_tensors='tf').pixel_values
__snake_case : str = tf.constant([[1, 2]])
__snake_case : Optional[int] = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]]) , axis=0)
# forward pass
__snake_case : str = model(input_ids=lowerCAmelCase_ , bbox=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , training=lowerCAmelCase_)
# verify the logits
__snake_case : List[str] = (1, 1_9_9, 7_6_8)
self.assertEqual(outputs.last_hidden_state.shape , lowerCAmelCase_)
__snake_case : Any = tf.constant(
[[-0.0_529, 0.3_618, 0.1_632], [-0.1_587, -0.1_667, -0.0_400], [-0.1_557, -0.1_671, -0.0_505]])
self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , lowerCAmelCase_ , atol=1E-4)) | 716 |
'''simple docstring'''
__A = {str(digit): digit**5 for digit in range(1_0)}
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
return sum(DIGITS_FIFTH_POWER[digit] for digit in str(A ) )
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
return sum(
number
for number in range(10_00 , 1_00_00_00 )
if number == digits_fifth_powers_sum(A ) )
if __name__ == "__main__":
print(solution()) | 61 | 0 |
'''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_ :
def __init__(self , __a , __a , __a , __a , __a , __a , ) -> Union[str, Any]:
"""simple docstring"""
__snake_case : str = pos_x
__snake_case : int = pos_y
__snake_case : int = (pos_y, pos_x)
__snake_case : List[str] = goal_x
__snake_case : Tuple = goal_y
__snake_case : str = g_cost
__snake_case : Optional[Any] = parent
__snake_case : Dict = self.calculate_heuristic()
__snake_case : Dict = self.g_cost + self.h_cost
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case : Optional[Any] = self.pos_x - self.goal_x
__snake_case : List[Any] = self.pos_y - self.goal_y
if HEURISTIC == 1:
return abs(UpperCAmelCase__) + abs(UpperCAmelCase__)
else:
return sqrt(dy**2 + dx**2)
def __lt__(self , __a) -> str:
"""simple docstring"""
return self.f_cost < other.f_cost
class a_ :
def __init__(self , __a , __a) -> Dict:
"""simple docstring"""
__snake_case : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , UpperCAmelCase__)
__snake_case : Optional[Any] = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9_9_9_9 , UpperCAmelCase__)
__snake_case : Tuple = [self.start]
__snake_case : list[Node] = []
__snake_case : Tuple = False
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
while self.open_nodes:
# Open Nodes are sorted using __lt__
self.open_nodes.sort()
__snake_case : Tuple = self.open_nodes.pop(0)
if current_node.pos == self.target.pos:
return self.retrace_path(UpperCAmelCase__)
self.closed_nodes.append(UpperCAmelCase__)
__snake_case : str = self.get_successors(UpperCAmelCase__)
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(UpperCAmelCase__)
else:
# retrieve the best current path
__snake_case : Tuple = self.open_nodes.pop(self.open_nodes.index(UpperCAmelCase__))
if child_node.g_cost < better_node.g_cost:
self.open_nodes.append(UpperCAmelCase__)
else:
self.open_nodes.append(UpperCAmelCase__)
return [self.start.pos]
def SCREAMING_SNAKE_CASE__ (self , __a) -> Any:
"""simple docstring"""
__snake_case : Dict = []
for action in delta:
__snake_case : List[Any] = parent.pos_x + action[1]
__snake_case : int = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(UpperCAmelCase__) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(
UpperCAmelCase__ , UpperCAmelCase__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , UpperCAmelCase__ , ))
return successors
def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple:
"""simple docstring"""
__snake_case : Any = node
__snake_case : str = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x))
__snake_case : Dict = current_node.parent
path.reverse()
return path
class a_ :
def __init__(self , __a , __a) -> Optional[Any]:
"""simple docstring"""
__snake_case : str = AStar(UpperCAmelCase__ , UpperCAmelCase__)
__snake_case : str = AStar(UpperCAmelCase__ , UpperCAmelCase__)
__snake_case : Dict = False
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""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()
__snake_case : Dict = self.fwd_astar.open_nodes.pop(0)
__snake_case : Tuple = self.bwd_astar.open_nodes.pop(0)
if current_bwd_node.pos == current_fwd_node.pos:
return self.retrace_bidirectional_path(
UpperCAmelCase__ , UpperCAmelCase__)
self.fwd_astar.closed_nodes.append(UpperCAmelCase__)
self.bwd_astar.closed_nodes.append(UpperCAmelCase__)
__snake_case : int = current_bwd_node
__snake_case : Dict = current_fwd_node
__snake_case : List[Any] = {
self.fwd_astar: self.fwd_astar.get_successors(UpperCAmelCase__),
self.bwd_astar: self.bwd_astar.get_successors(UpperCAmelCase__),
}
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(UpperCAmelCase__)
else:
# retrieve the best current path
__snake_case : str = astar.open_nodes.pop(
astar.open_nodes.index(UpperCAmelCase__))
if child_node.g_cost < better_node.g_cost:
astar.open_nodes.append(UpperCAmelCase__)
else:
astar.open_nodes.append(UpperCAmelCase__)
return [self.fwd_astar.start.pos]
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> List[str]:
"""simple docstring"""
__snake_case : Union[str, Any] = self.fwd_astar.retrace_path(UpperCAmelCase__)
__snake_case : List[str] = self.bwd_astar.retrace_path(UpperCAmelCase__)
bwd_path.pop()
bwd_path.reverse()
__snake_case : str = 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''') | 717 |
'''simple docstring'''
from __future__ import annotations
from collections import deque
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any
@dataclass
class a_ :
_snake_case = 42
_snake_case = None
_snake_case = None
def _SCREAMING_SNAKE_CASE ( ) -> Node | None:
"""simple docstring"""
__snake_case : str = Node(1 )
__snake_case : Tuple = Node(2 )
__snake_case : Optional[int] = Node(3 )
__snake_case : List[str] = Node(4 )
__snake_case : List[str] = Node(5 )
return tree
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return [root.data, *preorder(root.left ), *preorder(root.right )] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return postorder(root.left ) + postorder(root.right ) + [root.data] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return [*inorder(root.left ), root.data, *inorder(root.right )] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> int:
"""simple docstring"""
return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
if root is None:
return output
__snake_case : Optional[int] = deque([root] )
while process_queue:
__snake_case : List[str] = process_queue.popleft()
output.append(node.data )
if node.left:
process_queue.append(node.left )
if node.right:
process_queue.append(node.right )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
def populate_output(A : Node | None , A : int ) -> None:
if not root:
return
if level == 1:
output.append(root.data )
elif level > 1:
populate_output(root.left , level - 1 )
populate_output(root.right , level - 1 )
populate_output(A , A )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
def populate_output(A : Node | None , A : int ) -> None:
if root is None:
return
if level == 1:
output.append(root.data )
elif level > 1:
populate_output(root.right , level - 1 )
populate_output(root.left , level - 1 )
populate_output(A , A )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None] | list[Any]:
"""simple docstring"""
if root is None:
return []
__snake_case : list[Sequence[Node | None]] = []
__snake_case : List[Any] = 0
__snake_case : int = height(A )
for h in range(1 , height_tree + 1 ):
if not flag:
output.append(get_nodes_from_left_to_right(A , A ) )
__snake_case : int = 1
else:
output.append(get_nodes_from_right_to_left(A , A ) )
__snake_case : Tuple = 0
return output
def _SCREAMING_SNAKE_CASE ( ) -> None: # Main function for testing.
"""simple docstring"""
__snake_case : Optional[int] = make_tree()
print(F"""In-order Traversal: {inorder(A )}""" )
print(F"""Pre-order Traversal: {preorder(A )}""" )
print(F"""Post-order Traversal: {postorder(A )}""" , '\n' )
print(F"""Height of Tree: {height(A )}""" , '\n' )
print('Complete Level Order Traversal: ' )
print(level_order(A ) , '\n' )
print('Level-wise order Traversal: ' )
for level in range(1 , height(A ) + 1 ):
print(F"""Level {level}:""" , get_nodes_from_left_to_right(A , level=A ) )
print('\nZigZag order Traversal: ' )
print(zigzag(A ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main() | 61 | 0 |
'''simple docstring'''
from .testing import (
are_the_same_tensors,
execute_subprocess_async,
require_bnb,
require_cpu,
require_cuda,
require_huggingface_suite,
require_mps,
require_multi_gpu,
require_multi_xpu,
require_safetensors,
require_single_gpu,
require_single_xpu,
require_torch_min_version,
require_tpu,
require_xpu,
skip,
slow,
)
from .training import RegressionDataset, RegressionModel, RegressionModelaXPU
from .scripts import test_script, test_sync, test_ops # isort: skip | 718 |
'''simple docstring'''
from __future__ import annotations
import math
import random
from collections.abc import Collection
from typing import overload
class a_ :
def __init__(self , __a = None) -> None:
"""simple docstring"""
if components is None:
__snake_case : List[str] = []
__snake_case : Optional[int] = list(__a)
def __len__(self) -> int:
"""simple docstring"""
return len(self.__components)
def __str__(self) -> str:
"""simple docstring"""
return "(" + ",".join(map(__a , self.__components)) + ")"
def __add__(self , __a) -> Vector:
"""simple docstring"""
__snake_case : Optional[Any] = len(self)
if size == len(__a):
__snake_case : Optional[int] = [self.__components[i] + other.component(__a) for i in range(__a)]
return Vector(__a)
else:
raise Exception('must have the same size')
def __sub__(self , __a) -> Vector:
"""simple docstring"""
__snake_case : Optional[Any] = len(self)
if size == len(__a):
__snake_case : Optional[int] = [self.__components[i] - other.component(__a) for i in range(__a)]
return Vector(__a)
else: # error case
raise Exception('must have the same size')
@overload
def __mul__(self , __a) -> Vector:
"""simple docstring"""
...
@overload
def __mul__(self , __a) -> float:
"""simple docstring"""
...
def __mul__(self , __a) -> float | Vector:
"""simple docstring"""
if isinstance(__a , (float, int)):
__snake_case : str = [c * other for c in self.__components]
return Vector(__a)
elif isinstance(__a , __a) and len(self) == len(__a):
__snake_case : List[Any] = len(self)
__snake_case : Dict = [self.__components[i] * other.component(__a) for i in range(__a)]
return sum(__a)
else: # error case
raise Exception('invalid operand!')
def SCREAMING_SNAKE_CASE__ (self) -> Vector:
"""simple docstring"""
return Vector(self.__components)
def SCREAMING_SNAKE_CASE__ (self , __a) -> float:
"""simple docstring"""
if isinstance(__a , __a) and -len(self.__components) <= i < len(self.__components):
return self.__components[i]
else:
raise Exception('index out of range')
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> None:
"""simple docstring"""
assert -len(self.__components) <= pos < len(self.__components)
__snake_case : int = value
def SCREAMING_SNAKE_CASE__ (self) -> float:
"""simple docstring"""
if len(self.__components) == 0:
raise Exception('Vector is empty')
__snake_case : Tuple = [c**2 for c in self.__components]
return math.sqrt(sum(__a))
def SCREAMING_SNAKE_CASE__ (self , __a , __a = False) -> float:
"""simple docstring"""
__snake_case : Tuple = self * other
__snake_case : Optional[int] = self.euclidean_length() * other.euclidean_length()
if deg:
return math.degrees(math.acos(num / den))
else:
return math.acos(num / den)
def _SCREAMING_SNAKE_CASE ( A : int ) -> Vector:
"""simple docstring"""
assert isinstance(A , A )
return Vector([0] * dimension )
def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> Vector:
"""simple docstring"""
assert isinstance(A , A ) and (isinstance(A , A ))
__snake_case : Any = [0] * dimension
__snake_case : int = 1
return Vector(A )
def _SCREAMING_SNAKE_CASE ( A : float , A : Vector , A : Vector ) -> Vector:
"""simple docstring"""
assert (
isinstance(A , A )
and isinstance(A , A )
and (isinstance(A , (int, float) ))
)
return x * scalar + y
def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int ) -> Vector:
"""simple docstring"""
random.seed(A )
__snake_case : List[Any] = [random.randint(A , A ) for _ in range(A )]
return Vector(A )
class a_ :
def __init__(self , __a , __a , __a) -> None:
"""simple docstring"""
__snake_case : Union[str, Any] = matrix
__snake_case : int = w
__snake_case : str = h
def __str__(self) -> str:
"""simple docstring"""
__snake_case : Dict = ''
for i in range(self.__height):
ans += "|"
for j in range(self.__width):
if j < self.__width - 1:
ans += str(self.__matrix[i][j]) + ","
else:
ans += str(self.__matrix[i][j]) + "|\n"
return ans
def __add__(self , __a) -> Matrix:
"""simple docstring"""
if self.__width == other.width() and self.__height == other.height():
__snake_case : Tuple = []
for i in range(self.__height):
__snake_case : List[Any] = [
self.__matrix[i][j] + other.component(__a , __a)
for j in range(self.__width)
]
matrix.append(__a)
return Matrix(__a , self.__width , self.__height)
else:
raise Exception('matrix must have the same dimension!')
def __sub__(self , __a) -> Matrix:
"""simple docstring"""
if self.__width == other.width() and self.__height == other.height():
__snake_case : str = []
for i in range(self.__height):
__snake_case : List[str] = [
self.__matrix[i][j] - other.component(__a , __a)
for j in range(self.__width)
]
matrix.append(__a)
return Matrix(__a , self.__width , self.__height)
else:
raise Exception('matrices must have the same dimension!')
@overload
def __mul__(self , __a) -> Matrix:
"""simple docstring"""
...
@overload
def __mul__(self , __a) -> Vector:
"""simple docstring"""
...
def __mul__(self , __a) -> Vector | Matrix:
"""simple docstring"""
if isinstance(__a , __a): # matrix-vector
if len(__a) == self.__width:
__snake_case : Tuple = zero_vector(self.__height)
for i in range(self.__height):
__snake_case : Union[str, Any] = [
self.__matrix[i][j] * other.component(__a)
for j in range(self.__width)
]
ans.change_component(__a , sum(__a))
return ans
else:
raise Exception(
'vector must have the same size as the '
'number of columns of the matrix!')
elif isinstance(__a , (int, float)): # matrix-scalar
__snake_case : str = [
[self.__matrix[i][j] * other for j in range(self.__width)]
for i in range(self.__height)
]
return Matrix(__a , self.__width , self.__height)
return None
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return self.__height
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return self.__width
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float:
"""simple docstring"""
if 0 <= x < self.__height and 0 <= y < self.__width:
return self.__matrix[x][y]
else:
raise Exception('change_component: indices out of bounds')
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> None:
"""simple docstring"""
if 0 <= x < self.__height and 0 <= y < self.__width:
__snake_case : List[Any] = value
else:
raise Exception('change_component: indices out of bounds')
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float:
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square')
__snake_case : List[Any] = self.__matrix[:x] + self.__matrix[x + 1 :]
for i in range(len(__a)):
__snake_case : Tuple = minor[i][:y] + minor[i][y + 1 :]
return Matrix(__a , self.__width - 1 , self.__height - 1).determinant()
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float:
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square')
if 0 <= x < self.__height and 0 <= y < self.__width:
return (-1) ** (x + y) * self.minor(__a , __a)
else:
raise Exception('Indices out of bounds')
def SCREAMING_SNAKE_CASE__ (self) -> float:
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square')
if self.__height < 1:
raise Exception('Matrix has no element')
elif self.__height == 1:
return self.__matrix[0][0]
elif self.__height == 2:
return (
self.__matrix[0][0] * self.__matrix[1][1]
- self.__matrix[0][1] * self.__matrix[1][0]
)
else:
__snake_case : Any = [
self.__matrix[0][y] * self.cofactor(0 , __a) for y in range(self.__width)
]
return sum(__a)
def _SCREAMING_SNAKE_CASE ( A : int ) -> Matrix:
"""simple docstring"""
__snake_case : list[list[float]] = [[0] * n for _ in range(A )]
return Matrix(A , A , A )
def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int , A : int ) -> Matrix:
"""simple docstring"""
random.seed(A )
__snake_case : list[list[float]] = [
[random.randint(A , A ) for _ in range(A )] for _ in range(A )
]
return Matrix(A , A , A ) | 61 | 0 |
'''simple docstring'''
import argparse
import torch
# Step 1. clone https://github.com/microsoft/unilm
# Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd
# Step 3. cd unilm
# Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink
# import classes
from unilm.wavlm.WavLM import WavLM as WavLMOrig
from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig
from transformers import WavLMConfig, WavLMModel, 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.grep_linear''': '''encoder.layers.*.attention.gru_rel_pos_linear''',
'''self_attn.relative_attention_bias''': '''encoder.layers.*.attention.rel_attn_embed''',
'''self_attn.grep_a''': '''encoder.layers.*.attention.gru_rel_pos_const''',
'''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''',
'''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''': '''ctc_proj''',
'''mask_emb''': '''masked_spec_embed''',
}
__A = [
'''ctc_proj''',
'''quantizer.weight_proj''',
'''quantizer.codevectors''',
'''project_q''',
'''project_hid''',
]
def _SCREAMING_SNAKE_CASE ( A : int , A : List[str] , A : Optional[Any] , A : int , A : Tuple ) -> Tuple:
"""simple docstring"""
for attribute in key.split('.' ):
__snake_case : str = getattr(__a , __a )
if weight_type is not None:
__snake_case : Dict = getattr(__a , __a ).shape
else:
__snake_case : Optional[int] = hf_pointer.shape
assert hf_shape == value.shape, (
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":
__snake_case : Union[str, Any] = value
elif weight_type == "weight_g":
__snake_case : Any = value
elif weight_type == "weight_v":
__snake_case : int = value
elif weight_type == "bias":
__snake_case : Union[str, Any] = value
else:
__snake_case : Any = value
logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" )
def _SCREAMING_SNAKE_CASE ( A : Dict , A : Union[str, Any] ) -> List[Any]:
"""simple docstring"""
__snake_case : Dict = []
__snake_case : List[str] = fairseq_model.state_dict()
__snake_case : Union[str, Any] = hf_model.feature_extractor
for name, value in fairseq_dict.items():
__snake_case : Tuple = False
if "conv_layers" in name:
load_conv_layer(
__a , __a , __a , __a , hf_model.config.feat_extract_norm == 'group' , )
__snake_case : Optional[int] = True
else:
for key, mapped_key in MAPPING.items():
if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]:
__snake_case : Optional[int] = True
if "*" in mapped_key:
__snake_case : Union[str, Any] = name.split(__a )[0].split('.' )[-2]
__snake_case : Dict = mapped_key.replace('*' , __a )
if "weight_g" in name:
__snake_case : List[Any] = 'weight_g'
elif "weight_v" in name:
__snake_case : Any = 'weight_v'
elif "bias" in name and "relative_attention_bias" not in name:
__snake_case : Tuple = 'bias'
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
__snake_case : List[str] = 'weight'
else:
__snake_case : List[str] = None
set_recursively(__a , __a , __a , __a , __a )
continue
if not is_used:
unused_weights.append(__a )
logger.warning(F"""Unused weights: {unused_weights}""" )
def _SCREAMING_SNAKE_CASE ( A : Any , A : str , A : Tuple , A : Optional[Any] , A : Optional[Any] ) -> int:
"""simple docstring"""
__snake_case : Optional[int] = full_name.split('conv_layers.' )[-1]
__snake_case : Dict = name.split('.' )
__snake_case : Union[str, Any] = int(items[0] )
__snake_case : Optional[int] = int(items[1] )
if type_id == 0:
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
F"""{full_name} has size {value.shape}, but"""
F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."""
)
__snake_case : Dict = value
logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
F"""{full_name} has size {value.shape}, but"""
F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."""
)
__snake_case : Optional[int] = 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:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"""
" found."
)
__snake_case : int = value
logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
F"""{full_name} has size {value.shape}, but"""
F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."""
)
__snake_case : Dict = value
logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
else:
unused_weights.append(__a )
@torch.no_grad()
def _SCREAMING_SNAKE_CASE ( A : List[Any] , A : Any , A : Union[str, Any]=None ) -> Any:
"""simple docstring"""
__snake_case : Tuple = torch.load(__a )
__snake_case : Any = WavLMConfigOrig(checkpoint['cfg'] )
__snake_case : Union[str, Any] = WavLMOrig(__a )
model.load_state_dict(checkpoint['model'] )
model.eval()
if config_path is not None:
__snake_case : Dict = WavLMConfig.from_pretrained(__a )
else:
__snake_case : str = WavLMConfig()
__snake_case : str = WavLMModel(__a )
recursively_load_weights(__a , __a )
hf_wavlm.save_pretrained(__a )
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('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
__A = parser.parse_args()
convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path) | 719 |
'''simple docstring'''
import contextlib
import importlib
import io
import unittest
import transformers
# Try to import everything from transformers to ensure every object can be loaded.
from transformers import * # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available
if is_torch_available():
from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification
if is_tf_available():
from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification
if is_flax_available():
from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification
__A = DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co
__A = '''main'''
# Default branch name
__A = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
__A = '''aaaaaaa'''
# This commit does not exist, so we should 404.
__A = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
__A = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''
@contextlib.contextmanager
def _SCREAMING_SNAKE_CASE ( ) -> List[Any]:
"""simple docstring"""
print('Welcome!' )
yield
print('Bye!' )
@contextlib.contextmanager
def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]:
"""simple docstring"""
print('Bonjour!' )
yield
print('Au revoir!' )
class a_ ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
assert transformers.__spec__ is not None
assert importlib.util.find_spec('transformers') is not None
class a_ ( unittest.TestCase ):
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> int:
"""simple docstring"""
with ContextManagers([]):
print('Transformers are awesome!')
# The print statement adds a new line at the end of the output
self.assertEqual(mock_stdout.getvalue() , 'Transformers are awesome!\n')
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]:
"""simple docstring"""
with ContextManagers([context_en()]):
print('Transformers are awesome!')
# The output should be wrapped with an English welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , 'Welcome!\nTransformers are awesome!\nBye!\n')
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple:
"""simple docstring"""
with ContextManagers([context_fr(), context_en()]):
print('Transformers are awesome!')
# The output should be wrapped with an English and French welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , 'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n')
@require_torch
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
self.assertEqual(find_labels(__a) , ['labels'])
self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label'])
self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions'])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , ['labels'])
@require_tf
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
self.assertEqual(find_labels(__a) , ['labels'])
self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label'])
self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions'])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , ['labels'])
@require_flax
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
self.assertEqual(find_labels(__a) , [])
self.assertEqual(find_labels(__a) , [])
self.assertEqual(find_labels(__a) , [])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , []) | 61 | 0 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
if not isinstance(A , A ):
raise TypeError('Input value must be an \'int\' type' )
__snake_case : Union[str, Any] = 0
while number:
position += 1
number >>= 1
return position
if __name__ == "__main__":
import doctest
doctest.testmod() | 720 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__A = {'''configuration_timm_backbone''': ['''TimmBackboneConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ['''TimmBackbone''']
if TYPE_CHECKING:
from .configuration_timm_backbone import TimmBackboneConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_timm_backbone import TimmBackbone
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 61 | 0 |
'''simple docstring'''
import argparse
import shlex
import runhouse as rh
if __name__ == "__main__":
# Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access
# setup instructions, if using on-demand hardware
# If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster
# If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster
# Throw an error if user passes both BYO and on-demand cluster args
# Otherwise, use default values
__A = argparse.ArgumentParser()
parser.add_argument('''--user''', type=str, default='''ubuntu''')
parser.add_argument('''--host''', type=str, default='''localhost''')
parser.add_argument('''--key_path''', type=str, default=None)
parser.add_argument('''--instance''', type=str, default='''V100:1''')
parser.add_argument('''--provider''', type=str, default='''cheapest''')
parser.add_argument('''--use_spot''', type=bool, default=False)
parser.add_argument('''--example''', type=str, default='''pytorch/text-generation/run_generation.py''')
__A , __A = parser.parse_known_args()
if args.host != "localhost":
if args.instance != "V100:1" or args.provider != "cheapest":
raise ValueError('''Cannot specify both BYO and on-demand cluster args''')
__A = rh.cluster(
name='''rh-cluster''', ips=[args.host], ssh_creds={'''ssh_user''': args.user, '''ssh_private_key''': args.key_path}
)
else:
__A = rh.cluster(
name='''rh-cluster''', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot
)
__A = args.example.rsplit('''/''', 1)[0]
# Set up remote environment
cluster.install_packages(['''pip:./''']) # Installs transformers from local source
# Note transformers is copied into the home directory on the remote machine, so we can install from there
cluster.run([f'''pip install -r transformers/examples/{example_dir}/requirements.txt'''])
cluster.run(['''pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117'''])
# Run example. You can bypass the CLI wrapper and paste your own code here.
cluster.run([f'''python transformers/examples/{args.example} {' '.join(shlex.quote(arg) for arg in unknown)}'''])
# Alternatively, we can just import and run a training function (especially if there's no wrapper CLI):
# from my_script... import train
# reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard']
# launch_train_gpu = rh.function(fn=train,
# system=gpu,
# reqs=reqs,
# name='train_bert_glue')
#
# We can pass in arguments just like we would to a function:
# launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16
# stream_logs=True) | 721 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
__snake_case : str = 1
for i in range(1 , num + 1 ):
fact *= i
return fact
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
__snake_case : Union[str, Any] = 0
while number > 0:
__snake_case : Dict = number % 10
sum_of_digits += last_digit
__snake_case : Union[str, Any] = number // 10 # Removing the last_digit from the given number
return sum_of_digits
def _SCREAMING_SNAKE_CASE ( A : int = 1_00 ) -> int:
"""simple docstring"""
__snake_case : List[Any] = factorial(A )
__snake_case : Dict = split_and_add(A )
return result
if __name__ == "__main__":
print(solution(int(input('''Enter the Number: ''').strip()))) | 61 | 0 |
'''simple docstring'''
import torch
from diffusers import StableDiffusionPipeline
__A = '''path-to-your-trained-model'''
__A = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to('''cuda''')
__A = '''A photo of sks dog in a bucket'''
__A = pipe(prompt, num_inference_steps=5_0, guidance_scale=7.5).images[0]
image.save('''dog-bucket.png''') | 700 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import ChineseCLIPImageProcessor
class a_ ( unittest.TestCase ):
def __init__(self , __a , __a=7 , __a=3 , __a=1_8 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=None , __a=True , __a=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __a=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __a=True , ) -> List[Any]:
"""simple docstring"""
__snake_case : Tuple = size if size is not None else {'height': 2_2_4, 'width': 2_2_4}
__snake_case : Any = crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8}
__snake_case : Optional[int] = parent
__snake_case : Dict = batch_size
__snake_case : str = num_channels
__snake_case : Optional[Any] = image_size
__snake_case : Optional[int] = min_resolution
__snake_case : Tuple = max_resolution
__snake_case : Optional[int] = do_resize
__snake_case : Optional[int] = size
__snake_case : Union[str, Any] = do_center_crop
__snake_case : List[Any] = crop_size
__snake_case : int = do_normalize
__snake_case : Optional[Any] = image_mean
__snake_case : str = image_std
__snake_case : Optional[Any] = do_convert_rgb
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_convert_rgb": self.do_convert_rgb,
}
def SCREAMING_SNAKE_CASE__ (self , __a=False , __a=False , __a=False) -> List[str]:
"""simple docstring"""
assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"
if equal_resolution:
__snake_case : Optional[int] = []
for i in range(self.batch_size):
image_inputs.append(
np.random.randint(
2_5_5 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta))
else:
__snake_case : Dict = []
for i in range(self.batch_size):
__snake_case ,__snake_case : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution) , 2)
image_inputs.append(np.random.randint(2_5_5 , size=(self.num_channels, width, height) , dtype=np.uinta))
if not numpify and not torchify:
# PIL expects the channel dimension as last dimension
__snake_case : int = [Image.fromarray(np.moveaxis(__a , 0 , -1)) for x in image_inputs]
if torchify:
__snake_case : List[Any] = [torch.from_numpy(__a) for x in image_inputs]
return image_inputs
@require_torch
@require_vision
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = ChineseCLIPImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Union[str, Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=__a)
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : int = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , 'do_resize'))
self.assertTrue(hasattr(__a , 'size'))
self.assertTrue(hasattr(__a , 'do_center_crop'))
self.assertTrue(hasattr(__a , 'center_crop'))
self.assertTrue(hasattr(__a , 'do_normalize'))
self.assertTrue(hasattr(__a , 'image_mean'))
self.assertTrue(hasattr(__a , 'image_std'))
self.assertTrue(hasattr(__a , 'do_convert_rgb'))
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'height': 2_2_4, 'width': 2_2_4})
self.assertEqual(image_processor.crop_size , {'height': 1_8, 'width': 1_8})
__snake_case : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4)
self.assertEqual(image_processor.size , {'shortest_edge': 4_2})
self.assertEqual(image_processor.crop_size , {'height': 8_4, 'width': 8_4})
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
__snake_case : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
__snake_case : int = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : List[Any] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
__snake_case : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=__a , numpify=__a)
for image in image_inputs:
self.assertIsInstance(__a , np.ndarray)
# Test not batched input
__snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : int = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Any = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
__snake_case : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__a , torchify=__a)
for image in image_inputs:
self.assertIsInstance(__a , torch.Tensor)
# Test not batched input
__snake_case : Any = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : Union[str, Any] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
@require_torch
@require_vision
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = ChineseCLIPImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[Any] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__a)
__snake_case : List[Any] = 3
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Any = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , 'do_resize'))
self.assertTrue(hasattr(__a , 'size'))
self.assertTrue(hasattr(__a , 'do_center_crop'))
self.assertTrue(hasattr(__a , 'center_crop'))
self.assertTrue(hasattr(__a , 'do_normalize'))
self.assertTrue(hasattr(__a , 'image_mean'))
self.assertTrue(hasattr(__a , 'image_std'))
self.assertTrue(hasattr(__a , 'do_convert_rgb'))
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
__snake_case : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
__snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.expected_encoded_image_num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : Optional[int] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.expected_encoded_image_num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , ) | 61 | 0 |
'''simple docstring'''
import argparse
import torch
from torch import nn
from transformers import MBartConfig, MBartForConditionalGeneration
def _SCREAMING_SNAKE_CASE ( A : int ) -> Any:
"""simple docstring"""
__snake_case : Optional[int] = [
'''encoder.version''',
'''decoder.version''',
'''model.encoder.version''',
'''model.decoder.version''',
'''_float_tensor''',
'''decoder.output_projection.weight''',
]
for k in ignore_keys:
state_dict.pop(lowerCamelCase_ , lowerCamelCase_ )
def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> int:
"""simple docstring"""
__snake_case : Dict = emb.weight.shape
__snake_case : Tuple = nn.Linear(lowerCamelCase_ , lowerCamelCase_ , bias=lowerCamelCase_ )
__snake_case : Tuple = emb.weight.data
return lin_layer
def _SCREAMING_SNAKE_CASE ( A : List[Any] , A : List[Any]="facebook/mbart-large-en-ro" , A : str=False , A : int=False ) -> Tuple:
"""simple docstring"""
__snake_case : int = torch.load(lowerCamelCase_ , map_location='cpu' )['''model''']
remove_ignore_keys_(lowerCamelCase_ )
__snake_case : int = state_dict['''encoder.embed_tokens.weight'''].shape[0]
__snake_case : str = MBartConfig.from_pretrained(lowerCamelCase_ , vocab_size=lowerCamelCase_ )
if mbart_aa and finetuned:
__snake_case : List[Any] = '''relu'''
__snake_case : Dict = state_dict['''decoder.embed_tokens.weight''']
__snake_case : Any = MBartForConditionalGeneration(lowerCamelCase_ )
model.model.load_state_dict(lowerCamelCase_ )
if finetuned:
__snake_case : Dict = make_linear_from_emb(model.model.shared )
return model
if __name__ == "__main__":
__A = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.'''
)
parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument(
'''--hf_config''',
default='''facebook/mbart-large-cc25''',
type=str,
help='''Which huggingface architecture to use: mbart-large''',
)
parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''')
parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''')
__A = parser.parse_args()
__A = convert_fairseq_mbart_checkpoint_from_disk(
args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa
)
model.save_pretrained(args.pytorch_dump_folder_path) | 701 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json''',
# See all ViT MSN models at https://huggingface.co/models?filter=vit_msn
}
class a_ ( UpperCamelCase_ ):
_snake_case = """vit_msn"""
def __init__(self , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-06 , __a=2_2_4 , __a=1_6 , __a=3 , __a=True , **__a , ) -> Any:
"""simple docstring"""
super().__init__(**__a)
__snake_case : List[str] = hidden_size
__snake_case : Optional[int] = num_hidden_layers
__snake_case : Optional[Any] = num_attention_heads
__snake_case : str = intermediate_size
__snake_case : List[str] = hidden_act
__snake_case : List[Any] = hidden_dropout_prob
__snake_case : Tuple = attention_probs_dropout_prob
__snake_case : List[str] = initializer_range
__snake_case : Optional[int] = layer_norm_eps
__snake_case : Dict = image_size
__snake_case : int = patch_size
__snake_case : Dict = num_channels
__snake_case : Tuple = qkv_bias | 61 | 0 |
'''simple docstring'''
import json
import os
import subprocess
import unittest
from ast import literal_eval
import pytest
from parameterized import parameterized, parameterized_class
from . import is_sagemaker_available
if is_sagemaker_available():
from sagemaker import Session, TrainingJobAnalytics
from sagemaker.huggingface import HuggingFace
@pytest.mark.skipif(
literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""" ) ) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , )
@pytest.mark.usefixtures("""sm_env""" )
@parameterized_class(
[
{
"""framework""": """pytorch""",
"""script""": """run_glue.py""",
"""model_name_or_path""": """distilbert-base-cased""",
"""instance_type""": """ml.p3.16xlarge""",
"""results""": {"""train_runtime""": 650, """eval_accuracy""": 0.7, """eval_loss""": 0.6},
},
{
"""framework""": """pytorch""",
"""script""": """run_ddp.py""",
"""model_name_or_path""": """distilbert-base-cased""",
"""instance_type""": """ml.p3.16xlarge""",
"""results""": {"""train_runtime""": 600, """eval_accuracy""": 0.7, """eval_loss""": 0.6},
},
{
"""framework""": """tensorflow""",
"""script""": """run_tf_dist.py""",
"""model_name_or_path""": """distilbert-base-cased""",
"""instance_type""": """ml.p3.16xlarge""",
"""results""": {"""train_runtime""": 600, """eval_accuracy""": 0.6, """eval_loss""": 0.7},
},
] )
class a_ ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
if self.framework == "pytorch":
subprocess.run(
F"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split() , encoding='utf-8' , check=_lowercase , )
assert hasattr(self , 'env')
def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]:
"""simple docstring"""
__snake_case : str = F"""{self.env.base_job_name}-{instance_count}-{"ddp" if "ddp" in self.script else "smd"}"""
# distributed data settings
__snake_case : Dict = {'smdistributed': {'dataparallel': {'enabled': True}}} if self.script != 'run_ddp.py' else None
# creates estimator
return HuggingFace(
entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=_lowercase , instance_count=_lowercase , instance_type=self.instance_type , debugger_hook_config=_lowercase , hyperparameters={**self.env.distributed_hyperparameters, 'model_name_or_path': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=_lowercase , py_version='py36' , )
def SCREAMING_SNAKE_CASE__ (self , __a) -> Union[str, Any]:
"""simple docstring"""
TrainingJobAnalytics(_lowercase).export_csv(F"""{self.env.test_path}/{job_name}_metrics.csv""")
@parameterized.expand([(2,)])
def SCREAMING_SNAKE_CASE__ (self , __a) -> str:
"""simple docstring"""
__snake_case : Optional[int] = self.create_estimator(_lowercase)
# run training
estimator.fit()
# result dataframe
__snake_case : Optional[Any] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe()
# extract kpis
__snake_case : Tuple = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value'])
__snake_case : int = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value'])
# get train time from SageMaker job, this includes starting, preprocessing, stopping
__snake_case : int = (
Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' , 9_9_9_9_9_9)
)
# assert kpis
assert train_runtime <= self.results["train_runtime"]
assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy)
assert all(t <= self.results['eval_loss'] for t in eval_loss)
# dump tests result into json file to share in PR
with open(F"""{estimator.latest_training_job.name}.json""" , 'w') as outfile:
json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} , _lowercase) | 702 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : float , A : list[float] ) -> float:
"""simple docstring"""
if discount_rate < 0:
raise ValueError('Discount rate cannot be negative' )
if not cash_flows:
raise ValueError('Cash flows list cannot be empty' )
__snake_case : List[str] = sum(
cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(A ) )
return round(A , ndigits=2 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 61 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import _LazyModule
__A = {'''tokenization_wav2vec2_phoneme''': ['''Wav2Vec2PhonemeCTCTokenizer''']}
if TYPE_CHECKING:
from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 703 |
'''simple docstring'''
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__) | 61 | 0 |
'''simple docstring'''
import argparse
import json
from pathlib import Path
import requests
import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification
def _SCREAMING_SNAKE_CASE ( A : Dict ) -> List[Any]:
"""simple docstring"""
__snake_case : List[Any] = SwinvaConfig()
__snake_case : List[Any] = swinva_name.split('_' )
__snake_case : Tuple = name_split[1]
if "to" in name_split[3]:
__snake_case : Dict = int(name_split[3][-3:] )
else:
__snake_case : Union[str, Any] = int(name_split[3] )
if "to" in name_split[2]:
__snake_case : str = int(name_split[2][-2:] )
else:
__snake_case : int = int(name_split[2][6:] )
if model_size == "tiny":
__snake_case : Union[str, Any] = 96
__snake_case : List[Any] = (2, 2, 6, 2)
__snake_case : Tuple = (3, 6, 12, 24)
elif model_size == "small":
__snake_case : Any = 96
__snake_case : Dict = (2, 2, 18, 2)
__snake_case : int = (3, 6, 12, 24)
elif model_size == "base":
__snake_case : Union[str, Any] = 1_28
__snake_case : List[str] = (2, 2, 18, 2)
__snake_case : Union[str, Any] = (4, 8, 16, 32)
else:
__snake_case : Dict = 1_92
__snake_case : str = (2, 2, 18, 2)
__snake_case : Dict = (6, 12, 24, 48)
if "to" in swinva_name:
__snake_case : Any = (12, 12, 12, 6)
if ("22k" in swinva_name) and ("to" not in swinva_name):
__snake_case : List[str] = 2_18_41
__snake_case : Optional[int] = 'huggingface/label-files'
__snake_case : int = 'imagenet-22k-id2label.json'
__snake_case : List[str] = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) )
__snake_case : List[str] = {int(A ): v for k, v in idalabel.items()}
__snake_case : Optional[int] = idalabel
__snake_case : Dict = {v: k for k, v in idalabel.items()}
else:
__snake_case : Optional[Any] = 10_00
__snake_case : Optional[Any] = 'huggingface/label-files'
__snake_case : List[str] = 'imagenet-1k-id2label.json'
__snake_case : Optional[Any] = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) )
__snake_case : Union[str, Any] = {int(A ): v for k, v in idalabel.items()}
__snake_case : Dict = idalabel
__snake_case : Union[str, Any] = {v: k for k, v in idalabel.items()}
__snake_case : Tuple = img_size
__snake_case : Tuple = num_classes
__snake_case : Union[str, Any] = embed_dim
__snake_case : Optional[int] = depths
__snake_case : Dict = num_heads
__snake_case : Tuple = window_size
return config
def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
if "patch_embed.proj" in name:
__snake_case : Union[str, Any] = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' )
if "patch_embed.norm" in name:
__snake_case : str = name.replace('patch_embed.norm' , 'embeddings.norm' )
if "layers" in name:
__snake_case : List[Any] = 'encoder.' + name
if "attn.proj" in name:
__snake_case : Optional[Any] = name.replace('attn.proj' , 'attention.output.dense' )
if "attn" in name:
__snake_case : Dict = name.replace('attn' , 'attention.self' )
if "norm1" in name:
__snake_case : Tuple = name.replace('norm1' , 'layernorm_before' )
if "norm2" in name:
__snake_case : Optional[Any] = name.replace('norm2' , 'layernorm_after' )
if "mlp.fc1" in name:
__snake_case : str = name.replace('mlp.fc1' , 'intermediate.dense' )
if "mlp.fc2" in name:
__snake_case : Union[str, Any] = name.replace('mlp.fc2' , 'output.dense' )
if "q_bias" in name:
__snake_case : Dict = name.replace('q_bias' , 'query.bias' )
if "k_bias" in name:
__snake_case : Union[str, Any] = name.replace('k_bias' , 'key.bias' )
if "v_bias" in name:
__snake_case : Optional[Any] = name.replace('v_bias' , 'value.bias' )
if "cpb_mlp" in name:
__snake_case : Any = name.replace('cpb_mlp' , 'continuous_position_bias_mlp' )
if name == "norm.weight":
__snake_case : List[Any] = 'layernorm.weight'
if name == "norm.bias":
__snake_case : Optional[Any] = 'layernorm.bias'
if "head" in name:
__snake_case : List[str] = name.replace('head' , 'classifier' )
else:
__snake_case : Tuple = 'swinv2.' + name
return name
def _SCREAMING_SNAKE_CASE ( A : Optional[int] , A : Union[str, Any] ) -> List[str]:
"""simple docstring"""
for key in orig_state_dict.copy().keys():
__snake_case : int = orig_state_dict.pop(A )
if "mask" in key:
continue
elif "qkv" in key:
__snake_case : str = key.split('.' )
__snake_case : List[Any] = int(key_split[1] )
__snake_case : Tuple = int(key_split[3] )
__snake_case : Any = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size
if "weight" in key:
__snake_case : int = val[:dim, :]
__snake_case : List[str] = val[dim : dim * 2, :]
__snake_case : Tuple = val[-dim:, :]
else:
__snake_case : Optional[Any] = val[:dim]
__snake_case : Dict = val[
dim : dim * 2
]
__snake_case : str = val[-dim:]
else:
__snake_case : Optional[Any] = val
return orig_state_dict
def _SCREAMING_SNAKE_CASE ( A : int , A : Optional[Any] ) -> Any:
"""simple docstring"""
__snake_case : int = timm.create_model(A , pretrained=A )
timm_model.eval()
__snake_case : Any = get_swinva_config(A )
__snake_case : List[Any] = SwinvaForImageClassification(A )
model.eval()
__snake_case : List[str] = convert_state_dict(timm_model.state_dict() , A )
model.load_state_dict(A )
__snake_case : Optional[Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg'
__snake_case : str = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swinva_name.replace('_' , '-' ) ) )
__snake_case : int = Image.open(requests.get(A , stream=A ).raw )
__snake_case : Optional[Any] = image_processor(images=A , return_tensors='pt' )
__snake_case : Optional[Any] = timm_model(inputs['pixel_values'] )
__snake_case : str = model(**A ).logits
assert torch.allclose(A , A , atol=1e-3 )
print(F"""Saving model {swinva_name} to {pytorch_dump_folder_path}""" )
model.save_pretrained(A )
print(F"""Saving image processor to {pytorch_dump_folder_path}""" )
image_processor.save_pretrained(A )
model.push_to_hub(
repo_path_or_name=Path(A , A ) , organization='nandwalritik' , commit_message='Add model' , )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--swinv2_name''',
default='''swinv2_tiny_patch4_window8_256''',
type=str,
help='''Name of the Swinv2 timm model you\'d like to convert.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
)
__A = parser.parse_args()
convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path) | 704 |
'''simple docstring'''
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run
import sys
import warnings
from os.path import abspath, dirname, join
# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
__A = abspath(join(dirname(dirname(__file__)), '''src'''))
sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='''ignore''', category=FutureWarning)
def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> str:
"""simple docstring"""
from diffusers.utils.testing_utils import pytest_addoption_shared
pytest_addoption_shared(A )
def _SCREAMING_SNAKE_CASE ( A : int ) -> Optional[int]:
"""simple docstring"""
from diffusers.utils.testing_utils import pytest_terminal_summary_main
__snake_case : Any = terminalreporter.config.getoption('--make-reports' )
if make_reports:
pytest_terminal_summary_main(A , id=A ) | 61 | 0 |
'''simple docstring'''
import logging
import os
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import List, Optional
import faiss
import torch
from datasets import Features, Sequence, Value, load_dataset
from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser
__A = logging.getLogger(__name__)
torch.set_grad_enabled(False)
__A = 'cuda' if torch.cuda.is_available() else 'cpu'
def _SCREAMING_SNAKE_CASE ( A : str , A : List[Any]=1_00 , A : Union[str, Any]=" " ) -> List[str]:
"""simple docstring"""
__snake_case : Optional[int] = text.split(_lowerCamelCase )
return [character.join(text[i : i + n] ).strip() for i in range(0 , len(_lowerCamelCase ) , _lowerCamelCase )]
def _SCREAMING_SNAKE_CASE ( A : dict ) -> dict:
"""simple docstring"""
__snake_case : str = [], []
for title, text in zip(documents['title'] , documents['text'] ):
if text is not None:
for passage in split_text(_lowerCamelCase ):
titles.append(title if title is not None else '' )
texts.append(_lowerCamelCase )
return {"title": titles, "text": texts}
def _SCREAMING_SNAKE_CASE ( A : dict , A : DPRContextEncoder , A : DPRContextEncoderTokenizerFast ) -> dict:
"""simple docstring"""
__snake_case : str = ctx_tokenizer(
documents['title'] , documents['text'] , truncation=_lowerCamelCase , padding='longest' , return_tensors='pt' )["input_ids"]
__snake_case : int = ctx_encoder(input_ids.to(device=_lowerCamelCase ) , return_dict=_lowerCamelCase ).pooler_output
return {"embeddings": embeddings.detach().cpu().numpy()}
def _SCREAMING_SNAKE_CASE ( A : "RagExampleArguments" , A : "ProcessingArguments" , A : "IndexHnswArguments" , ) -> Dict:
"""simple docstring"""
logger.info('Step 1 - Create the dataset' )
######################################
# The dataset needed for RAG must have three columns:
# - title (string): title of the document
# - text (string): text of a passage of the document
# - embeddings (array of dimension d): DPR representation of the passage
# Let's say you have documents in tab-separated csv files with columns "title" and "text"
assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file"
# You can load a Dataset object this way
__snake_case : str = load_dataset(
'csv' , data_files=[rag_example_args.csv_path] , split='train' , delimiter='\t' , column_names=['title', 'text'] )
# More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files
# Then split the documents into passages of 100 words
__snake_case : str = dataset.map(_lowerCamelCase , batched=_lowerCamelCase , num_proc=processing_args.num_proc )
# And compute the embeddings
__snake_case : Optional[Any] = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=_lowerCamelCase )
__snake_case : Optional[int] = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name )
__snake_case : str = Features(
{'text': Value('string' ), 'title': Value('string' ), 'embeddings': Sequence(Value('float32' ) )} ) # optional, save as float32 instead of float64 to save space
__snake_case : Union[str, Any] = dataset.map(
partial(_lowerCamelCase , ctx_encoder=_lowerCamelCase , ctx_tokenizer=_lowerCamelCase ) , batched=_lowerCamelCase , batch_size=processing_args.batch_size , features=_lowerCamelCase , )
# And finally save your dataset
__snake_case : Any = os.path.join(rag_example_args.output_dir , 'my_knowledge_dataset' )
dataset.save_to_disk(_lowerCamelCase )
# from datasets import load_from_disk
# dataset = load_from_disk(passages_path) # to reload the dataset
######################################
logger.info('Step 2 - Index the dataset' )
######################################
# Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search
__snake_case : str = faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT )
dataset.add_faiss_index('embeddings' , custom_index=_lowerCamelCase )
# And save the index
__snake_case : Optional[int] = os.path.join(rag_example_args.output_dir , 'my_knowledge_dataset_hnsw_index.faiss' )
dataset.get_index('embeddings' ).save(_lowerCamelCase )
# dataset.load_faiss_index("embeddings", index_path) # to reload the index
@dataclass
class a_ :
_snake_case = field(
default=str(Path(__lowercase ).parent / """test_run""" / """dummy-kb""" / """my_knowledge_dataset.csv""" ) , metadata={"""help""": """Path to a tab-separated csv file with columns \'title\' and \'text\'"""} , )
_snake_case = field(
default=__lowercase , metadata={"""help""": """Question that is passed as input to RAG. Default is \'What does Moses\' rod turn into ?\'."""} , )
_snake_case = field(
default="""facebook/rag-sequence-nq""" , metadata={"""help""": """The RAG model to use. Either \'facebook/rag-sequence-nq\' or \'facebook/rag-token-nq\'"""} , )
_snake_case = field(
default="""facebook/dpr-ctx_encoder-multiset-base""" , metadata={
"""help""": (
"""The DPR context encoder model to use. Either \'facebook/dpr-ctx_encoder-single-nq-base\' or"""
""" \'facebook/dpr-ctx_encoder-multiset-base\'"""
)
} , )
_snake_case = field(
default=str(Path(__lowercase ).parent / """test_run""" / """dummy-kb""" ) , metadata={"""help""": """Path to a directory where the dataset passages and the index will be saved"""} , )
@dataclass
class a_ :
_snake_case = field(
default=__lowercase , metadata={
"""help""": """The number of processes to use to split the documents into passages. Default is single process."""
} , )
_snake_case = field(
default=16 , metadata={
"""help""": """The batch size to use when computing the passages embeddings using the DPR context encoder."""
} , )
@dataclass
class a_ :
_snake_case = field(
default=768 , metadata={"""help""": """The dimension of the embeddings to pass to the HNSW Faiss index."""} , )
_snake_case = field(
default=128 , metadata={
"""help""": (
"""The number of bi-directional links created for every new element during the HNSW index construction."""
)
} , )
if __name__ == "__main__":
logging.basicConfig(level=logging.WARNING)
logger.setLevel(logging.INFO)
__A = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments))
__A = parser.parse_args_into_dataclasses()
with TemporaryDirectory() as tmp_dir:
__A = rag_example_args.output_dir or tmp_dir
main(rag_example_args, processing_args, index_hnsw_args)
| 705 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
__A = {
'''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''],
'''tokenization_biogpt''': ['''BioGptTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''BioGptForCausalLM''',
'''BioGptForTokenClassification''',
'''BioGptForSequenceClassification''',
'''BioGptModel''',
'''BioGptPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig
from .tokenization_biogpt import BioGptTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_biogpt import (
BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST,
BioGptForCausalLM,
BioGptForSequenceClassification,
BioGptForTokenClassification,
BioGptModel,
BioGptPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 61 | 0 |
'''simple docstring'''
import timeit
import numpy as np
import datasets
from datasets.arrow_writer import ArrowWriter
from datasets.features.features import _ArrayXD
def _SCREAMING_SNAKE_CASE ( A : Dict ) -> str:
"""simple docstring"""
def wrapper(*A : Union[str, Any] , **A : Any ):
__snake_case : Union[str, Any] = timeit.default_timer()
__snake_case : str = func(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
__snake_case : int = timeit.default_timer() - starttime
return delta
__snake_case : str = func.__name__
return wrapper
def _SCREAMING_SNAKE_CASE ( A : dict , A : Optional[int]=1_00 , A : Optional[Any]=None ) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[int] = []
__snake_case : Tuple = seq_shapes or {}
for i in range(_SCREAMING_SNAKE_CASE ):
__snake_case : Optional[int] = {}
for col_id, (k, v) in enumerate(features.items() ):
if isinstance(_SCREAMING_SNAKE_CASE , _ArrayXD ):
__snake_case : Any = np.random.rand(*v.shape ).astype(v.dtype )
elif isinstance(_SCREAMING_SNAKE_CASE , datasets.Value ):
if v.dtype == "string":
__snake_case : str = 'The small grey turtle was surprisingly fast when challenged.'
else:
__snake_case : int = np.random.randint(10 , size=1 ).astype(v.dtype ).item()
elif isinstance(_SCREAMING_SNAKE_CASE , datasets.Sequence ):
while isinstance(_SCREAMING_SNAKE_CASE , datasets.Sequence ):
__snake_case : Tuple = v.feature
__snake_case : Tuple = seq_shapes[k]
__snake_case : List[Any] = np.random.rand(*_SCREAMING_SNAKE_CASE ).astype(v.dtype )
__snake_case : Any = data
dummy_data.append((i, example) )
return dummy_data
def _SCREAMING_SNAKE_CASE ( A : List[Any] , A : Optional[Any] , A : Union[str, Any]=1_00 , A : Optional[Any]=None ) -> Optional[Any]:
"""simple docstring"""
__snake_case : str = generate_examples(_SCREAMING_SNAKE_CASE , num_examples=_SCREAMING_SNAKE_CASE , seq_shapes=_SCREAMING_SNAKE_CASE )
with ArrowWriter(features=_SCREAMING_SNAKE_CASE , path=_SCREAMING_SNAKE_CASE ) as writer:
for key, record in dummy_data:
__snake_case : Dict = features.encode_example(_SCREAMING_SNAKE_CASE )
writer.write(_SCREAMING_SNAKE_CASE )
__snake_case ,__snake_case : int = writer.finalize()
if not num_final_examples == num_examples:
raise ValueError(
F"""Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.""" )
__snake_case : Optional[int] = datasets.Dataset.from_file(filename=_SCREAMING_SNAKE_CASE , info=datasets.DatasetInfo(features=_SCREAMING_SNAKE_CASE ) )
return dataset | 706 |
'''simple docstring'''
from packaging import version
from .import_utils import is_accelerate_available
if is_accelerate_available():
import accelerate
def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> int:
"""simple docstring"""
if not is_accelerate_available():
return method
__snake_case : Optional[Any] = version.parse(accelerate.__version__ ).base_version
if version.parse(A ) < version.parse('0.17.0' ):
return method
def wrapper(self : Optional[Any] , *A : Optional[Any] , **A : Optional[int] ):
if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ):
self._hf_hook.pre_forward(self )
return method(self , *A , **A )
return wrapper | 61 | 0 |
'''simple docstring'''
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxSeqaSeqConfigWithPast
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'''google/umt5-small''': '''https://huggingface.co/google/umt5-small/resolve/main/config.json''',
# See all umt5 models at https://huggingface.co/models?filter=umt5
}
class a_ ( A_ ):
_snake_case = '''umt5'''
_snake_case = ['''past_key_values''']
def __init__(self , __a=2_5_0_1_1_2 , __a=5_1_2 , __a=6_4 , __a=1_0_2_4 , __a=8 , __a=None , __a=6 , __a=3_2 , __a=1_2_8 , __a=0.1 , __a=1E-6 , __a=1.0 , __a="gated-gelu" , __a=True , __a=True , __a="T5Tokenizer" , __a=True , __a=0 , __a=1 , __a=0 , **__a , ) -> Tuple:
"""simple docstring"""
super().__init__(
is_encoder_decoder=__a , tokenizer_class=__a , tie_word_embeddings=__a , pad_token_id=__a , eos_token_id=__a , decoder_start_token_id=__a , **__a , )
__snake_case : Optional[int] = vocab_size
__snake_case : Dict = d_model
__snake_case : Any = d_kv
__snake_case : Optional[int] = d_ff
__snake_case : List[str] = num_layers
__snake_case : Any = (
num_decoder_layers if num_decoder_layers is not None else self.num_layers
) # default = symmetry
__snake_case : List[str] = num_heads
__snake_case : Tuple = relative_attention_num_buckets
__snake_case : Union[str, Any] = relative_attention_max_distance
__snake_case : str = dropout_rate
__snake_case : List[str] = layer_norm_epsilon
__snake_case : Tuple = initializer_factor
__snake_case : Tuple = feed_forward_proj
__snake_case : Dict = use_cache
__snake_case : Dict = self.feed_forward_proj.split('-')
__snake_case : List[str] = act_info[-1]
__snake_case : Any = act_info[0] == """gated"""
if len(__a) > 1 and act_info[0] != "gated" or len(__a) > 2:
raise ValueError(
F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."""
'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '
'\'gated-gelu\' or \'relu\'')
if feed_forward_proj == "gated-gelu":
__snake_case : Optional[int] = """gelu_new"""
@property
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
return self.d_model
@property
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
return self.num_heads
@property
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
return self.num_layers
class a_ ( A_ ):
@property
# Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : int = {
"""input_ids""": {0: """batch""", 1: """encoder_sequence"""},
"""attention_mask""": {0: """batch""", 1: """encoder_sequence"""},
}
if self.use_past:
__snake_case : Optional[int] = """past_encoder_sequence + sequence"""
__snake_case : Optional[int] = {0: """batch"""}
__snake_case : Tuple = {0: """batch""", 1: """past_decoder_sequence + sequence"""}
else:
__snake_case : Any = {0: """batch""", 1: """decoder_sequence"""}
__snake_case : List[str] = {0: """batch""", 1: """decoder_sequence"""}
if self.use_past:
self.fill_with_past_key_values_(__a , direction='inputs')
return common_inputs
@property
# Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
return 1_3
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
return 5E-4 | 707 |
'''simple docstring'''
import unittest
from transformers import load_tool
from transformers.utils import is_torch_available
if is_torch_available():
import torch
from transformers.testing_utils import require_torch
from .test_tools_common import ToolTesterMixin
@require_torch
class a_ ( unittest.TestCase , UpperCamelCase_ ):
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[str] = load_tool('text-to-speech')
self.tool.setup()
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : Dict = self.tool('hey')
__snake_case : List[Any] = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , ))
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : Any = self.tool('hey')
__snake_case : Any = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , )) | 61 | 0 |
'''simple docstring'''
import functools
from typing import Any
def _SCREAMING_SNAKE_CASE ( A : str , A : list[str] ) -> str:
"""simple docstring"""
if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) or len(lowerCAmelCase__ ) == 0:
raise ValueError('the string should be not empty string' )
if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) or not all(
isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and len(lowerCAmelCase__ ) > 0 for item in words ):
raise ValueError('the words should be a list of non-empty strings' )
# Build trie
__snake_case : dict[str, Any] = {}
__snake_case : Dict = 'WORD_KEEPER'
for word in words:
__snake_case : List[Any] = trie
for c in word:
if c not in trie_node:
__snake_case : str = {}
__snake_case : Any = trie_node[c]
__snake_case : Optional[int] = True
__snake_case : List[str] = len(lowerCAmelCase__ )
# Dynamic programming method
@functools.cache
def is_breakable(A : int ) -> bool:
if index == len_string:
return True
__snake_case : Tuple = trie
for i in range(lowerCAmelCase__ , lowerCAmelCase__ ):
__snake_case : Dict = trie_node.get(string[i] , lowerCAmelCase__ )
if trie_node is None:
return False
if trie_node.get(lowerCAmelCase__ , lowerCAmelCase__ ) and is_breakable(i + 1 ):
return True
return False
return is_breakable(0 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 708 |
'''simple docstring'''
import math
class a_ :
def __init__(self , __a=0) -> Any: # a graph with Node 0,1,...,N-1
"""simple docstring"""
__snake_case : List[str] = n
__snake_case : Tuple = [
[math.inf for j in range(0 , __a)] for i in range(0 , __a)
] # adjacency matrix for weight
__snake_case : Union[str, Any] = [
[math.inf for j in range(0 , __a)] for i in range(0 , __a)
] # dp[i][j] stores minimum distance from i to j
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple:
"""simple docstring"""
__snake_case : Union[str, Any] = w
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
for k in range(0 , self.n):
for i in range(0 , self.n):
for j in range(0 , self.n):
__snake_case : List[Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j])
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Optional[int]:
"""simple docstring"""
return self.dp[u][v]
if __name__ == "__main__":
__A = Graph(5)
graph.add_edge(0, 2, 9)
graph.add_edge(0, 4, 1_0)
graph.add_edge(1, 3, 5)
graph.add_edge(2, 3, 7)
graph.add_edge(3, 0, 1_0)
graph.add_edge(3, 1, 2)
graph.add_edge(3, 2, 1)
graph.add_edge(3, 4, 6)
graph.add_edge(4, 1, 3)
graph.add_edge(4, 2, 4)
graph.add_edge(4, 3, 9)
graph.floyd_warshall()
graph.show_min(1, 4)
graph.show_min(0, 3) | 61 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
__A = {
'''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''GPTBigCodeForSequenceClassification''',
'''GPTBigCodeForTokenClassification''',
'''GPTBigCodeForCausalLM''',
'''GPTBigCodeModel''',
'''GPTBigCodePreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_bigcode import (
GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTBigCodeForCausalLM,
GPTBigCodeForSequenceClassification,
GPTBigCodeForTokenClassification,
GPTBigCodeModel,
GPTBigCodePreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 709 |
'''simple docstring'''
from typing import Dict, List, Optional, Union
import numpy as np
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,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_vision_available():
import PIL
__A = logging.get_logger(__name__)
class a_ ( UpperCamelCase_ ):
_snake_case = ["""pixel_values"""]
def __init__(self , __a = True , __a = None , __a = None , __a = PILImageResampling.BILINEAR , __a = True , __a = 1 / 2_5_5 , __a = True , __a = None , __a = None , **__a , ) -> None:
"""simple docstring"""
super().__init__(**__a)
__snake_case : Tuple = size if size is not None else {'shortest_edge': 3_8_4}
__snake_case : List[Any] = get_size_dict(__a , default_to_square=__a)
__snake_case : int = do_resize
__snake_case : List[str] = size
# Default value set here for backwards compatibility where the value in config is None
__snake_case : Any = crop_pct if crop_pct is not None else 2_2_4 / 2_5_6
__snake_case : Tuple = resample
__snake_case : Dict = do_rescale
__snake_case : Any = rescale_factor
__snake_case : str = do_normalize
__snake_case : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
__snake_case : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = PILImageResampling.BICUBIC , __a = None , **__a , ) -> np.ndarray:
"""simple docstring"""
__snake_case : Dict = get_size_dict(__a , default_to_square=__a)
if "shortest_edge" not in size:
raise ValueError(F"""Size dictionary must contain 'shortest_edge' key. Got {size.keys()}""")
__snake_case : List[str] = size['shortest_edge']
if shortest_edge < 3_8_4:
# maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
__snake_case : Any = int(shortest_edge / crop_pct)
__snake_case : Any = get_resize_output_image_size(__a , size=__a , default_to_square=__a)
__snake_case : int = resize(image=__a , size=__a , resample=__a , data_format=__a , **__a)
# then crop to (shortest_edge, shortest_edge)
return center_crop(image=__a , size=(shortest_edge, shortest_edge) , data_format=__a , **__a)
else:
# warping (no cropping) when evaluated at 384 or larger
return resize(
__a , size=(shortest_edge, shortest_edge) , resample=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> Any:
"""simple docstring"""
return rescale(__a , scale=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray:
"""simple docstring"""
return normalize(__a , mean=__a , std=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image:
"""simple docstring"""
__snake_case : Optional[int] = do_resize if do_resize is not None else self.do_resize
__snake_case : Dict = crop_pct if crop_pct is not None else self.crop_pct
__snake_case : Tuple = resample if resample is not None else self.resample
__snake_case : Any = do_rescale if do_rescale is not None else self.do_rescale
__snake_case : Any = rescale_factor if rescale_factor is not None else self.rescale_factor
__snake_case : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize
__snake_case : Optional[int] = image_mean if image_mean is not None else self.image_mean
__snake_case : Optional[Any] = image_std if image_std is not None else self.image_std
__snake_case : List[str] = size if size is not None else self.size
__snake_case : Any = get_size_dict(__a , default_to_square=__a)
__snake_case : Dict = make_list_of_images(__a)
if not valid_images(__a):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.')
if do_resize and size is None or resample is None:
raise ValueError('Size and resample must be specified if do_resize is True.')
if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None:
raise ValueError('crop_pct must be specified if size < 384.')
if do_rescale and rescale_factor is None:
raise ValueError('Rescale factor must be specified if do_rescale is True.')
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('Image mean and std must be specified if do_normalize is True.')
# All transformations expect numpy arrays.
__snake_case : Tuple = [to_numpy_array(__a) for image in images]
if do_resize:
__snake_case : Optional[int] = [self.resize(image=__a , size=__a , crop_pct=__a , resample=__a) for image in images]
if do_rescale:
__snake_case : Optional[int] = [self.rescale(image=__a , scale=__a) for image in images]
if do_normalize:
__snake_case : Any = [self.normalize(image=__a , mean=__a , std=__a) for image in images]
__snake_case : Dict = [to_channel_dimension_format(__a , __a) for image in images]
__snake_case : Union[str, Any] = {'pixel_values': images}
return BatchFeature(data=__a , tensor_type=__a) | 61 | 0 |
from string import ascii_uppercase
__A = {char: i for i, char in enumerate(ascii_uppercase)}
__A = dict(enumerate(ascii_uppercase))
def _SCREAMING_SNAKE_CASE ( A : str , A : str ) -> List[Any]:
"""simple docstring"""
__snake_case : Optional[Any] = len(A )
__snake_case : str = 0
while True:
if x == i:
__snake_case : Dict = 0
if len(A ) == len(A ):
break
key += key[i]
i += 1
return key
def _SCREAMING_SNAKE_CASE ( A : str , A : str ) -> Dict:
"""simple docstring"""
__snake_case : Optional[int] = ''
__snake_case : List[str] = 0
for letter in message:
if letter == " ":
cipher_text += " "
else:
__snake_case : Any = (dicta[letter] - dicta[key_new[i]]) % 26
i += 1
cipher_text += dicta[x]
return cipher_text
def _SCREAMING_SNAKE_CASE ( A : str , A : str ) -> Dict:
"""simple docstring"""
__snake_case : Optional[int] = ''
__snake_case : List[Any] = 0
for letter in cipher_text:
if letter == " ":
or_txt += " "
else:
__snake_case : int = (dicta[letter] + dicta[key_new[i]] + 26) % 26
i += 1
or_txt += dicta[x]
return or_txt
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
__snake_case : int = 'THE GERMAN ATTACK'
__snake_case : List[Any] = 'SECRET'
__snake_case : Optional[int] = generate_key(A , A )
__snake_case : Optional[Any] = cipher_text(A , A )
print(F"""Encrypted Text = {s}""" )
print(F"""Original Text = {original_text(A , A )}""" )
if __name__ == "__main__":
import doctest
doctest.testmod()
main() | 710 |
'''simple docstring'''
from functools import lru_cache
@lru_cache
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
if num < 0:
raise ValueError('Number should not be negative.' )
return 1 if num in (0, 1) else num * factorial(num - 1 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 61 | 0 |
'''simple docstring'''
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING
__A = logging.get_logger(__name__)
__A = {
"Salesforce/instruct-blip-flan-t5": "https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json",
}
class a_ ( __UpperCAmelCase ):
_snake_case = """instructblip_vision_model"""
def __init__(self , __a=1_4_0_8 , __a=6_1_4_4 , __a=3_9 , __a=1_6 , __a=2_2_4 , __a=1_4 , __a="gelu" , __a=1E-6 , __a=0.0 , __a=1E-10 , __a=True , **__a , ) -> Dict:
"""simple docstring"""
super().__init__(**lowerCAmelCase_)
__snake_case : str = hidden_size
__snake_case : List[Any] = intermediate_size
__snake_case : Tuple = num_hidden_layers
__snake_case : Dict = num_attention_heads
__snake_case : int = patch_size
__snake_case : Optional[int] = image_size
__snake_case : Dict = initializer_range
__snake_case : Tuple = attention_dropout
__snake_case : Optional[int] = layer_norm_eps
__snake_case : Any = hidden_act
__snake_case : Union[str, Any] = qkv_bias
@classmethod
def SCREAMING_SNAKE_CASE__ (cls , __a , **__a) -> Dict:
"""simple docstring"""
cls._set_token_in_kwargs(lowerCAmelCase_)
__snake_case ,__snake_case : Any = cls.get_config_dict(lowerCAmelCase_ , **lowerCAmelCase_)
# get the vision config dict if we are loading from InstructBlipConfig
if config_dict.get('model_type') == "instructblip":
__snake_case : Dict = 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(lowerCAmelCase_ , **lowerCAmelCase_)
class a_ ( __UpperCAmelCase ):
_snake_case = """instructblip_qformer"""
def __init__(self , __a=3_0_5_2_2 , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_1_2 , __a=0.02 , __a=1E-12 , __a=0 , __a="absolute" , __a=2 , __a=1_4_0_8 , **__a , ) -> Optional[Any]:
"""simple docstring"""
super().__init__(pad_token_id=lowerCAmelCase_ , **lowerCAmelCase_)
__snake_case : Union[str, Any] = vocab_size
__snake_case : Optional[int] = hidden_size
__snake_case : List[Any] = num_hidden_layers
__snake_case : Any = num_attention_heads
__snake_case : Optional[int] = hidden_act
__snake_case : int = intermediate_size
__snake_case : Tuple = hidden_dropout_prob
__snake_case : List[Any] = attention_probs_dropout_prob
__snake_case : int = max_position_embeddings
__snake_case : Dict = initializer_range
__snake_case : Optional[Any] = layer_norm_eps
__snake_case : str = position_embedding_type
__snake_case : str = cross_attention_frequency
__snake_case : Optional[Any] = encoder_hidden_size
@classmethod
def SCREAMING_SNAKE_CASE__ (cls , __a , **__a) -> Union[str, Any]:
"""simple docstring"""
cls._set_token_in_kwargs(lowerCAmelCase_)
__snake_case ,__snake_case : Any = cls.get_config_dict(lowerCAmelCase_ , **lowerCAmelCase_)
# get the qformer config dict if we are loading from InstructBlipConfig
if config_dict.get('model_type') == "instructblip":
__snake_case : str = config_dict['qformer_config']
if "model_type" in config_dict and hasattr(cls , 'model_type') and config_dict["model_type"] != cls.model_type:
logger.warning(
F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""")
return cls.from_dict(lowerCAmelCase_ , **lowerCAmelCase_)
class a_ ( __UpperCAmelCase ):
_snake_case = """instructblip"""
_snake_case = True
def __init__(self , __a=None , __a=None , __a=None , __a=3_2 , **__a) -> Union[str, Any]:
"""simple docstring"""
super().__init__(**lowerCAmelCase_)
if vision_config is None:
__snake_case : Any = {}
logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.')
if qformer_config is None:
__snake_case : Tuple = {}
logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.')
if text_config is None:
__snake_case : List[Any] = {}
logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).')
__snake_case : Tuple = InstructBlipVisionConfig(**lowerCAmelCase_)
__snake_case : str = InstructBlipQFormerConfig(**lowerCAmelCase_)
__snake_case : Any = text_config['model_type'] if 'model_type' in text_config else 'opt'
__snake_case : str = CONFIG_MAPPING[text_model_type](**lowerCAmelCase_)
__snake_case : Any = self.text_config.tie_word_embeddings
__snake_case : Any = self.text_config.is_encoder_decoder
__snake_case : Union[str, Any] = num_query_tokens
__snake_case : List[str] = self.vision_config.hidden_size
__snake_case : str = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
__snake_case : int = 1.0
__snake_case : List[str] = 0.02
@classmethod
def SCREAMING_SNAKE_CASE__ (cls , __a , __a , __a , **__a , ) -> Dict:
"""simple docstring"""
return cls(
vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **lowerCAmelCase_ , )
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : Optional[int] = copy.deepcopy(self.__dict__)
__snake_case : Tuple = self.vision_config.to_dict()
__snake_case : Tuple = self.qformer_config.to_dict()
__snake_case : Optional[Any] = self.text_config.to_dict()
__snake_case : Dict = self.__class__.model_type
return output | 711 |
'''simple docstring'''
import unittest
import torch
from diffusers import VQModel
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism
from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ):
_snake_case = VQModel
_snake_case = """sample"""
@property
def SCREAMING_SNAKE_CASE__ (self , __a=(3_2, 3_2)) -> str:
"""simple docstring"""
__snake_case : Dict = 4
__snake_case : Optional[int] = 3
__snake_case : str = floats_tensor((batch_size, num_channels) + sizes).to(__a)
return {"sample": image}
@property
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
return (3, 3_2, 3_2)
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
return (3, 3_2, 3_2)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[Any] = {
'block_out_channels': [3_2, 6_4],
'in_channels': 3,
'out_channels': 3,
'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'],
'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'],
'latent_channels': 3,
}
__snake_case : List[Any] = self.dummy_input
return init_dict, inputs_dict
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case ,__snake_case : List[Any] = VQModel.from_pretrained('fusing/vqgan-dummy' , output_loading_info=__a)
self.assertIsNotNone(__a)
self.assertEqual(len(loading_info['missing_keys']) , 0)
model.to(__a)
__snake_case : Any = model(**self.dummy_input)
assert image is not None, "Make sure output is not None"
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : Union[str, Any] = VQModel.from_pretrained('fusing/vqgan-dummy')
model.to(__a).eval()
torch.manual_seed(0)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(0)
__snake_case : Tuple = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size)
__snake_case : Optional[int] = image.to(__a)
with torch.no_grad():
__snake_case : List[Any] = model(__a).sample
__snake_case : int = output[0, -1, -3:, -3:].flatten().cpu()
# fmt: off
__snake_case : int = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143])
# fmt: on
self.assertTrue(torch.allclose(__a , __a , atol=1E-3)) | 61 | 0 |
'''simple docstring'''
import os
import pytest
from attr import dataclass
__A = '''us-east-1''' # defaults region
@dataclass
class a_ :
_snake_case = 42
_snake_case = """arn:aws:iam::558105141721:role/sagemaker_execution_role"""
_snake_case = {
"""task_name""": """mnli""",
"""per_device_train_batch_size""": 16,
"""per_device_eval_batch_size""": 16,
"""do_train""": True,
"""do_eval""": True,
"""do_predict""": True,
"""output_dir""": """/opt/ml/model""",
"""overwrite_output_dir""": True,
"""max_steps""": 500,
"""save_steps""": 5500,
}
_snake_case = {**hyperparameters, """max_steps""": 1000}
@property
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
if self.framework == "pytorch":
return [
{"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"},
{"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"},
{"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"},
]
else:
return [
{"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"},
{"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"},
{"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"},
]
@property
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
return F"""{self.framework}-transfromers-test"""
@property
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
return F"""./tests/sagemaker/scripts/{self.framework}"""
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
if self.framework == "pytorch":
return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04"
else:
return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04"
@pytest.fixture(scope='class' )
def _SCREAMING_SNAKE_CASE ( A : Dict ) -> str:
"""simple docstring"""
__snake_case : Optional[Any] = SageMakerTestEnvironment(framework=request.cls.framework ) | 712 |
'''simple docstring'''
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
__A = logging.getLogger(__name__)
@dataclass
class a_ :
_snake_case = field(
metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} )
_snake_case = field(
default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} )
_snake_case = 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.
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , )
@dataclass
class a_ :
_snake_case = field(
metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , )
_snake_case = field(
default=128 , metadata={
"""help""": (
"""The maximum total input sequence length after tokenization. Sequences longer """
"""than this will be truncated, sequences shorter will be padded."""
)
} , )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} )
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
# 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.
__snake_case : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
__snake_case ,__snake_case ,__snake_case : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
__snake_case ,__snake_case ,__snake_case : int = 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.' )
__snake_case : List[str] = import_module('tasks' )
try:
__snake_case : Any = getattr(A , model_args.task_type )
__snake_case : TokenClassificationTask = 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' , A )
# Set seed
set_seed(training_args.seed )
# Prepare CONLL-2003 task
__snake_case : Optional[Any] = token_classification_task.get_labels(data_args.labels )
__snake_case : Dict[int, str] = dict(enumerate(A ) )
__snake_case : Optional[Any] = len(A )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
__snake_case : Any = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=A , idalabel=A , labelaid={label: i for i, label in enumerate(A )} , cache_dir=model_args.cache_dir , )
__snake_case : List[str] = 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 , )
__snake_case : Optional[int] = AutoModelForTokenClassification.from_pretrained(
model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=A , cache_dir=model_args.cache_dir , )
# Get datasets
__snake_case : List[Any] = (
TokenClassificationDataset(
token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , 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
)
__snake_case : int = (
TokenClassificationDataset(
token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , 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(A : np.ndarray , A : np.ndarray ) -> Tuple[List[int], List[int]]:
__snake_case : str = np.argmax(A , axis=2 )
__snake_case ,__snake_case : int = preds.shape
__snake_case : Dict = [[] for _ in range(A )]
__snake_case : Union[str, Any] = [[] for _ in range(A )]
for i in range(A ):
for j in range(A ):
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(A : EvalPrediction ) -> Dict:
__snake_case ,__snake_case : Any = align_predictions(p.predictions , p.label_ids )
return {
"accuracy_score": accuracy_score(A , A ),
"precision": precision_score(A , A ),
"recall": recall_score(A , A ),
"f1": fa_score(A , A ),
}
# Data collator
__snake_case : Optional[int] = DataCollatorWithPadding(A , pad_to_multiple_of=8 ) if training_args.fpaa else None
# Initialize our Trainer
__snake_case : Optional[Any] = Trainer(
model=A , args=A , train_dataset=A , eval_dataset=A , compute_metrics=A , data_collator=A , )
# 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
__snake_case : List[Any] = {}
if training_args.do_eval:
logger.info('*** Evaluate ***' )
__snake_case : List[str] = trainer.evaluate()
__snake_case : Tuple = os.path.join(training_args.output_dir , 'eval_results.txt' )
if trainer.is_world_process_zero():
with open(A , 'w' ) as writer:
logger.info('***** Eval results *****' )
for key, value in result.items():
logger.info(' %s = %s' , A , A )
writer.write('%s = %s\n' % (key, value) )
results.update(A )
# Predict
if training_args.do_predict:
__snake_case : str = TokenClassificationDataset(
token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , )
__snake_case ,__snake_case ,__snake_case : str = trainer.predict(A )
__snake_case ,__snake_case : List[str] = align_predictions(A , A )
__snake_case : Optional[int] = os.path.join(training_args.output_dir , 'test_results.txt' )
if trainer.is_world_process_zero():
with open(A , 'w' ) as writer:
for key, value in metrics.items():
logger.info(' %s = %s' , A , A )
writer.write('%s = %s\n' % (key, value) )
# Save predictions
__snake_case : List[str] = os.path.join(training_args.output_dir , 'test_predictions.txt' )
if trainer.is_world_process_zero():
with open(A , 'w' ) as writer:
with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f:
token_classification_task.write_predictions_to_file(A , A , A )
return results
def _SCREAMING_SNAKE_CASE ( A : int ) -> Any:
"""simple docstring"""
# For xla_spawn (TPUs)
main()
if __name__ == "__main__":
main() | 61 | 0 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : Optional[Any] , A : Any ) -> Any:
"""simple docstring"""
while second != 0:
__snake_case : List[Any] = first & second
first ^= second
__snake_case : Optional[Any] = c << 1
return first
if __name__ == "__main__":
import doctest
doctest.testmod()
__A = int(input('''Enter the first number: ''').strip())
__A = int(input('''Enter the second number: ''').strip())
print(f'''{add(first, second) = }''') | 713 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : list ) -> list:
"""simple docstring"""
__snake_case : Tuple = False
while is_sorted is False: # Until all the indices are traversed keep looping
__snake_case : Optional[Any] = True
for i in range(0 , len(A ) - 1 , 2 ): # iterating over all even indices
if input_list[i] > input_list[i + 1]:
__snake_case ,__snake_case : int = input_list[i + 1], input_list[i]
# swapping if elements not in order
__snake_case : List[Any] = False
for i in range(1 , len(A ) - 1 , 2 ): # iterating over all odd indices
if input_list[i] > input_list[i + 1]:
__snake_case ,__snake_case : Tuple = input_list[i + 1], input_list[i]
# swapping if elements not in order
__snake_case : Any = False
return input_list
if __name__ == "__main__":
print('''Enter list to be sorted''')
__A = [int(x) for x in input().split()]
# inputing elements of the list in one line
__A = odd_even_sort(input_list)
print('''The sorted list is''')
print(sorted_list) | 61 | 0 |
'''simple docstring'''
class a_ : # Public class to implement a graph
def __init__(self , __a , __a , __a) -> List[Any]:
"""simple docstring"""
__snake_case : Any = row
__snake_case : List[str] = col
__snake_case : Dict = graph
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Union[str, Any]:
"""simple docstring"""
return (
0 <= i < self.ROW
and 0 <= j < self.COL
and not visited[i][j]
and self.graph[i][j]
)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> List[str]:
"""simple docstring"""
__snake_case : Optional[Any] = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order
__snake_case : Optional[int] = [-1, 0, 1, -1, 1, -1, 0, 1]
__snake_case : Dict = True # Make those cells visited
for k in range(8):
if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , __UpperCamelCase):
self.diffs(i + row_nbr[k] , j + col_nbr[k] , __UpperCamelCase)
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]: # And finally, count all islands.
"""simple docstring"""
__snake_case : List[Any] = [[False for j in range(self.COL)] for i in range(self.ROW)]
__snake_case : Tuple = 0
for i in range(self.ROW):
for j in range(self.COL):
if visited[i][j] is False and self.graph[i][j] == 1:
self.diffs(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase)
count += 1
return count | 714 |
'''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 _SCREAMING_SNAKE_CASE ( A : int , A : str , A : LevitConfig , A : Path , A : bool = True ) -> Dict:
"""simple docstring"""
print(F"""Converting {name}...""" )
with torch.no_grad():
if hidden_sizes == 1_28:
if name[-1] == "S":
__snake_case : Optional[int] = timm.create_model('levit_128s' , pretrained=A )
else:
__snake_case : Tuple = timm.create_model('levit_128' , pretrained=A )
if hidden_sizes == 1_92:
__snake_case : int = timm.create_model('levit_192' , pretrained=A )
if hidden_sizes == 2_56:
__snake_case : List[Any] = timm.create_model('levit_256' , pretrained=A )
if hidden_sizes == 3_84:
__snake_case : int = timm.create_model('levit_384' , pretrained=A )
from_model.eval()
__snake_case : str = LevitForImageClassificationWithTeacher(A ).eval()
__snake_case : int = OrderedDict()
__snake_case : Optional[Any] = from_model.state_dict()
__snake_case : Tuple = list(from_model.state_dict().keys() )
__snake_case : List[str] = list(our_model.state_dict().keys() )
print(len(A ) , len(A ) )
for i in range(len(A ) ):
__snake_case : Optional[int] = weights[og_keys[i]]
our_model.load_state_dict(A )
__snake_case : Tuple = torch.randn((2, 3, 2_24, 2_24) )
__snake_case : Union[str, Any] = from_model(A )
__snake_case : List[str] = our_model(A ).logits
assert torch.allclose(A , A ), "The model logits don't match the original one."
__snake_case : int = name
print(A )
if push_to_hub:
our_model.save_pretrained(save_directory / checkpoint_name )
__snake_case : int = LevitImageProcessor()
image_processor.save_pretrained(save_directory / checkpoint_name )
print(F"""Pushed {checkpoint_name}""" )
def _SCREAMING_SNAKE_CASE ( A : Path , A : str = None , A : bool = True ) -> List[Any]:
"""simple docstring"""
__snake_case : Optional[Any] = 'imagenet-1k-id2label.json'
__snake_case : Tuple = 10_00
__snake_case : Dict = (1, num_labels)
__snake_case : List[str] = 'huggingface/label-files'
__snake_case : Any = num_labels
__snake_case : str = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) )
__snake_case : Any = {int(A ): v for k, v in idalabel.items()}
__snake_case : int = idalabel
__snake_case : Union[str, Any] = {v: k for k, v in idalabel.items()}
__snake_case : Optional[int] = partial(A , num_labels=A , idalabel=A , labelaid=A )
__snake_case : Dict = {
'levit-128S': 1_28,
'levit-128': 1_28,
'levit-192': 1_92,
'levit-256': 2_56,
'levit-384': 3_84,
}
__snake_case : Union[str, Any] = {
'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) | 61 | 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
__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 a_ ( UpperCamelCase_ ):
_snake_case = """levit"""
def __init__(self , __a=2_2_4 , __a=3 , __a=3 , __a=2 , __a=1 , __a=1_6 , __a=[1_2_8, 2_5_6, 3_8_4] , __a=[4, 8, 1_2] , __a=[4, 4, 4] , __a=[1_6, 1_6, 1_6] , __a=0 , __a=[2, 2, 2] , __a=[2, 2, 2] , __a=0.02 , **__a , ) -> int:
"""simple docstring"""
super().__init__(**__a)
__snake_case : Any = image_size
__snake_case : Dict = num_channels
__snake_case : List[Any] = kernel_size
__snake_case : Optional[Any] = stride
__snake_case : List[str] = padding
__snake_case : Optional[int] = hidden_sizes
__snake_case : Optional[Any] = num_attention_heads
__snake_case : Tuple = depths
__snake_case : Any = key_dim
__snake_case : List[Any] = drop_path_rate
__snake_case : Union[str, Any] = patch_size
__snake_case : List[Any] = attention_ratio
__snake_case : Union[str, Any] = mlp_ratio
__snake_case : Optional[Any] = initializer_range
__snake_case : Union[str, Any] = [
['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 a_ ( UpperCamelCase_ ):
_snake_case = version.parse("""1.11""" )
@property
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
return OrderedDict(
[
('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
])
@property
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
return 1E-4 | 715 |
'''simple docstring'''
import inspect
import unittest
from typing import List
import numpy as np
from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFEfficientFormerForImageClassification,
TFEfficientFormerForImageClassificationWithTeacher,
TFEfficientFormerModel,
)
from transformers.models.efficientformer.modeling_tf_efficientformer import (
TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_vision_available():
from PIL import Image
from transformers import EfficientFormerImageProcessor
class a_ :
def __init__(self , __a , __a = 1_3 , __a = 6_4 , __a = 2 , __a = 3 , __a = 3 , __a = True , __a = True , __a = 1_2_8 , __a=[1_6, 3_2, 6_4, 1_2_8] , __a = 7 , __a = 4 , __a = 3_7 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 1_0 , __a = 0.02 , __a = 2 , __a = 1 , __a = 1_2_8 , __a = [2, 2, 2, 2] , __a = 2 , __a = 2 , ) -> str:
"""simple docstring"""
__snake_case : Optional[Any] = parent
__snake_case : Optional[int] = batch_size
__snake_case : Optional[Any] = image_size
__snake_case : Optional[int] = patch_size
__snake_case : Optional[Any] = num_channels
__snake_case : Optional[Any] = is_training
__snake_case : Tuple = use_labels
__snake_case : Optional[int] = hidden_size
__snake_case : Any = num_hidden_layers
__snake_case : List[str] = num_attention_heads
__snake_case : Tuple = intermediate_size
__snake_case : List[str] = hidden_act
__snake_case : Dict = hidden_dropout_prob
__snake_case : Any = attention_probs_dropout_prob
__snake_case : Dict = type_sequence_label_size
__snake_case : str = initializer_range
__snake_case : int = encoder_stride
__snake_case : List[str] = num_attention_outputs
__snake_case : Optional[Any] = embed_dim
__snake_case : Optional[Any] = embed_dim + 1
__snake_case : List[str] = resolution
__snake_case : Optional[int] = depths
__snake_case : List[Any] = hidden_sizes
__snake_case : List[str] = dim
__snake_case : Union[str, Any] = mlp_expansion_ratio
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
__snake_case : List[str] = None
if self.use_labels:
__snake_case : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size)
__snake_case : Tuple = self.get_config()
return config, pixel_values, labels
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return EfficientFormerConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , )
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Optional[int]:
"""simple docstring"""
__snake_case : Union[str, Any] = TFEfficientFormerModel(config=__a)
__snake_case : int = model(__a , training=__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple:
"""simple docstring"""
__snake_case : Dict = self.type_sequence_label_size
__snake_case : List[Any] = TFEfficientFormerForImageClassification(__a)
__snake_case : Optional[int] = model(__a , labels=__a , training=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size))
# test greyscale images
__snake_case : List[Any] = 1
__snake_case : List[Any] = TFEfficientFormerForImageClassification(__a)
__snake_case : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
__snake_case : str = model(__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size))
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : Union[str, Any] = self.prepare_config_and_inputs()
__snake_case ,__snake_case ,__snake_case : Union[str, Any] = config_and_inputs
__snake_case : Optional[int] = {'pixel_values': pixel_values}
return config, inputs_dict
@require_tf
class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ):
_snake_case = (
(
TFEfficientFormerModel,
TFEfficientFormerForImageClassificationWithTeacher,
TFEfficientFormerForImageClassification,
)
if is_tf_available()
else ()
)
_snake_case = (
{
"""feature-extraction""": TFEfficientFormerModel,
"""image-classification""": (
TFEfficientFormerForImageClassification,
TFEfficientFormerForImageClassificationWithTeacher,
),
}
if is_tf_available()
else {}
)
_snake_case = False
_snake_case = False
_snake_case = False
_snake_case = False
_snake_case = False
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Dict = TFEfficientFormerModelTester(self)
__snake_case : List[Any] = ConfigTester(
self , config_class=__a , has_text_modality=__a , hidden_size=3_7)
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
self.config_tester.run_common_tests()
@unittest.skip(reason='EfficientFormer does not use inputs_embeds')
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
pass
@unittest.skip(reason='EfficientFormer does not support input and output embeddings')
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case ,__snake_case : str = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case : Optional[int] = model_class(__a)
__snake_case : Union[str, Any] = inspect.signature(model.call)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__snake_case : Optional[int] = [*signature.parameters.keys()]
__snake_case : Dict = ['pixel_values']
self.assertListEqual(arg_names[:1] , __a)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
def check_hidden_states_output(__a , __a , __a):
__snake_case : str = model_class(__a)
__snake_case : List[Any] = model(**self._prepare_for_class(__a , __a) , training=__a)
__snake_case : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
__snake_case : Optional[Any] = getattr(
self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1)
self.assertEqual(len(__a) , __a)
if hasattr(self.model_tester , 'encoder_seq_length'):
__snake_case : List[Any] = self.model_tester.encoder_seq_length
if hasattr(self.model_tester , 'chunk_length') and self.model_tester.chunk_length > 1:
__snake_case : str = seq_length * self.model_tester.chunk_length
else:
__snake_case : Optional[int] = self.model_tester.seq_length
self.assertListEqual(
list(hidden_states[-1].shape[-2:]) , [seq_length, self.model_tester.hidden_size] , )
if config.is_encoder_decoder:
__snake_case : List[Any] = outputs.decoder_hidden_states
self.asseretIsInstance(__a , (list, tuple))
self.assertEqual(len(__a) , __a)
__snake_case : List[str] = getattr(self.model_tester , 'seq_length' , __a)
__snake_case : Tuple = getattr(self.model_tester , 'decoder_seq_length' , __a)
self.assertListEqual(
list(hidden_states[-1].shape[-2:]) , [decoder_seq_length, self.model_tester.hidden_size] , )
__snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case : List[str] = True
check_hidden_states_output(__a , __a , __a)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__snake_case : str = True
check_hidden_states_output(__a , __a , __a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a=False) -> int:
"""simple docstring"""
__snake_case : Optional[int] = super()._prepare_for_class(__a , __a , return_labels=__a)
if return_labels:
if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
del inputs_dict["labels"]
return inputs_dict
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
@unittest.skip(reason='EfficientFormer does not implement masked image modeling yet')
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*__a)
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*__a)
@slow
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__snake_case : Any = TFEfficientFormerModel.from_pretrained(__a)
self.assertIsNotNone(__a)
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case : Tuple = True
__snake_case : Optional[Any] = getattr(self.model_tester , 'seq_length' , __a)
__snake_case : List[Any] = getattr(self.model_tester , 'encoder_seq_length' , __a)
__snake_case : Tuple = getattr(self.model_tester , 'key_length' , __a)
__snake_case : Optional[Any] = getattr(self.model_tester , 'chunk_length' , __a)
if chunk_length is not None and hasattr(self.model_tester , 'num_hashes'):
__snake_case : str = encoder_seq_length * self.model_tester.num_hashes
for model_class in self.all_model_classes:
__snake_case : Optional[Any] = True
__snake_case : Dict = False
__snake_case : Optional[int] = True
__snake_case : Dict = model_class(__a)
__snake_case : Tuple = model(**self._prepare_for_class(__a , __a) , training=__a)
__snake_case : Union[str, Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(__a) , self.model_tester.num_attention_outputs)
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
__snake_case : Dict = True
__snake_case : str = model_class(__a)
__snake_case : str = model(**self._prepare_for_class(__a , __a) , training=__a)
__snake_case : Tuple = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(__a) , self.model_tester.num_attention_outputs)
if chunk_length is not None:
self.assertListEqual(
list(attentions[0].shape[-4:]) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , )
else:
self.assertListEqual(
list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , )
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case ,__snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
# Prepare our model
__snake_case : Tuple = model_class(__a)
# These are maximally general inputs for the model, with multiple None dimensions
# Hopefully this will catch any conditionals that fail for flexible shapes
__snake_case : Optional[Any] = {
key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=__a)
for key, val in model.input_signature.items()
if key in model.dummy_inputs
}
__snake_case : Tuple = model(__a)
self.assertTrue(outputs_dict is not None)
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
__snake_case : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_tf
@require_vision
class a_ ( unittest.TestCase ):
@cached_property
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return (
EfficientFormerImageProcessor.from_pretrained('snap-research/efficientformer-l1-300')
if is_vision_available()
else None
)
@slow
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case : List[str] = TFEfficientFormerForImageClassification.from_pretrained('snap-research/efficientformer-l1-300')
__snake_case : Optional[int] = self.default_image_processor
__snake_case : List[Any] = prepare_img()
__snake_case : List[Any] = image_processor(images=__a , return_tensors='tf')
# forward pass
__snake_case : List[str] = model(**__a , training=__a)
# verify the logits
__snake_case : str = tf.TensorShape((1, 1_0_0_0))
self.assertEqual(outputs.logits.shape , __a)
__snake_case : Any = tf.constant([-0.0_555, 0.4_825, -0.0_852])
self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4))
@slow
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[Any] = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
'snap-research/efficientformer-l1-300')
__snake_case : List[Any] = self.default_image_processor
__snake_case : Union[str, Any] = prepare_img()
__snake_case : List[Any] = image_processor(images=__a , return_tensors='tf')
# forward pass
__snake_case : Optional[int] = model(**__a , training=__a)
# verify the logits
__snake_case : Optional[int] = tf.TensorShape((1, 1_0_0_0))
self.assertEqual(outputs.logits.shape , __a)
__snake_case : List[str] = tf.constant([-0.1_312, 0.4_353, -1.0_499])
self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4)) | 61 | 0 |
'''simple docstring'''
from math import factorial
def _SCREAMING_SNAKE_CASE ( A : Union[str, Any] = 1_00 ) -> Dict:
"""simple docstring"""
return sum(int(A ) for x in str(factorial(A ) ) )
if __name__ == "__main__":
print(solution(int(input('''Enter the Number: ''').strip()))) | 716 |
'''simple docstring'''
__A = {str(digit): digit**5 for digit in range(1_0)}
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
return sum(DIGITS_FIFTH_POWER[digit] for digit in str(A ) )
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
return sum(
number
for number in range(10_00 , 1_00_00_00 )
if number == digits_fifth_powers_sum(A ) )
if __name__ == "__main__":
print(solution()) | 61 | 0 |
'''simple docstring'''
import argparse
import re
import numpy as np
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
SamConfig,
SamImageProcessor,
SamModel,
SamProcessor,
SamVisionConfig,
)
__A = {
"iou_prediction_head.layers.0": "iou_prediction_head.proj_in",
"iou_prediction_head.layers.1": "iou_prediction_head.layers.0",
"iou_prediction_head.layers.2": "iou_prediction_head.proj_out",
"mask_decoder.output_upscaling.0": "mask_decoder.upscale_conv1",
"mask_decoder.output_upscaling.1": "mask_decoder.upscale_layer_norm",
"mask_decoder.output_upscaling.3": "mask_decoder.upscale_conv2",
"mask_downscaling.0": "mask_embed.conv1",
"mask_downscaling.1": "mask_embed.layer_norm1",
"mask_downscaling.3": "mask_embed.conv2",
"mask_downscaling.4": "mask_embed.layer_norm2",
"mask_downscaling.6": "mask_embed.conv3",
"point_embeddings": "point_embed",
"pe_layer.positional_encoding_gaussian_matrix": "shared_embedding.positional_embedding",
"image_encoder": "vision_encoder",
"neck.0": "neck.conv1",
"neck.1": "neck.layer_norm1",
"neck.2": "neck.conv2",
"neck.3": "neck.layer_norm2",
"patch_embed.proj": "patch_embed.projection",
".norm": ".layer_norm",
"blocks": "layers",
}
def _SCREAMING_SNAKE_CASE ( A : Dict ) -> str:
"""simple docstring"""
__snake_case : str = {}
state_dict.pop('pixel_mean' , A )
state_dict.pop('pixel_std' , A )
__snake_case : List[Any] = r'''.*.output_hypernetworks_mlps.(\d+).layers.(\d+).*'''
for key, value in state_dict.items():
for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
if key_to_modify in key:
__snake_case : List[Any] = key.replace(A , A )
if re.match(A , A ):
__snake_case : List[str] = int(re.match(A , A ).group(2 ) )
if layer_nb == 0:
__snake_case : List[Any] = key.replace('layers.0' , 'proj_in' )
elif layer_nb == 1:
__snake_case : Tuple = key.replace('layers.1' , 'layers.0' )
elif layer_nb == 2:
__snake_case : Any = key.replace('layers.2' , 'proj_out' )
__snake_case : int = value
__snake_case : Union[str, Any] = model_state_dict[
'''prompt_encoder.shared_embedding.positional_embedding'''
]
return model_state_dict
def _SCREAMING_SNAKE_CASE ( A : Union[str, Any] , A : Optional[Any] , A : List[str] , A : Optional[int]="ybelkada/segment-anything" ) -> List[Any]:
"""simple docstring"""
__snake_case : Tuple = hf_hub_download(A , F"""checkpoints/{model_name}.pth""" )
if "sam_vit_b" in model_name:
__snake_case : Optional[int] = SamConfig()
elif "sam_vit_l" in model_name:
__snake_case : str = SamVisionConfig(
hidden_size=10_24 , num_hidden_layers=24 , num_attention_heads=16 , global_attn_indexes=[5, 11, 17, 23] , )
__snake_case : Tuple = SamConfig(
vision_config=A , )
elif "sam_vit_h" in model_name:
__snake_case : Optional[Any] = SamVisionConfig(
hidden_size=12_80 , num_hidden_layers=32 , num_attention_heads=16 , global_attn_indexes=[7, 15, 23, 31] , )
__snake_case : str = SamConfig(
vision_config=A , )
__snake_case : Any = torch.load(A , map_location='cpu' )
__snake_case : Tuple = replace_keys(A )
__snake_case : int = SamImageProcessor()
__snake_case : str = SamProcessor(image_processor=A )
__snake_case : List[str] = SamModel(A )
hf_model.load_state_dict(A )
__snake_case : int = hf_model.to('cuda' )
__snake_case : Union[str, Any] = '''https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png'''
__snake_case : Union[str, Any] = Image.open(requests.get(A , stream=A ).raw ).convert('RGB' )
__snake_case : str = [[[4_00, 6_50]]]
__snake_case : Tuple = [[1]]
__snake_case : Any = processor(images=np.array(A ) , return_tensors='pt' ).to('cuda' )
with torch.no_grad():
__snake_case : Optional[int] = hf_model(**A )
__snake_case : List[Any] = output.iou_scores.squeeze()
if model_name == "sam_vit_h_4b8939":
assert scores[-1].item() == 0.579890251159668
__snake_case : Any = processor(
images=np.array(A ) , input_points=A , input_labels=A , return_tensors='pt' ).to('cuda' )
with torch.no_grad():
__snake_case : Any = hf_model(**A )
__snake_case : str = output.iou_scores.squeeze()
assert scores[-1].item() == 0.9712603092193604
__snake_case : str = ((75, 2_75, 17_25, 8_50),)
__snake_case : Any = processor(images=np.array(A ) , input_boxes=A , return_tensors='pt' ).to('cuda' )
with torch.no_grad():
__snake_case : Tuple = hf_model(**A )
__snake_case : str = output.iou_scores.squeeze()
assert scores[-1].item() == 0.8686015605926514
# Test with 2 points and 1 image.
__snake_case : Optional[int] = [[[4_00, 6_50], [8_00, 6_50]]]
__snake_case : List[str] = [[1, 1]]
__snake_case : Union[str, Any] = processor(
images=np.array(A ) , input_points=A , input_labels=A , return_tensors='pt' ).to('cuda' )
with torch.no_grad():
__snake_case : Any = hf_model(**A )
__snake_case : Any = output.iou_scores.squeeze()
assert scores[-1].item() == 0.9936047792434692
if __name__ == "__main__":
__A = argparse.ArgumentParser()
__A = ["sam_vit_b_01ec64", "sam_vit_h_4b8939", "sam_vit_l_0b3195"]
parser.add_argument(
'''--model_name''',
default='''sam_vit_h_4b8939''',
choices=choices,
type=str,
help='''Path to hf config.json of model to convert''',
)
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument(
'''--push_to_hub''',
action='''store_true''',
help='''Whether to push the model and processor to the hub after converting''',
)
parser.add_argument(
'''--model_hub_id''',
default='''ybelkada/segment-anything''',
choices=choices,
type=str,
help='''Path to hf config.json of model to convert''',
)
__A = parser.parse_args()
convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id) | 717 |
'''simple docstring'''
from __future__ import annotations
from collections import deque
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any
@dataclass
class a_ :
_snake_case = 42
_snake_case = None
_snake_case = None
def _SCREAMING_SNAKE_CASE ( ) -> Node | None:
"""simple docstring"""
__snake_case : str = Node(1 )
__snake_case : Tuple = Node(2 )
__snake_case : Optional[int] = Node(3 )
__snake_case : List[str] = Node(4 )
__snake_case : List[str] = Node(5 )
return tree
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return [root.data, *preorder(root.left ), *preorder(root.right )] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return postorder(root.left ) + postorder(root.right ) + [root.data] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return [*inorder(root.left ), root.data, *inorder(root.right )] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> int:
"""simple docstring"""
return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
if root is None:
return output
__snake_case : Optional[int] = deque([root] )
while process_queue:
__snake_case : List[str] = process_queue.popleft()
output.append(node.data )
if node.left:
process_queue.append(node.left )
if node.right:
process_queue.append(node.right )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
def populate_output(A : Node | None , A : int ) -> None:
if not root:
return
if level == 1:
output.append(root.data )
elif level > 1:
populate_output(root.left , level - 1 )
populate_output(root.right , level - 1 )
populate_output(A , A )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
def populate_output(A : Node | None , A : int ) -> None:
if root is None:
return
if level == 1:
output.append(root.data )
elif level > 1:
populate_output(root.right , level - 1 )
populate_output(root.left , level - 1 )
populate_output(A , A )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None] | list[Any]:
"""simple docstring"""
if root is None:
return []
__snake_case : list[Sequence[Node | None]] = []
__snake_case : List[Any] = 0
__snake_case : int = height(A )
for h in range(1 , height_tree + 1 ):
if not flag:
output.append(get_nodes_from_left_to_right(A , A ) )
__snake_case : int = 1
else:
output.append(get_nodes_from_right_to_left(A , A ) )
__snake_case : Tuple = 0
return output
def _SCREAMING_SNAKE_CASE ( ) -> None: # Main function for testing.
"""simple docstring"""
__snake_case : Optional[int] = make_tree()
print(F"""In-order Traversal: {inorder(A )}""" )
print(F"""Pre-order Traversal: {preorder(A )}""" )
print(F"""Post-order Traversal: {postorder(A )}""" , '\n' )
print(F"""Height of Tree: {height(A )}""" , '\n' )
print('Complete Level Order Traversal: ' )
print(level_order(A ) , '\n' )
print('Level-wise order Traversal: ' )
for level in range(1 , height(A ) + 1 ):
print(F"""Level {level}:""" , get_nodes_from_left_to_right(A , level=A ) )
print('\nZigZag order Traversal: ' )
print(zigzag(A ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main() | 61 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__A = {
'configuration_chinese_clip': [
'CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP',
'ChineseCLIPConfig',
'ChineseCLIPOnnxConfig',
'ChineseCLIPTextConfig',
'ChineseCLIPVisionConfig',
],
'processing_chinese_clip': ['ChineseCLIPProcessor'],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ['ChineseCLIPFeatureExtractor']
__A = ['ChineseCLIPImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST',
'ChineseCLIPModel',
'ChineseCLIPPreTrainedModel',
'ChineseCLIPTextModel',
'ChineseCLIPVisionModel',
]
if TYPE_CHECKING:
from .configuration_chinese_clip import (
CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
ChineseCLIPConfig,
ChineseCLIPOnnxConfig,
ChineseCLIPTextConfig,
ChineseCLIPVisionConfig,
)
from .processing_chinese_clip import ChineseCLIPProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_chinese_clip import (
CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
ChineseCLIPModel,
ChineseCLIPPreTrainedModel,
ChineseCLIPTextModel,
ChineseCLIPVisionModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 718 |
'''simple docstring'''
from __future__ import annotations
import math
import random
from collections.abc import Collection
from typing import overload
class a_ :
def __init__(self , __a = None) -> None:
"""simple docstring"""
if components is None:
__snake_case : List[str] = []
__snake_case : Optional[int] = list(__a)
def __len__(self) -> int:
"""simple docstring"""
return len(self.__components)
def __str__(self) -> str:
"""simple docstring"""
return "(" + ",".join(map(__a , self.__components)) + ")"
def __add__(self , __a) -> Vector:
"""simple docstring"""
__snake_case : Optional[Any] = len(self)
if size == len(__a):
__snake_case : Optional[int] = [self.__components[i] + other.component(__a) for i in range(__a)]
return Vector(__a)
else:
raise Exception('must have the same size')
def __sub__(self , __a) -> Vector:
"""simple docstring"""
__snake_case : Optional[Any] = len(self)
if size == len(__a):
__snake_case : Optional[int] = [self.__components[i] - other.component(__a) for i in range(__a)]
return Vector(__a)
else: # error case
raise Exception('must have the same size')
@overload
def __mul__(self , __a) -> Vector:
"""simple docstring"""
...
@overload
def __mul__(self , __a) -> float:
"""simple docstring"""
...
def __mul__(self , __a) -> float | Vector:
"""simple docstring"""
if isinstance(__a , (float, int)):
__snake_case : str = [c * other for c in self.__components]
return Vector(__a)
elif isinstance(__a , __a) and len(self) == len(__a):
__snake_case : List[Any] = len(self)
__snake_case : Dict = [self.__components[i] * other.component(__a) for i in range(__a)]
return sum(__a)
else: # error case
raise Exception('invalid operand!')
def SCREAMING_SNAKE_CASE__ (self) -> Vector:
"""simple docstring"""
return Vector(self.__components)
def SCREAMING_SNAKE_CASE__ (self , __a) -> float:
"""simple docstring"""
if isinstance(__a , __a) and -len(self.__components) <= i < len(self.__components):
return self.__components[i]
else:
raise Exception('index out of range')
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> None:
"""simple docstring"""
assert -len(self.__components) <= pos < len(self.__components)
__snake_case : int = value
def SCREAMING_SNAKE_CASE__ (self) -> float:
"""simple docstring"""
if len(self.__components) == 0:
raise Exception('Vector is empty')
__snake_case : Tuple = [c**2 for c in self.__components]
return math.sqrt(sum(__a))
def SCREAMING_SNAKE_CASE__ (self , __a , __a = False) -> float:
"""simple docstring"""
__snake_case : Tuple = self * other
__snake_case : Optional[int] = self.euclidean_length() * other.euclidean_length()
if deg:
return math.degrees(math.acos(num / den))
else:
return math.acos(num / den)
def _SCREAMING_SNAKE_CASE ( A : int ) -> Vector:
"""simple docstring"""
assert isinstance(A , A )
return Vector([0] * dimension )
def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> Vector:
"""simple docstring"""
assert isinstance(A , A ) and (isinstance(A , A ))
__snake_case : Any = [0] * dimension
__snake_case : int = 1
return Vector(A )
def _SCREAMING_SNAKE_CASE ( A : float , A : Vector , A : Vector ) -> Vector:
"""simple docstring"""
assert (
isinstance(A , A )
and isinstance(A , A )
and (isinstance(A , (int, float) ))
)
return x * scalar + y
def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int ) -> Vector:
"""simple docstring"""
random.seed(A )
__snake_case : List[Any] = [random.randint(A , A ) for _ in range(A )]
return Vector(A )
class a_ :
def __init__(self , __a , __a , __a) -> None:
"""simple docstring"""
__snake_case : Union[str, Any] = matrix
__snake_case : int = w
__snake_case : str = h
def __str__(self) -> str:
"""simple docstring"""
__snake_case : Dict = ''
for i in range(self.__height):
ans += "|"
for j in range(self.__width):
if j < self.__width - 1:
ans += str(self.__matrix[i][j]) + ","
else:
ans += str(self.__matrix[i][j]) + "|\n"
return ans
def __add__(self , __a) -> Matrix:
"""simple docstring"""
if self.__width == other.width() and self.__height == other.height():
__snake_case : Tuple = []
for i in range(self.__height):
__snake_case : List[Any] = [
self.__matrix[i][j] + other.component(__a , __a)
for j in range(self.__width)
]
matrix.append(__a)
return Matrix(__a , self.__width , self.__height)
else:
raise Exception('matrix must have the same dimension!')
def __sub__(self , __a) -> Matrix:
"""simple docstring"""
if self.__width == other.width() and self.__height == other.height():
__snake_case : str = []
for i in range(self.__height):
__snake_case : List[str] = [
self.__matrix[i][j] - other.component(__a , __a)
for j in range(self.__width)
]
matrix.append(__a)
return Matrix(__a , self.__width , self.__height)
else:
raise Exception('matrices must have the same dimension!')
@overload
def __mul__(self , __a) -> Matrix:
"""simple docstring"""
...
@overload
def __mul__(self , __a) -> Vector:
"""simple docstring"""
...
def __mul__(self , __a) -> Vector | Matrix:
"""simple docstring"""
if isinstance(__a , __a): # matrix-vector
if len(__a) == self.__width:
__snake_case : Tuple = zero_vector(self.__height)
for i in range(self.__height):
__snake_case : Union[str, Any] = [
self.__matrix[i][j] * other.component(__a)
for j in range(self.__width)
]
ans.change_component(__a , sum(__a))
return ans
else:
raise Exception(
'vector must have the same size as the '
'number of columns of the matrix!')
elif isinstance(__a , (int, float)): # matrix-scalar
__snake_case : str = [
[self.__matrix[i][j] * other for j in range(self.__width)]
for i in range(self.__height)
]
return Matrix(__a , self.__width , self.__height)
return None
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return self.__height
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return self.__width
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float:
"""simple docstring"""
if 0 <= x < self.__height and 0 <= y < self.__width:
return self.__matrix[x][y]
else:
raise Exception('change_component: indices out of bounds')
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> None:
"""simple docstring"""
if 0 <= x < self.__height and 0 <= y < self.__width:
__snake_case : List[Any] = value
else:
raise Exception('change_component: indices out of bounds')
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float:
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square')
__snake_case : List[Any] = self.__matrix[:x] + self.__matrix[x + 1 :]
for i in range(len(__a)):
__snake_case : Tuple = minor[i][:y] + minor[i][y + 1 :]
return Matrix(__a , self.__width - 1 , self.__height - 1).determinant()
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float:
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square')
if 0 <= x < self.__height and 0 <= y < self.__width:
return (-1) ** (x + y) * self.minor(__a , __a)
else:
raise Exception('Indices out of bounds')
def SCREAMING_SNAKE_CASE__ (self) -> float:
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square')
if self.__height < 1:
raise Exception('Matrix has no element')
elif self.__height == 1:
return self.__matrix[0][0]
elif self.__height == 2:
return (
self.__matrix[0][0] * self.__matrix[1][1]
- self.__matrix[0][1] * self.__matrix[1][0]
)
else:
__snake_case : Any = [
self.__matrix[0][y] * self.cofactor(0 , __a) for y in range(self.__width)
]
return sum(__a)
def _SCREAMING_SNAKE_CASE ( A : int ) -> Matrix:
"""simple docstring"""
__snake_case : list[list[float]] = [[0] * n for _ in range(A )]
return Matrix(A , A , A )
def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int , A : int ) -> Matrix:
"""simple docstring"""
random.seed(A )
__snake_case : list[list[float]] = [
[random.randint(A , A ) for _ in range(A )] for _ in range(A )
]
return Matrix(A , A , A ) | 61 | 0 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool
class a_ ( lowercase_ ):
_snake_case = '''philschmid/bart-large-cnn-samsum'''
_snake_case = (
'''This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, '''
'''and returns a summary of the text.'''
)
_snake_case = '''summarizer'''
_snake_case = AutoTokenizer
_snake_case = AutoModelForSeqaSeqLM
_snake_case = ['''text''']
_snake_case = ['''text''']
def SCREAMING_SNAKE_CASE__ (self , __a) -> str:
"""simple docstring"""
return self.pre_processor(__a , return_tensors='pt' , truncation=__a)
def SCREAMING_SNAKE_CASE__ (self , __a) -> Any:
"""simple docstring"""
return self.model.generate(**__a)[0]
def SCREAMING_SNAKE_CASE__ (self , __a) -> Union[str, Any]:
"""simple docstring"""
return self.pre_processor.decode(__a , skip_special_tokens=__a , clean_up_tokenization_spaces=__a) | 719 |
'''simple docstring'''
import contextlib
import importlib
import io
import unittest
import transformers
# Try to import everything from transformers to ensure every object can be loaded.
from transformers import * # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available
if is_torch_available():
from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification
if is_tf_available():
from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification
if is_flax_available():
from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification
__A = DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co
__A = '''main'''
# Default branch name
__A = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
__A = '''aaaaaaa'''
# This commit does not exist, so we should 404.
__A = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
__A = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''
@contextlib.contextmanager
def _SCREAMING_SNAKE_CASE ( ) -> List[Any]:
"""simple docstring"""
print('Welcome!' )
yield
print('Bye!' )
@contextlib.contextmanager
def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]:
"""simple docstring"""
print('Bonjour!' )
yield
print('Au revoir!' )
class a_ ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
assert transformers.__spec__ is not None
assert importlib.util.find_spec('transformers') is not None
class a_ ( unittest.TestCase ):
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> int:
"""simple docstring"""
with ContextManagers([]):
print('Transformers are awesome!')
# The print statement adds a new line at the end of the output
self.assertEqual(mock_stdout.getvalue() , 'Transformers are awesome!\n')
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]:
"""simple docstring"""
with ContextManagers([context_en()]):
print('Transformers are awesome!')
# The output should be wrapped with an English welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , 'Welcome!\nTransformers are awesome!\nBye!\n')
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple:
"""simple docstring"""
with ContextManagers([context_fr(), context_en()]):
print('Transformers are awesome!')
# The output should be wrapped with an English and French welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , 'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n')
@require_torch
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
self.assertEqual(find_labels(__a) , ['labels'])
self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label'])
self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions'])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , ['labels'])
@require_tf
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
self.assertEqual(find_labels(__a) , ['labels'])
self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label'])
self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions'])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , ['labels'])
@require_flax
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
self.assertEqual(find_labels(__a) , [])
self.assertEqual(find_labels(__a) , [])
self.assertEqual(find_labels(__a) , [])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , []) | 61 | 0 |
'''simple docstring'''
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 a_ ( UpperCamelCase_ , UpperCamelCase_ ):
@register_to_config
def __init__(self , __a = 7_6_8 , ) -> Any:
"""simple docstring"""
super().__init__()
__snake_case : List[Any] = nn.Parameter(torch.zeros(1 , __a))
__snake_case : Dict = nn.Parameter(torch.ones(1 , __a))
def SCREAMING_SNAKE_CASE__ (self , __a = None , __a = None , ) -> Dict:
"""simple docstring"""
__snake_case : Dict = nn.Parameter(self.mean.to(__a).to(__a))
__snake_case : str = nn.Parameter(self.std.to(__a).to(__a))
return self
def SCREAMING_SNAKE_CASE__ (self , __a) -> List[Any]:
"""simple docstring"""
__snake_case : int = (embeds - self.mean) * 1.0 / self.std
return embeds
def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]:
"""simple docstring"""
__snake_case : Any = (embeds * self.std) + self.mean
return embeds | 720 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__A = {'''configuration_timm_backbone''': ['''TimmBackboneConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ['''TimmBackbone''']
if TYPE_CHECKING:
from .configuration_timm_backbone import TimmBackboneConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_timm_backbone import TimmBackbone
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 61 | 0 |
'''simple docstring'''
from typing import List, Optional, Union
import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging
__A = logging.get_logger(__name__)
class a_ ( snake_case__ ):
_snake_case = ["""input_features""", """attention_mask"""]
def __init__(self , __a=8_0 , __a=1_6_0_0_0 , __a=8_0 , __a=0.0 , __a=True , __a=True , __a=True , **__a , ) -> Dict:
"""simple docstring"""
super().__init__(feature_size=_SCREAMING_SNAKE_CASE , sampling_rate=_SCREAMING_SNAKE_CASE , padding_value=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE)
__snake_case : Dict = num_mel_bins
__snake_case : Any = do_ceptral_normalize
__snake_case : Dict = normalize_means
__snake_case : int = normalize_vars
__snake_case : str = True
def SCREAMING_SNAKE_CASE__ (self , __a , ) -> np.ndarray:
"""simple docstring"""
__snake_case : List[str] = waveform * (2**1_5) # Kaldi compliance: 16-bit signed integers
__snake_case : int = torch.from_numpy(_SCREAMING_SNAKE_CASE).unsqueeze(0)
__snake_case : List[str] = ta_kaldi.fbank(_SCREAMING_SNAKE_CASE , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate)
return features.numpy()
@staticmethod
def SCREAMING_SNAKE_CASE__ (__a , __a , __a = True , __a = True , __a = 0.0 , ) -> np.ndarray:
"""simple docstring"""
if normalize_means:
__snake_case : Union[str, Any] = x[:input_length].mean(axis=0)
__snake_case : Tuple = np.subtract(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE)
if normalize_vars:
__snake_case : Optional[Any] = x[:input_length].std(axis=0)
__snake_case : Optional[int] = np.divide(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE)
if input_length < x.shape[0]:
__snake_case : List[str] = padding_value
# make sure array is in float32
__snake_case : Tuple = x.astype(np.floataa)
return x
def SCREAMING_SNAKE_CASE__ (self , __a , __a = None) -> List[np.ndarray]:
"""simple docstring"""
__snake_case : int = attention_mask.sum(-1) if attention_mask is not None else [x.shape[0] for x in input_features]
return [
self.utterance_cmvn(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.normalize_means , self.normalize_vars , self.padding_value)
for x, n in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE)
]
def __call__(self , __a , __a = False , __a = None , __a = False , __a = None , __a = None , __a = None , __a = None , **__a , ) -> BatchFeature:
"""simple docstring"""
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
F"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of"""
F""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"""
F""" {self.sampling_rate} and not {sampling_rate}.""")
else:
logger.warning(
'It is strongly recommended to pass the `sampling_rate` argument to this function. '
'Failing to do so can result in silent errors that might be hard to debug.')
__snake_case : Dict = isinstance(_SCREAMING_SNAKE_CASE , np.ndarray) and len(raw_speech.shape) > 1
if is_batched_numpy and len(raw_speech.shape) > 2:
raise ValueError(F"""Only mono-channel audio is supported for input to {self}""")
__snake_case : Optional[int] = is_batched_numpy or (
isinstance(_SCREAMING_SNAKE_CASE , (list, tuple)) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list)))
)
if is_batched:
__snake_case : Any = [np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa) for speech in raw_speech]
elif not is_batched and not isinstance(_SCREAMING_SNAKE_CASE , np.ndarray):
__snake_case : Tuple = np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa)
elif isinstance(_SCREAMING_SNAKE_CASE , np.ndarray) and raw_speech.dtype is np.dtype(np.floataa):
__snake_case : Union[str, Any] = raw_speech.astype(np.floataa)
# always return batch
if not is_batched:
__snake_case : str = [raw_speech]
# extract fbank features
__snake_case : List[Any] = [self._extract_fbank_features(_SCREAMING_SNAKE_CASE) for waveform in raw_speech]
# convert into correct format for padding
__snake_case : str = BatchFeature({'input_features': features})
__snake_case : Dict = self.pad(
_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , pad_to_multiple_of=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
# make sure list is in array format
__snake_case : List[str] = padded_inputs.get('input_features')
if isinstance(input_features[0] , _SCREAMING_SNAKE_CASE):
__snake_case : Union[str, Any] = [np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa) for feature in input_features]
__snake_case : Optional[int] = padded_inputs.get('attention_mask')
if attention_mask is not None:
__snake_case : int = [np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.intaa) for array in attention_mask]
# Utterance-level cepstral mean and variance normalization
if self.do_ceptral_normalize:
__snake_case : Any = (
np.array(_SCREAMING_SNAKE_CASE , dtype=np.intaa)
if self._get_padding_strategies(_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE) is not PaddingStrategy.DO_NOT_PAD
else None
)
__snake_case : Union[str, Any] = self.normalize(
padded_inputs['input_features'] , attention_mask=_SCREAMING_SNAKE_CASE)
if return_tensors is not None:
__snake_case : str = padded_inputs.convert_to_tensors(_SCREAMING_SNAKE_CASE)
return padded_inputs | 721 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
__snake_case : str = 1
for i in range(1 , num + 1 ):
fact *= i
return fact
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
__snake_case : Union[str, Any] = 0
while number > 0:
__snake_case : Dict = number % 10
sum_of_digits += last_digit
__snake_case : Union[str, Any] = number // 10 # Removing the last_digit from the given number
return sum_of_digits
def _SCREAMING_SNAKE_CASE ( A : int = 1_00 ) -> int:
"""simple docstring"""
__snake_case : List[Any] = factorial(A )
__snake_case : Dict = split_and_add(A )
return result
if __name__ == "__main__":
print(solution(int(input('''Enter the Number: ''').strip()))) | 61 | 0 |
'''simple docstring'''
import argparse
from typing import Dict
import tensorflow as tf
import torch
from tqdm import tqdm
from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration
__A = [
# tf -> hf
('''/''', '''.'''),
('''layer_''', '''layers.'''),
('''kernel''', '''weight'''),
('''beta''', '''bias'''),
('''gamma''', '''weight'''),
('''pegasus''', '''model'''),
]
__A = [
('''.output.dense''', '''.fc2'''),
('''intermediate.LayerNorm''', '''final_layer_norm'''),
('''intermediate.dense''', '''fc1'''),
]
__A = (
INIT_COMMON
+ [
('''attention.self.LayerNorm''', '''self_attn_layer_norm'''),
('''attention.output.dense''', '''self_attn.out_proj'''),
('''attention.self''', '''self_attn'''),
('''attention.encdec.LayerNorm''', '''encoder_attn_layer_norm'''),
('''attention.encdec_output.dense''', '''encoder_attn.out_proj'''),
('''attention.encdec''', '''encoder_attn'''),
('''key''', '''k_proj'''),
('''value''', '''v_proj'''),
('''query''', '''q_proj'''),
('''decoder.LayerNorm''', '''decoder.layernorm_embedding'''),
]
+ END_COMMON
)
__A = (
INIT_COMMON
+ [
('''embeddings.word_embeddings''', '''shared.weight'''),
('''embeddings.position_embeddings''', '''embed_positions.weight'''),
('''attention.self.LayerNorm''', '''self_attn_layer_norm'''),
('''attention.output.dense''', '''self_attn.output'''),
('''attention.self''', '''self_attn.self'''),
('''encoder.LayerNorm''', '''encoder.layernorm_embedding'''),
]
+ END_COMMON
)
__A = [
'''encdec/key/bias''',
'''encdec/query/bias''',
'''encdec/value/bias''',
'''self/key/bias''',
'''self/query/bias''',
'''self/value/bias''',
'''encdec_output/dense/bias''',
'''attention/output/dense/bias''',
]
def _SCREAMING_SNAKE_CASE ( A : int , A : str ) -> Dict:
"""simple docstring"""
for tf_name, hf_name in patterns:
__snake_case : List[Any] = k.replace(A , A )
return k
def _SCREAMING_SNAKE_CASE ( A : dict , A : dict ) -> BigBirdPegasusForConditionalGeneration:
"""simple docstring"""
__snake_case : Tuple = BigBirdPegasusConfig(**A )
__snake_case : Dict = BigBirdPegasusForConditionalGeneration(A )
__snake_case : int = torch_model.state_dict()
__snake_case : str = {}
# separating decoder weights
__snake_case : str = {k: tf_weights[k] for k in tf_weights if k.startswith('pegasus/decoder' )}
__snake_case : str = {k: tf_weights[k] for k in tf_weights if not k.startswith('pegasus/decoder' )}
for k, v in tqdm(decoder_weights.items() , 'tf -> hf conversion' ):
__snake_case : Tuple = [k.endswith(A ) for ending in KEYS_TO_IGNORE]
if any(A ):
continue
__snake_case : str = DECODER_PATTERNS
__snake_case : Optional[int] = rename_state_dict_key(A , A )
if new_k not in state_dict:
raise ValueError(F"""could not find new key {new_k} in state dict. (converted from {k})""" )
if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ):
__snake_case : Optional[Any] = v.T
__snake_case : Dict = torch.from_numpy(A )
assert v.shape == state_dict[new_k].shape, F"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}"""
for k, v in tqdm(remaining_weights.items() , 'tf -> hf conversion' ):
__snake_case : List[str] = [k.endswith(A ) for ending in KEYS_TO_IGNORE]
if any(A ):
continue
__snake_case : List[str] = REMAINING_PATTERNS
__snake_case : List[str] = rename_state_dict_key(A , A )
if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings":
raise ValueError(F"""could not find new key {new_k} in state dict. (converted from {k})""" )
if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ):
__snake_case : Union[str, Any] = v.T
__snake_case : Dict = torch.from_numpy(A )
if k != "pegasus/embeddings/position_embeddings":
assert v.shape == state_dict[new_k].shape, F"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}"""
__snake_case : Optional[int] = mapping['model.embed_positions.weight']
__snake_case : Tuple = mapping.pop('model.embed_positions.weight' )
__snake_case : Optional[int] = torch_model.load_state_dict(A , strict=A )
__snake_case : Optional[int] = [
k
for k in missing
if k
not in [
'final_logits_bias',
'model.encoder.embed_tokens.weight',
'model.decoder.embed_tokens.weight',
'lm_head.weight',
]
]
assert unexpected_missing == [], F"""no matches found for the following torch keys {unexpected_missing}"""
assert extra == [], F"""no matches found for the following tf keys {extra}"""
return torch_model
def _SCREAMING_SNAKE_CASE ( A : Union[str, Any] ) -> Dict:
"""simple docstring"""
__snake_case : Optional[Any] = tf.train.list_variables(A )
__snake_case : Optional[int] = {}
__snake_case : int = ['global_step']
for name, shape in tqdm(A , desc='converting tf checkpoint to dict' ):
__snake_case : str = any(pat in name for pat in ignore_name )
if skip_key:
continue
__snake_case : List[str] = tf.train.load_variable(A , A )
__snake_case : Union[str, Any] = array
return tf_weights
def _SCREAMING_SNAKE_CASE ( A : str , A : str , A : dict ) -> int:
"""simple docstring"""
__snake_case : List[Any] = get_tf_weights_as_numpy(A )
__snake_case : List[Any] = convert_bigbird_pegasus(A , A )
torch_model.save_pretrained(A )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument('''--tf_ckpt_path''', type=str, help='''passed to tf.train.list_variables''')
parser.add_argument('''--save_dir''', default=None, type=str, help='''Path to the output PyTorch model.''')
__A = parser.parse_args()
__A = {}
convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update) | 700 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import ChineseCLIPImageProcessor
class a_ ( unittest.TestCase ):
def __init__(self , __a , __a=7 , __a=3 , __a=1_8 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=None , __a=True , __a=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __a=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __a=True , ) -> List[Any]:
"""simple docstring"""
__snake_case : Tuple = size if size is not None else {'height': 2_2_4, 'width': 2_2_4}
__snake_case : Any = crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8}
__snake_case : Optional[int] = parent
__snake_case : Dict = batch_size
__snake_case : str = num_channels
__snake_case : Optional[Any] = image_size
__snake_case : Optional[int] = min_resolution
__snake_case : Tuple = max_resolution
__snake_case : Optional[int] = do_resize
__snake_case : Optional[int] = size
__snake_case : Union[str, Any] = do_center_crop
__snake_case : List[Any] = crop_size
__snake_case : int = do_normalize
__snake_case : Optional[Any] = image_mean
__snake_case : str = image_std
__snake_case : Optional[Any] = do_convert_rgb
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_convert_rgb": self.do_convert_rgb,
}
def SCREAMING_SNAKE_CASE__ (self , __a=False , __a=False , __a=False) -> List[str]:
"""simple docstring"""
assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"
if equal_resolution:
__snake_case : Optional[int] = []
for i in range(self.batch_size):
image_inputs.append(
np.random.randint(
2_5_5 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta))
else:
__snake_case : Dict = []
for i in range(self.batch_size):
__snake_case ,__snake_case : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution) , 2)
image_inputs.append(np.random.randint(2_5_5 , size=(self.num_channels, width, height) , dtype=np.uinta))
if not numpify and not torchify:
# PIL expects the channel dimension as last dimension
__snake_case : int = [Image.fromarray(np.moveaxis(__a , 0 , -1)) for x in image_inputs]
if torchify:
__snake_case : List[Any] = [torch.from_numpy(__a) for x in image_inputs]
return image_inputs
@require_torch
@require_vision
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = ChineseCLIPImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Union[str, Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=__a)
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : int = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , 'do_resize'))
self.assertTrue(hasattr(__a , 'size'))
self.assertTrue(hasattr(__a , 'do_center_crop'))
self.assertTrue(hasattr(__a , 'center_crop'))
self.assertTrue(hasattr(__a , 'do_normalize'))
self.assertTrue(hasattr(__a , 'image_mean'))
self.assertTrue(hasattr(__a , 'image_std'))
self.assertTrue(hasattr(__a , 'do_convert_rgb'))
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'height': 2_2_4, 'width': 2_2_4})
self.assertEqual(image_processor.crop_size , {'height': 1_8, 'width': 1_8})
__snake_case : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4)
self.assertEqual(image_processor.size , {'shortest_edge': 4_2})
self.assertEqual(image_processor.crop_size , {'height': 8_4, 'width': 8_4})
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
__snake_case : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
__snake_case : int = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : List[Any] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
__snake_case : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=__a , numpify=__a)
for image in image_inputs:
self.assertIsInstance(__a , np.ndarray)
# Test not batched input
__snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : int = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Any = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
__snake_case : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__a , torchify=__a)
for image in image_inputs:
self.assertIsInstance(__a , torch.Tensor)
# Test not batched input
__snake_case : Any = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : Union[str, Any] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
@require_torch
@require_vision
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = ChineseCLIPImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[Any] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__a)
__snake_case : List[Any] = 3
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Any = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , 'do_resize'))
self.assertTrue(hasattr(__a , 'size'))
self.assertTrue(hasattr(__a , 'do_center_crop'))
self.assertTrue(hasattr(__a , 'center_crop'))
self.assertTrue(hasattr(__a , 'do_normalize'))
self.assertTrue(hasattr(__a , 'image_mean'))
self.assertTrue(hasattr(__a , 'image_std'))
self.assertTrue(hasattr(__a , 'do_convert_rgb'))
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
__snake_case : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
__snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.expected_encoded_image_num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : Optional[int] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.expected_encoded_image_num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , ) | 61 | 0 |
'''simple docstring'''
from itertools import permutations
def _SCREAMING_SNAKE_CASE ( A : tuple ) -> bool:
"""simple docstring"""
if num[3] % 2 != 0:
return False
if (num[2] + num[3] + num[4]) % 3 != 0:
return False
if num[5] % 5 != 0:
return False
__snake_case : List[str] = [7, 11, 13, 17]
for i, test in enumerate(A ):
if (num[i + 4] * 1_00 + num[i + 5] * 10 + num[i + 6]) % test != 0:
return False
return True
def _SCREAMING_SNAKE_CASE ( A : int = 10 ) -> int:
"""simple docstring"""
return sum(
int(''.join(map(A , A ) ) )
for num in permutations(range(A ) )
if is_substring_divisible(A ) )
if __name__ == "__main__":
print(f'''{solution() = }''') | 701 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json''',
# See all ViT MSN models at https://huggingface.co/models?filter=vit_msn
}
class a_ ( UpperCamelCase_ ):
_snake_case = """vit_msn"""
def __init__(self , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-06 , __a=2_2_4 , __a=1_6 , __a=3 , __a=True , **__a , ) -> Any:
"""simple docstring"""
super().__init__(**__a)
__snake_case : List[str] = hidden_size
__snake_case : Optional[int] = num_hidden_layers
__snake_case : Optional[Any] = num_attention_heads
__snake_case : str = intermediate_size
__snake_case : List[str] = hidden_act
__snake_case : List[Any] = hidden_dropout_prob
__snake_case : Tuple = attention_probs_dropout_prob
__snake_case : List[str] = initializer_range
__snake_case : Optional[int] = layer_norm_eps
__snake_case : Dict = image_size
__snake_case : int = patch_size
__snake_case : Dict = num_channels
__snake_case : Tuple = qkv_bias | 61 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__A = {
'''configuration_trajectory_transformer''': [
'''TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''TrajectoryTransformerConfig''',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'''TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TrajectoryTransformerModel''',
'''TrajectoryTransformerPreTrainedModel''',
'''load_tf_weights_in_trajectory_transformer''',
]
if TYPE_CHECKING:
from .configuration_trajectory_transformer import (
TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
TrajectoryTransformerConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_trajectory_transformer import (
TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TrajectoryTransformerModel,
TrajectoryTransformerPreTrainedModel,
load_tf_weights_in_trajectory_transformer,
)
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 702 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : float , A : list[float] ) -> float:
"""simple docstring"""
if discount_rate < 0:
raise ValueError('Discount rate cannot be negative' )
if not cash_flows:
raise ValueError('Cash flows list cannot be empty' )
__snake_case : List[str] = sum(
cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(A ) )
return round(A , ndigits=2 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 61 | 0 |
'''simple docstring'''
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
convert_to_rgb,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
OPENAI_CLIP_MEAN,
OPENAI_CLIP_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
__A = logging.get_logger(__name__)
if is_vision_available():
import PIL
class a_ ( UpperCamelCase_ ):
_snake_case = ["""pixel_values"""]
def __init__(self , __a = True , __a = None , __a = PILImageResampling.BICUBIC , __a = True , __a = None , __a = True , __a = 1 / 2_5_5 , __a = True , __a = None , __a = None , __a = True , **__a , ) -> None:
"""simple docstring"""
super().__init__(**__a)
__snake_case : Dict = size if size is not None else {'shortest_edge': 2_2_4}
__snake_case : Dict = get_size_dict(__a , default_to_square=__a)
__snake_case : Optional[Any] = crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4}
__snake_case : Union[str, Any] = get_size_dict(__a , default_to_square=__a , param_name='crop_size')
__snake_case : List[str] = do_resize
__snake_case : Dict = size
__snake_case : int = resample
__snake_case : List[Any] = do_center_crop
__snake_case : Optional[int] = crop_size
__snake_case : Any = do_rescale
__snake_case : List[Any] = rescale_factor
__snake_case : Optional[Any] = do_normalize
__snake_case : Optional[Any] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
__snake_case : Tuple = image_std if image_std is not None else OPENAI_CLIP_STD
__snake_case : Optional[int] = do_convert_rgb
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = PILImageResampling.BICUBIC , __a = None , **__a , ) -> np.ndarray:
"""simple docstring"""
__snake_case : Tuple = get_size_dict(__a , default_to_square=__a)
if "shortest_edge" not in size:
raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""")
__snake_case : int = get_resize_output_image_size(__a , size=size['shortest_edge'] , default_to_square=__a)
return resize(__a , size=__a , resample=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> np.ndarray:
"""simple docstring"""
__snake_case : int = get_size_dict(__a)
if "height" not in size or "width" not in size:
raise ValueError(F"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""")
return center_crop(__a , size=(size['height'], size['width']) , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> Union[str, Any]:
"""simple docstring"""
return rescale(__a , scale=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray:
"""simple docstring"""
return normalize(__a , mean=__a , std=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image:
"""simple docstring"""
__snake_case : List[str] = do_resize if do_resize is not None else self.do_resize
__snake_case : int = size if size is not None else self.size
__snake_case : Union[str, Any] = get_size_dict(__a , param_name='size' , default_to_square=__a)
__snake_case : Any = resample if resample is not None else self.resample
__snake_case : Optional[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop
__snake_case : str = crop_size if crop_size is not None else self.crop_size
__snake_case : int = get_size_dict(__a , param_name='crop_size' , default_to_square=__a)
__snake_case : str = do_rescale if do_rescale is not None else self.do_rescale
__snake_case : Optional[int] = rescale_factor if rescale_factor is not None else self.rescale_factor
__snake_case : str = do_normalize if do_normalize is not None else self.do_normalize
__snake_case : Union[str, Any] = image_mean if image_mean is not None else self.image_mean
__snake_case : List[Any] = image_std if image_std is not None else self.image_std
__snake_case : int = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
__snake_case : List[Any] = make_list_of_images(__a)
if not valid_images(__a):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.')
if do_resize and size is None:
raise ValueError('Size must be specified if do_resize is True.')
if do_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.')
# PIL RGBA images are converted to RGB
if do_convert_rgb:
__snake_case : Dict = [convert_to_rgb(__a) for image in images]
# All transformations expect numpy arrays.
__snake_case : List[str] = [to_numpy_array(__a) for image in images]
if do_resize:
__snake_case : Any = [self.resize(image=__a , size=__a , resample=__a) for image in images]
if do_center_crop:
__snake_case : Union[str, Any] = [self.center_crop(image=__a , size=__a) for image in images]
if do_rescale:
__snake_case : Any = [self.rescale(image=__a , scale=__a) for image in images]
if do_normalize:
__snake_case : Optional[int] = [self.normalize(image=__a , mean=__a , std=__a) for image in images]
__snake_case : Optional[Any] = [to_channel_dimension_format(__a , __a) for image in images]
__snake_case : Tuple = {'pixel_values': images}
return BatchFeature(data=__a , tensor_type=__a) | 703 |
'''simple docstring'''
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__) | 61 | 0 |
'''simple docstring'''
from __future__ import annotations
import math
import random
from typing import Any
class a_ :
def __init__(self) -> None:
"""simple docstring"""
__snake_case : list[Any] = []
__snake_case : int = 0
__snake_case : int = 0
def SCREAMING_SNAKE_CASE__ (self) -> bool:
"""simple docstring"""
return self.head == self.tail
def SCREAMING_SNAKE_CASE__ (self , __a) -> None:
"""simple docstring"""
self.data.append(__a)
__snake_case : Optional[Any] = self.tail + 1
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : Optional[int] = self.data[self.head]
__snake_case : Union[str, Any] = self.head + 1
return ret
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return self.tail - self.head
def SCREAMING_SNAKE_CASE__ (self) -> None:
"""simple docstring"""
print(self.data)
print('**************')
print(self.data[self.head : self.tail])
class a_ :
def __init__(self , __a) -> None:
"""simple docstring"""
__snake_case : Tuple = data
__snake_case : MyNode | None = None
__snake_case : MyNode | None = None
__snake_case : int = 1
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
return self.data
def SCREAMING_SNAKE_CASE__ (self) -> MyNode | None:
"""simple docstring"""
return self.left
def SCREAMING_SNAKE_CASE__ (self) -> MyNode | None:
"""simple docstring"""
return self.right
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return self.height
def SCREAMING_SNAKE_CASE__ (self , __a) -> None:
"""simple docstring"""
__snake_case : Optional[int] = data
def SCREAMING_SNAKE_CASE__ (self , __a) -> None:
"""simple docstring"""
__snake_case : List[str] = node
def SCREAMING_SNAKE_CASE__ (self , __a) -> None:
"""simple docstring"""
__snake_case : Tuple = node
def SCREAMING_SNAKE_CASE__ (self , __a) -> None:
"""simple docstring"""
__snake_case : List[str] = height
def _SCREAMING_SNAKE_CASE ( A : MyNode | None ) -> int:
"""simple docstring"""
if node is None:
return 0
return node.get_height()
def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> int:
"""simple docstring"""
if a > b:
return a
return b
def _SCREAMING_SNAKE_CASE ( A : MyNode ) -> MyNode:
"""simple docstring"""
print('left rotation node:' , node.get_data() )
__snake_case : List[str] = node.get_left()
assert ret is not None
node.set_left(ret.get_right() )
ret.set_right(A )
__snake_case : Union[str, Any] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1
node.set_height(A )
__snake_case : Any = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1
ret.set_height(A )
return ret
def _SCREAMING_SNAKE_CASE ( A : MyNode ) -> MyNode:
"""simple docstring"""
print('right rotation node:' , node.get_data() )
__snake_case : List[str] = node.get_right()
assert ret is not None
node.set_right(ret.get_left() )
ret.set_left(A )
__snake_case : Optional[Any] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1
node.set_height(A )
__snake_case : Optional[int] = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1
ret.set_height(A )
return ret
def _SCREAMING_SNAKE_CASE ( A : MyNode ) -> MyNode:
"""simple docstring"""
__snake_case : Dict = node.get_left()
assert left_child is not None
node.set_left(left_rotation(A ) )
return right_rotation(A )
def _SCREAMING_SNAKE_CASE ( A : MyNode ) -> MyNode:
"""simple docstring"""
__snake_case : List[str] = node.get_right()
assert right_child is not None
node.set_right(right_rotation(A ) )
return left_rotation(A )
def _SCREAMING_SNAKE_CASE ( A : MyNode | None , A : Any ) -> MyNode | None:
"""simple docstring"""
if node is None:
return MyNode(A )
if data < node.get_data():
node.set_left(insert_node(node.get_left() , A ) )
if (
get_height(node.get_left() ) - get_height(node.get_right() ) == 2
): # an unbalance detected
__snake_case : Optional[Any] = node.get_left()
assert left_child is not None
if (
data < left_child.get_data()
): # new node is the left child of the left child
__snake_case : Union[str, Any] = right_rotation(A )
else:
__snake_case : Any = lr_rotation(A )
else:
node.set_right(insert_node(node.get_right() , A ) )
if get_height(node.get_right() ) - get_height(node.get_left() ) == 2:
__snake_case : Any = node.get_right()
assert right_child is not None
if data < right_child.get_data():
__snake_case : List[str] = rl_rotation(A )
else:
__snake_case : Dict = left_rotation(A )
__snake_case : Optional[int] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1
node.set_height(A )
return node
def _SCREAMING_SNAKE_CASE ( A : MyNode ) -> Any:
"""simple docstring"""
while True:
__snake_case : Optional[int] = root.get_right()
if right_child is None:
break
__snake_case : Any = right_child
return root.get_data()
def _SCREAMING_SNAKE_CASE ( A : MyNode ) -> Any:
"""simple docstring"""
while True:
__snake_case : Optional[Any] = root.get_left()
if left_child is None:
break
__snake_case : Tuple = left_child
return root.get_data()
def _SCREAMING_SNAKE_CASE ( A : MyNode , A : Any ) -> MyNode | None:
"""simple docstring"""
__snake_case : Tuple = root.get_left()
__snake_case : Union[str, Any] = root.get_right()
if root.get_data() == data:
if left_child is not None and right_child is not None:
__snake_case : Tuple = get_left_most(A )
root.set_data(A )
root.set_right(del_node(A , A ) )
elif left_child is not None:
__snake_case : List[str] = left_child
elif right_child is not None:
__snake_case : Dict = right_child
else:
return None
elif root.get_data() > data:
if left_child is None:
print('No such data' )
return root
else:
root.set_left(del_node(A , A ) )
else: # root.get_data() < data
if right_child is None:
return root
else:
root.set_right(del_node(A , A ) )
if get_height(A ) - get_height(A ) == 2:
assert right_child is not None
if get_height(right_child.get_right() ) > get_height(right_child.get_left() ):
__snake_case : Optional[Any] = left_rotation(A )
else:
__snake_case : Optional[Any] = rl_rotation(A )
elif get_height(A ) - get_height(A ) == -2:
assert left_child is not None
if get_height(left_child.get_left() ) > get_height(left_child.get_right() ):
__snake_case : List[Any] = right_rotation(A )
else:
__snake_case : Union[str, Any] = lr_rotation(A )
__snake_case : str = my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1
root.set_height(A )
return root
class a_ :
def __init__(self) -> None:
"""simple docstring"""
__snake_case : MyNode | None = None
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return get_height(self.root)
def SCREAMING_SNAKE_CASE__ (self , __a) -> None:
"""simple docstring"""
print('insert:' + str(__a))
__snake_case : Any = insert_node(self.root , __a)
def SCREAMING_SNAKE_CASE__ (self , __a) -> None:
"""simple docstring"""
print('delete:' + str(__a))
if self.root is None:
print('Tree is empty!')
return
__snake_case : Union[str, Any] = del_node(self.root , __a)
def __str__(self , ) -> str: # a level traversale, gives a more intuitive look on the tree
"""simple docstring"""
__snake_case : List[str] = ''
__snake_case : Optional[int] = MyQueue()
q.push(self.root)
__snake_case : Union[str, Any] = self.get_height()
if layer == 0:
return output
__snake_case : Union[str, Any] = 0
while not q.is_empty():
__snake_case : Dict = q.pop()
__snake_case : Tuple = ' ' * int(math.pow(2 , layer - 1))
output += space
if node is None:
output += "*"
q.push(__a)
q.push(__a)
else:
output += str(node.get_data())
q.push(node.get_left())
q.push(node.get_right())
output += space
__snake_case : Optional[Any] = cnt + 1
for i in range(1_0_0):
if cnt == math.pow(2 , __a) - 1:
__snake_case : Dict = layer - 1
if layer == 0:
output += "\n*************************************"
return output
output += "\n"
break
output += "\n*************************************"
return output
def _SCREAMING_SNAKE_CASE ( ) -> None:
"""simple docstring"""
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
__A = AVLtree()
__A = list(range(1_0))
random.shuffle(lst)
for i in lst:
t.insert(i)
print(str(t))
random.shuffle(lst)
for i in lst:
t.del_node(i)
print(str(t)) | 704 |
'''simple docstring'''
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run
import sys
import warnings
from os.path import abspath, dirname, join
# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
__A = abspath(join(dirname(dirname(__file__)), '''src'''))
sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='''ignore''', category=FutureWarning)
def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> str:
"""simple docstring"""
from diffusers.utils.testing_utils import pytest_addoption_shared
pytest_addoption_shared(A )
def _SCREAMING_SNAKE_CASE ( A : int ) -> Optional[int]:
"""simple docstring"""
from diffusers.utils.testing_utils import pytest_terminal_summary_main
__snake_case : Any = terminalreporter.config.getoption('--make-reports' )
if make_reports:
pytest_terminal_summary_main(A , id=A ) | 61 | 0 |
'''simple docstring'''
from functools import lru_cache
@lru_cache
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
if num < 0:
raise ValueError('Number should not be negative.' )
return 1 if num in (0, 1) else num * factorial(num - 1 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 705 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
__A = {
'''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''],
'''tokenization_biogpt''': ['''BioGptTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''BioGptForCausalLM''',
'''BioGptForTokenClassification''',
'''BioGptForSequenceClassification''',
'''BioGptModel''',
'''BioGptPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig
from .tokenization_biogpt import BioGptTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_biogpt import (
BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST,
BioGptForCausalLM,
BioGptForSequenceClassification,
BioGptForTokenClassification,
BioGptModel,
BioGptPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 61 | 0 |
'''simple docstring'''
import unittest
from transformers import AlbertTokenizer, AlbertTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
__A = get_tests_dir('''fixtures/spiece.model''')
@require_sentencepiece
@require_tokenizers
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = AlbertTokenizer
_snake_case = AlbertTokenizerFast
_snake_case = True
_snake_case = True
_snake_case = True
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
super().setUp()
# We have a SentencePiece fixture for testing
__snake_case : List[str] = AlbertTokenizer(__a)
tokenizer.save_pretrained(self.tmpdirname)
def SCREAMING_SNAKE_CASE__ (self , __a) -> List[Any]:
"""simple docstring"""
__snake_case : Tuple = 'this is a test'
__snake_case : List[str] = 'this is a test'
return input_text, output_text
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : int = '<pad>'
__snake_case : Optional[Any] = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a) , __a)
self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a) , __a)
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Optional[Any] = list(self.get_tokenizer().get_vocab().keys())
self.assertEqual(vocab_keys[0] , '<pad>')
self.assertEqual(vocab_keys[1] , '<unk>')
self.assertEqual(vocab_keys[-1] , '▁eloquent')
self.assertEqual(len(__a) , 3_0_0_0_0)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
self.assertEqual(self.get_tokenizer().vocab_size , 3_0_0_0_0)
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
if not self.test_rust_tokenizer:
return
__snake_case : Optional[int] = self.get_tokenizer()
__snake_case : Optional[Any] = self.get_rust_tokenizer()
__snake_case : Union[str, Any] = 'I was born in 92000, and this is falsé.'
__snake_case : int = tokenizer.tokenize(__a)
__snake_case : List[str] = rust_tokenizer.tokenize(__a)
self.assertListEqual(__a , __a)
__snake_case : int = tokenizer.encode(__a , add_special_tokens=__a)
__snake_case : Optional[Any] = rust_tokenizer.encode(__a , add_special_tokens=__a)
self.assertListEqual(__a , __a)
__snake_case : Union[str, Any] = self.get_rust_tokenizer()
__snake_case : int = tokenizer.encode(__a)
__snake_case : List[Any] = rust_tokenizer.encode(__a)
self.assertListEqual(__a , __a)
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case : Tuple = AlbertTokenizer(__a , keep_accents=__a)
__snake_case : List[Any] = tokenizer.tokenize('This is a test')
self.assertListEqual(__a , ['▁this', '▁is', '▁a', '▁test'])
self.assertListEqual(tokenizer.convert_tokens_to_ids(__a) , [4_8, 2_5, 2_1, 1_2_8_9])
__snake_case : Optional[Any] = tokenizer.tokenize('I was born in 92000, and this is falsé.')
self.assertListEqual(
__a , ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.'])
__snake_case : int = tokenizer.convert_tokens_to_ids(__a)
self.assertListEqual(__a , [3_1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9])
__snake_case : Union[str, Any] = tokenizer.convert_ids_to_tokens(__a)
self.assertListEqual(
__a , ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.'] , )
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : Union[str, Any] = AlbertTokenizer(__a)
__snake_case : Tuple = tokenizer.encode('sequence builders')
__snake_case : Any = tokenizer.encode('multi-sequence build')
__snake_case : List[str] = tokenizer.build_inputs_with_special_tokens(__a)
__snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__a , __a)
assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [
tokenizer.sep_token_id
]
@slow
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case : int = {'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'input_ids': [[2, 2_1_9_7_0, 1_3, 5, 6_0_9_2, 1_6_7, 2_8, 7_1_0_3, 2_1_5_3, 6_7_3, 8, 7_0_2_8, 1_2_0_5_1, 1_8, 1_7, 7_1_0_3, 2_1_5_3, 6_7_3, 8, 3_5_1_5, 1_8_6_8_4, 8, 4_4_6_1, 6, 1_9_2_7, 2_9_7, 8, 1_2_0_6_0, 2_6_0_7, 1_8, 1_3, 5, 4_4_6_1, 1_5, 1_0_5_3_8, 3_8, 8, 1_3_5, 1_5, 8_2_2, 5_8, 1_5, 9_9_3, 1_0_3_6_3, 1_5, 1_4_6_0, 8_0_0_5, 4_4_6_1, 1_5, 9_9_3, 2_5_5, 2_3_2_8, 9, 9, 9, 6, 2_6, 1_1_1_2, 8_1_6, 3_2_6_0, 1_3, 5, 1_0_3, 2_3_7_7, 6, 1_7, 1_1_1_2, 8_1_6, 2_7_8_2, 1_3, 5, 1_0_3, 1_0_6_4_1, 6, 2_9, 8_4, 2_5_1_2, 2_4_3_0, 7_8_2, 1_8_6_8_4, 2_7_6_1, 1_9, 8_0_8, 2_4_3_0, 2_5_5_6, 1_7, 8_5_5, 1_4_8_0, 9_4_7_7, 4_0_9_1, 1_2_8, 1_1_7_1_2, 1_5, 7_1_0_3, 2_1_5_3, 6_7_3, 1_7, 2_4_8_8_3, 9_9_9_0, 9, 3], [2, 1_1_5_0_2, 2_5, 1_0_0_6, 2_0, 7_8_2, 8, 1_1_8_0_9, 8_5_5, 1_7_3_2, 1_9_3_9_3, 1_8_6_6_7, 3_7, 3_6_7, 2_1_0_1_8, 6_9, 1_8_5_4, 3_4, 1_1_8_6_0, 1_9_1_2_4, 2_7, 1_5_6, 2_2_5, 1_7, 1_9_3, 4_1_4_1, 1_9, 6_5, 9_1_2_4, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 1_4, 2_2_3_1, 8_8_6, 2_3_8_5, 1_7_6_5_9, 8_4, 1_4, 1_6_7_9_2, 1_9_5_2, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=__a , model_name='albert-base-v2' , revision='6b6560eaf5ff2e250b00c50f380c5389a9c2d82e' , ) | 706 |
'''simple docstring'''
from packaging import version
from .import_utils import is_accelerate_available
if is_accelerate_available():
import accelerate
def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> int:
"""simple docstring"""
if not is_accelerate_available():
return method
__snake_case : Optional[Any] = version.parse(accelerate.__version__ ).base_version
if version.parse(A ) < version.parse('0.17.0' ):
return method
def wrapper(self : Optional[Any] , *A : Optional[Any] , **A : Optional[int] ):
if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ):
self._hf_hook.pre_forward(self )
return method(self , *A , **A )
return wrapper | 61 | 0 |
'''simple docstring'''
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
from torch import nn
from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel
from transformers.utils import ModelOutput
@dataclass
class a_ ( UpperCamelCase_ ):
_snake_case = None
_snake_case = None
_snake_case = None
_snake_case = None
class a_ ( UpperCamelCase_ ):
def __init__(self , __a=1 , __a=0 , __a=2 , __a=5_1_2 , __a="cls" , __a=False , __a=True , **__a , ) -> Any:
"""simple docstring"""
super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a)
__snake_case : Optional[int] = project_dim
__snake_case : Tuple = pooler_fn
__snake_case : Tuple = learn_encoder
__snake_case : Union[str, Any] = use_attention_mask
class a_ ( UpperCamelCase_ ):
_snake_case = [r"""pooler""", r"""logit_scale"""]
_snake_case = [r"""position_ids""", r"""predictions.decoder.bias"""]
_snake_case = """roberta"""
_snake_case = RobertaSeriesConfig
def __init__(self , __a) -> Optional[int]:
"""simple docstring"""
super().__init__(__a)
__snake_case : List[Any] = XLMRobertaModel(__a)
__snake_case : Optional[int] = nn.Linear(config.hidden_size , config.project_dim)
__snake_case : Optional[int] = getattr(__a , 'has_pre_transformation' , __a)
if self.has_pre_transformation:
__snake_case : Optional[int] = nn.Linear(config.hidden_size , config.project_dim)
__snake_case : Dict = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps)
self.post_init()
def SCREAMING_SNAKE_CASE__ (self , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , ) -> List[str]:
"""simple docstring"""
__snake_case : int = return_dict if return_dict is not None else self.config.use_return_dict
__snake_case : Optional[int] = self.base_model(
input_ids=__a , attention_mask=__a , token_type_ids=__a , position_ids=__a , head_mask=__a , inputs_embeds=__a , encoder_hidden_states=__a , encoder_attention_mask=__a , output_attentions=__a , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=__a , )
if self.has_pre_transformation:
__snake_case : int = outputs['hidden_states'][-2]
__snake_case : List[str] = self.pre_LN(__a)
__snake_case : Union[str, Any] = self.transformation_pre(__a)
return TransformationModelOutput(
projection_state=__a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
else:
__snake_case : Any = self.transformation(outputs.last_hidden_state)
return TransformationModelOutput(
projection_state=__a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) | 707 |
'''simple docstring'''
import unittest
from transformers import load_tool
from transformers.utils import is_torch_available
if is_torch_available():
import torch
from transformers.testing_utils import require_torch
from .test_tools_common import ToolTesterMixin
@require_torch
class a_ ( unittest.TestCase , UpperCamelCase_ ):
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[str] = load_tool('text-to-speech')
self.tool.setup()
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : Dict = self.tool('hey')
__snake_case : List[Any] = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , ))
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : Any = self.tool('hey')
__snake_case : Any = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , )) | 61 | 0 |
'''simple docstring'''
from __future__ import annotations
from collections import deque
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any
@dataclass
class a_ :
_snake_case = 42
_snake_case = None
_snake_case = None
def _SCREAMING_SNAKE_CASE ( ) -> Node | None:
"""simple docstring"""
__snake_case : str = Node(1 )
__snake_case : Tuple = Node(2 )
__snake_case : Optional[int] = Node(3 )
__snake_case : List[str] = Node(4 )
__snake_case : List[str] = Node(5 )
return tree
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return [root.data, *preorder(root.left ), *preorder(root.right )] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return postorder(root.left ) + postorder(root.right ) + [root.data] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return [*inorder(root.left ), root.data, *inorder(root.right )] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> int:
"""simple docstring"""
return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
if root is None:
return output
__snake_case : Optional[int] = deque([root] )
while process_queue:
__snake_case : List[str] = process_queue.popleft()
output.append(node.data )
if node.left:
process_queue.append(node.left )
if node.right:
process_queue.append(node.right )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
def populate_output(A : Node | None , A : int ) -> None:
if not root:
return
if level == 1:
output.append(root.data )
elif level > 1:
populate_output(root.left , level - 1 )
populate_output(root.right , level - 1 )
populate_output(A , A )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
def populate_output(A : Node | None , A : int ) -> None:
if root is None:
return
if level == 1:
output.append(root.data )
elif level > 1:
populate_output(root.right , level - 1 )
populate_output(root.left , level - 1 )
populate_output(A , A )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None] | list[Any]:
"""simple docstring"""
if root is None:
return []
__snake_case : list[Sequence[Node | None]] = []
__snake_case : List[Any] = 0
__snake_case : int = height(A )
for h in range(1 , height_tree + 1 ):
if not flag:
output.append(get_nodes_from_left_to_right(A , A ) )
__snake_case : int = 1
else:
output.append(get_nodes_from_right_to_left(A , A ) )
__snake_case : Tuple = 0
return output
def _SCREAMING_SNAKE_CASE ( ) -> None: # Main function for testing.
"""simple docstring"""
__snake_case : Optional[int] = make_tree()
print(F"""In-order Traversal: {inorder(A )}""" )
print(F"""Pre-order Traversal: {preorder(A )}""" )
print(F"""Post-order Traversal: {postorder(A )}""" , '\n' )
print(F"""Height of Tree: {height(A )}""" , '\n' )
print('Complete Level Order Traversal: ' )
print(level_order(A ) , '\n' )
print('Level-wise order Traversal: ' )
for level in range(1 , height(A ) + 1 ):
print(F"""Level {level}:""" , get_nodes_from_left_to_right(A , level=A ) )
print('\nZigZag order Traversal: ' )
print(zigzag(A ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main() | 708 |
'''simple docstring'''
import math
class a_ :
def __init__(self , __a=0) -> Any: # a graph with Node 0,1,...,N-1
"""simple docstring"""
__snake_case : List[str] = n
__snake_case : Tuple = [
[math.inf for j in range(0 , __a)] for i in range(0 , __a)
] # adjacency matrix for weight
__snake_case : Union[str, Any] = [
[math.inf for j in range(0 , __a)] for i in range(0 , __a)
] # dp[i][j] stores minimum distance from i to j
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple:
"""simple docstring"""
__snake_case : Union[str, Any] = w
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
for k in range(0 , self.n):
for i in range(0 , self.n):
for j in range(0 , self.n):
__snake_case : List[Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j])
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Optional[int]:
"""simple docstring"""
return self.dp[u][v]
if __name__ == "__main__":
__A = Graph(5)
graph.add_edge(0, 2, 9)
graph.add_edge(0, 4, 1_0)
graph.add_edge(1, 3, 5)
graph.add_edge(2, 3, 7)
graph.add_edge(3, 0, 1_0)
graph.add_edge(3, 1, 2)
graph.add_edge(3, 2, 1)
graph.add_edge(3, 4, 6)
graph.add_edge(4, 1, 3)
graph.add_edge(4, 2, 4)
graph.add_edge(4, 3, 9)
graph.floyd_warshall()
graph.show_min(1, 4)
graph.show_min(0, 3) | 61 | 0 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A = logging.get_logger(__name__)
class a_ ( UpperCamelCase_ ):
_snake_case = """timm_backbone"""
def __init__(self , __a=None , __a=3 , __a=True , __a=True , __a=None , **__a , ) -> Union[str, Any]:
super().__init__(**__a)
__snake_case : List[str] = backbone
__snake_case : Dict = num_channels
__snake_case : List[Any] = features_only
__snake_case : str = use_pretrained_backbone
__snake_case : Optional[int] = True
__snake_case : List[str] = out_indices if out_indices is not None else (-1,) | 709 |
'''simple docstring'''
from typing import Dict, List, Optional, Union
import numpy as np
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,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_vision_available():
import PIL
__A = logging.get_logger(__name__)
class a_ ( UpperCamelCase_ ):
_snake_case = ["""pixel_values"""]
def __init__(self , __a = True , __a = None , __a = None , __a = PILImageResampling.BILINEAR , __a = True , __a = 1 / 2_5_5 , __a = True , __a = None , __a = None , **__a , ) -> None:
"""simple docstring"""
super().__init__(**__a)
__snake_case : Tuple = size if size is not None else {'shortest_edge': 3_8_4}
__snake_case : List[Any] = get_size_dict(__a , default_to_square=__a)
__snake_case : int = do_resize
__snake_case : List[str] = size
# Default value set here for backwards compatibility where the value in config is None
__snake_case : Any = crop_pct if crop_pct is not None else 2_2_4 / 2_5_6
__snake_case : Tuple = resample
__snake_case : Dict = do_rescale
__snake_case : Any = rescale_factor
__snake_case : str = do_normalize
__snake_case : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
__snake_case : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = PILImageResampling.BICUBIC , __a = None , **__a , ) -> np.ndarray:
"""simple docstring"""
__snake_case : Dict = get_size_dict(__a , default_to_square=__a)
if "shortest_edge" not in size:
raise ValueError(F"""Size dictionary must contain 'shortest_edge' key. Got {size.keys()}""")
__snake_case : List[str] = size['shortest_edge']
if shortest_edge < 3_8_4:
# maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
__snake_case : Any = int(shortest_edge / crop_pct)
__snake_case : Any = get_resize_output_image_size(__a , size=__a , default_to_square=__a)
__snake_case : int = resize(image=__a , size=__a , resample=__a , data_format=__a , **__a)
# then crop to (shortest_edge, shortest_edge)
return center_crop(image=__a , size=(shortest_edge, shortest_edge) , data_format=__a , **__a)
else:
# warping (no cropping) when evaluated at 384 or larger
return resize(
__a , size=(shortest_edge, shortest_edge) , resample=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a = None , **__a , ) -> Any:
"""simple docstring"""
return rescale(__a , scale=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray:
"""simple docstring"""
return normalize(__a , mean=__a , std=__a , data_format=__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image:
"""simple docstring"""
__snake_case : Optional[int] = do_resize if do_resize is not None else self.do_resize
__snake_case : Dict = crop_pct if crop_pct is not None else self.crop_pct
__snake_case : Tuple = resample if resample is not None else self.resample
__snake_case : Any = do_rescale if do_rescale is not None else self.do_rescale
__snake_case : Any = rescale_factor if rescale_factor is not None else self.rescale_factor
__snake_case : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize
__snake_case : Optional[int] = image_mean if image_mean is not None else self.image_mean
__snake_case : Optional[Any] = image_std if image_std is not None else self.image_std
__snake_case : List[str] = size if size is not None else self.size
__snake_case : Any = get_size_dict(__a , default_to_square=__a)
__snake_case : Dict = make_list_of_images(__a)
if not valid_images(__a):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.')
if do_resize and size is None or resample is None:
raise ValueError('Size and resample must be specified if do_resize is True.')
if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None:
raise ValueError('crop_pct must be specified if size < 384.')
if do_rescale and rescale_factor is None:
raise ValueError('Rescale factor must be specified if do_rescale is True.')
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('Image mean and std must be specified if do_normalize is True.')
# All transformations expect numpy arrays.
__snake_case : Tuple = [to_numpy_array(__a) for image in images]
if do_resize:
__snake_case : Optional[int] = [self.resize(image=__a , size=__a , crop_pct=__a , resample=__a) for image in images]
if do_rescale:
__snake_case : Optional[int] = [self.rescale(image=__a , scale=__a) for image in images]
if do_normalize:
__snake_case : Any = [self.normalize(image=__a , mean=__a , std=__a) for image in images]
__snake_case : Dict = [to_channel_dimension_format(__a , __a) for image in images]
__snake_case : Union[str, Any] = {'pixel_values': images}
return BatchFeature(data=__a , tensor_type=__a) | 61 | 0 |
from __future__ import annotations
def _SCREAMING_SNAKE_CASE ( A : list , A : int | None = None , A : int | None = None ) -> None:
"""simple docstring"""
if start is None:
__snake_case : Union[str, Any] = 0
if end is None:
__snake_case : int = len(A ) - 1
if start >= end:
return
__snake_case : Tuple = (start + end) // 2
slowsort(A , A , A )
slowsort(A , mid + 1 , A )
if sequence[end] < sequence[mid]:
__snake_case : Dict = sequence[mid], sequence[end]
slowsort(A , A , end - 1 )
if __name__ == "__main__":
from doctest import testmod
testmod() | 710 |
'''simple docstring'''
from functools import lru_cache
@lru_cache
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
if num < 0:
raise ValueError('Number should not be negative.' )
return 1 if num in (0, 1) else num * factorial(num - 1 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 61 | 0 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> str:
"""simple docstring"""
if a < 0 or b < 0:
raise ValueError('the value of both inputs must be positive' )
__snake_case : int = str(bin(A ) )[2:] # remove the leading "0b"
__snake_case : Optional[int] = str(bin(A ) )[2:] # remove the leading "0b"
__snake_case : List[Any] = max(len(A ) , len(A ) )
return "0b" + "".join(
str(int(char_a == '1' and char_b == '1' ) )
for char_a, char_b in zip(a_binary.zfill(A ) , b_binary.zfill(A ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod() | 711 |
'''simple docstring'''
import unittest
import torch
from diffusers import VQModel
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism
from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ):
_snake_case = VQModel
_snake_case = """sample"""
@property
def SCREAMING_SNAKE_CASE__ (self , __a=(3_2, 3_2)) -> str:
"""simple docstring"""
__snake_case : Dict = 4
__snake_case : Optional[int] = 3
__snake_case : str = floats_tensor((batch_size, num_channels) + sizes).to(__a)
return {"sample": image}
@property
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
return (3, 3_2, 3_2)
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
return (3, 3_2, 3_2)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[Any] = {
'block_out_channels': [3_2, 6_4],
'in_channels': 3,
'out_channels': 3,
'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'],
'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'],
'latent_channels': 3,
}
__snake_case : List[Any] = self.dummy_input
return init_dict, inputs_dict
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case ,__snake_case : List[Any] = VQModel.from_pretrained('fusing/vqgan-dummy' , output_loading_info=__a)
self.assertIsNotNone(__a)
self.assertEqual(len(loading_info['missing_keys']) , 0)
model.to(__a)
__snake_case : Any = model(**self.dummy_input)
assert image is not None, "Make sure output is not None"
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : Union[str, Any] = VQModel.from_pretrained('fusing/vqgan-dummy')
model.to(__a).eval()
torch.manual_seed(0)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(0)
__snake_case : Tuple = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size)
__snake_case : Optional[int] = image.to(__a)
with torch.no_grad():
__snake_case : List[Any] = model(__a).sample
__snake_case : int = output[0, -1, -3:, -3:].flatten().cpu()
# fmt: off
__snake_case : int = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143])
# fmt: on
self.assertTrue(torch.allclose(__a , __a , atol=1E-3)) | 61 | 0 |
'''simple docstring'''
from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
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 (
VersatileDiffusionDualGuidedPipeline,
VersatileDiffusionImageVariationPipeline,
VersatileDiffusionPipeline,
VersatileDiffusionTextToImagePipeline,
)
else:
from .modeling_text_unet import UNetFlatConditionModel
from .pipeline_versatile_diffusion import VersatileDiffusionPipeline
from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline
from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline
from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline | 712 |
'''simple docstring'''
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
__A = logging.getLogger(__name__)
@dataclass
class a_ :
_snake_case = field(
metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} )
_snake_case = field(
default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} )
_snake_case = 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.
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , )
@dataclass
class a_ :
_snake_case = field(
metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , )
_snake_case = field(
default=128 , metadata={
"""help""": (
"""The maximum total input sequence length after tokenization. Sequences longer """
"""than this will be truncated, sequences shorter will be padded."""
)
} , )
_snake_case = field(
default=UpperCamelCase_ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} )
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
# 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.
__snake_case : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
__snake_case ,__snake_case ,__snake_case : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
__snake_case ,__snake_case ,__snake_case : int = 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.' )
__snake_case : List[str] = import_module('tasks' )
try:
__snake_case : Any = getattr(A , model_args.task_type )
__snake_case : TokenClassificationTask = 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' , A )
# Set seed
set_seed(training_args.seed )
# Prepare CONLL-2003 task
__snake_case : Optional[Any] = token_classification_task.get_labels(data_args.labels )
__snake_case : Dict[int, str] = dict(enumerate(A ) )
__snake_case : Optional[Any] = len(A )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
__snake_case : Any = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=A , idalabel=A , labelaid={label: i for i, label in enumerate(A )} , cache_dir=model_args.cache_dir , )
__snake_case : List[str] = 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 , )
__snake_case : Optional[int] = AutoModelForTokenClassification.from_pretrained(
model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=A , cache_dir=model_args.cache_dir , )
# Get datasets
__snake_case : List[Any] = (
TokenClassificationDataset(
token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , 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
)
__snake_case : int = (
TokenClassificationDataset(
token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , 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(A : np.ndarray , A : np.ndarray ) -> Tuple[List[int], List[int]]:
__snake_case : str = np.argmax(A , axis=2 )
__snake_case ,__snake_case : int = preds.shape
__snake_case : Dict = [[] for _ in range(A )]
__snake_case : Union[str, Any] = [[] for _ in range(A )]
for i in range(A ):
for j in range(A ):
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(A : EvalPrediction ) -> Dict:
__snake_case ,__snake_case : Any = align_predictions(p.predictions , p.label_ids )
return {
"accuracy_score": accuracy_score(A , A ),
"precision": precision_score(A , A ),
"recall": recall_score(A , A ),
"f1": fa_score(A , A ),
}
# Data collator
__snake_case : Optional[int] = DataCollatorWithPadding(A , pad_to_multiple_of=8 ) if training_args.fpaa else None
# Initialize our Trainer
__snake_case : Optional[Any] = Trainer(
model=A , args=A , train_dataset=A , eval_dataset=A , compute_metrics=A , data_collator=A , )
# 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
__snake_case : List[Any] = {}
if training_args.do_eval:
logger.info('*** Evaluate ***' )
__snake_case : List[str] = trainer.evaluate()
__snake_case : Tuple = os.path.join(training_args.output_dir , 'eval_results.txt' )
if trainer.is_world_process_zero():
with open(A , 'w' ) as writer:
logger.info('***** Eval results *****' )
for key, value in result.items():
logger.info(' %s = %s' , A , A )
writer.write('%s = %s\n' % (key, value) )
results.update(A )
# Predict
if training_args.do_predict:
__snake_case : str = TokenClassificationDataset(
token_classification_task=A , data_dir=data_args.data_dir , tokenizer=A , labels=A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , )
__snake_case ,__snake_case ,__snake_case : str = trainer.predict(A )
__snake_case ,__snake_case : List[str] = align_predictions(A , A )
__snake_case : Optional[int] = os.path.join(training_args.output_dir , 'test_results.txt' )
if trainer.is_world_process_zero():
with open(A , 'w' ) as writer:
for key, value in metrics.items():
logger.info(' %s = %s' , A , A )
writer.write('%s = %s\n' % (key, value) )
# Save predictions
__snake_case : List[str] = os.path.join(training_args.output_dir , 'test_predictions.txt' )
if trainer.is_world_process_zero():
with open(A , 'w' ) as writer:
with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f:
token_classification_task.write_predictions_to_file(A , A , A )
return results
def _SCREAMING_SNAKE_CASE ( A : int ) -> Any:
"""simple docstring"""
# For xla_spawn (TPUs)
main()
if __name__ == "__main__":
main() | 61 | 0 |
'''simple docstring'''
import gc
import random
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DiffusionPipeline,
EulerDiscreteScheduler,
StableDiffusionXLImgaImgPipeline,
UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..pipeline_params import (
IMAGE_TO_IMAGE_IMAGE_PARAMS,
TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin
enable_full_determinism()
class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ):
_snake_case = StableDiffusionXLImgaImgPipeline
_snake_case = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
_snake_case = PipelineTesterMixin.required_optional_params - {"""latents"""}
_snake_case = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
_snake_case = IMAGE_TO_IMAGE_IMAGE_PARAMS
_snake_case = IMAGE_TO_IMAGE_IMAGE_PARAMS
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : int = UNetaDConditionModel(
block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , attention_head_dim=(2, 4) , use_linear_projection=__a , addition_embed_type='text_time' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , )
__snake_case : Any = EulerDiscreteScheduler(
beta_start=0.00_085 , beta_end=0.012 , steps_offset=1 , beta_schedule='scaled_linear' , timestep_spacing='leading' , )
torch.manual_seed(0)
__snake_case : List[str] = AutoencoderKL(
block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , )
torch.manual_seed(0)
__snake_case : str = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=3_2 , )
__snake_case : Any = CLIPTextModel(__a)
__snake_case : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__a)
__snake_case : int = CLIPTextModelWithProjection(__a)
__snake_case : Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' , local_files_only=__a)
__snake_case : Union[str, Any] = {
'unet': unet,
'scheduler': scheduler,
'vae': vae,
'text_encoder': text_encoder,
'tokenizer': tokenizer,
'text_encoder_2': text_encoder_a,
'tokenizer_2': tokenizer_a,
# "safety_checker": None,
# "feature_extractor": None,
}
return components
def SCREAMING_SNAKE_CASE__ (self , __a , __a=0) -> Tuple:
"""simple docstring"""
__snake_case : Optional[Any] = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__a)).to(__a)
__snake_case : Optional[int] = image / 2 + 0.5
if str(__a).startswith('mps'):
__snake_case : Dict = torch.manual_seed(__a)
else:
__snake_case : Dict = torch.Generator(device=__a).manual_seed(__a)
__snake_case : List[Any] = {
'prompt': 'A painting of a squirrel eating a burger',
'image': image,
'generator': generator,
'num_inference_steps': 2,
'guidance_scale': 5.0,
'output_type': 'numpy',
'strength': 0.75,
}
return inputs
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : str = 'cpu' # ensure determinism for the device-dependent torch.Generator
__snake_case : Optional[Any] = self.get_dummy_components()
__snake_case : int = StableDiffusionXLImgaImgPipeline(**__a)
__snake_case : Optional[int] = sd_pipe.to(__a)
sd_pipe.set_progress_bar_config(disable=__a)
__snake_case : List[Any] = self.get_dummy_inputs(__a)
__snake_case : List[Any] = sd_pipe(**__a).images
__snake_case : Any = image[0, -3:, -3:, -1]
assert image.shape == (1, 3_2, 3_2, 3)
__snake_case : Optional[int] = np.array([0.4_656, 0.4_840, 0.4_439, 0.6_698, 0.5_574, 0.4_524, 0.5_799, 0.5_943, 0.5_165])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
super().test_attention_slicing_forward_pass(expected_max_diff=3E-3)
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
super().test_inference_batch_single_identical(expected_max_diff=3E-3)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
__snake_case : Optional[int] = self.get_dummy_components()
__snake_case : Tuple = StableDiffusionXLImgaImgPipeline(**__a)
__snake_case : Optional[int] = sd_pipe.to(__a)
__snake_case : Optional[Any] = sd_pipe.to(__a)
sd_pipe.set_progress_bar_config(disable=__a)
# forward without prompt embeds
__snake_case : Union[str, Any] = self.get_dummy_inputs(__a)
__snake_case : int = 3 * ['this is a negative prompt']
__snake_case : Optional[Any] = negative_prompt
__snake_case : str = 3 * [inputs['prompt']]
__snake_case : Dict = sd_pipe(**__a)
__snake_case : Union[str, Any] = output.images[0, -3:, -3:, -1]
# forward with prompt embeds
__snake_case : int = self.get_dummy_inputs(__a)
__snake_case : Tuple = 3 * ['this is a negative prompt']
__snake_case : Union[str, Any] = 3 * [inputs.pop('prompt')]
(
__snake_case
) : Tuple = sd_pipe.encode_prompt(__a , negative_prompt=__a)
__snake_case : str = sd_pipe(
**__a , prompt_embeds=__a , negative_prompt_embeds=__a , pooled_prompt_embeds=__a , negative_pooled_prompt_embeds=__a , )
__snake_case : str = output.images[0, -3:, -3:, -1]
# make sure that it's equal
assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()).max() < 1E-4
@slow
@require_torch_gpu
class a_ ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def SCREAMING_SNAKE_CASE__ (self , __a , __a="cpu" , __a=torch.floataa , __a=0) -> Any:
"""simple docstring"""
__snake_case : int = torch.Generator(device=__a).manual_seed(__a)
__snake_case : Tuple = np.random.RandomState(__a).standard_normal((1, 4, 6_4, 6_4))
__snake_case : Tuple = torch.from_numpy(__a).to(device=__a , dtype=__a)
__snake_case : Tuple = {
'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) -> Tuple:
"""simple docstring"""
__snake_case : Optional[int] = DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base')
pipe.to(__a)
pipe.set_progress_bar_config(disable=__a)
__snake_case : Tuple = self.get_inputs(__a)
__snake_case : Any = pipe(**__a).images
__snake_case : Any = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 5_1_2, 5_1_2, 3)
__snake_case : Optional[int] = np.array([0.49_493, 0.47_896, 0.40_798, 0.54_214, 0.53_212, 0.48_202, 0.47_656, 0.46_329, 0.48_506])
assert np.abs(image_slice - expected_slice).max() < 7E-3 | 713 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : list ) -> list:
"""simple docstring"""
__snake_case : Tuple = False
while is_sorted is False: # Until all the indices are traversed keep looping
__snake_case : Optional[Any] = True
for i in range(0 , len(A ) - 1 , 2 ): # iterating over all even indices
if input_list[i] > input_list[i + 1]:
__snake_case ,__snake_case : int = input_list[i + 1], input_list[i]
# swapping if elements not in order
__snake_case : List[Any] = False
for i in range(1 , len(A ) - 1 , 2 ): # iterating over all odd indices
if input_list[i] > input_list[i + 1]:
__snake_case ,__snake_case : Tuple = input_list[i + 1], input_list[i]
# swapping if elements not in order
__snake_case : Any = False
return input_list
if __name__ == "__main__":
print('''Enter list to be sorted''')
__A = [int(x) for x in input().split()]
# inputing elements of the list in one line
__A = odd_even_sort(input_list)
print('''The sorted list is''')
print(sorted_list) | 61 | 0 |
'''simple docstring'''
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import cached_download, hf_hub_url
from PIL import Image
from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
__A = logging.get_logger(__name__)
def _SCREAMING_SNAKE_CASE ( A : int ) -> str:
__snake_case : List[Any] = DPTConfig(embedding_type='hybrid' )
if "large" in checkpoint_url:
__snake_case : Optional[Any] = 10_24
__snake_case : Union[str, Any] = 40_96
__snake_case : Any = 24
__snake_case : int = 16
__snake_case : Dict = [5, 11, 17, 23]
__snake_case : List[str] = [2_56, 5_12, 10_24, 10_24]
__snake_case : Optional[Any] = (1, 3_84, 3_84)
if "nyu" or "midas" in checkpoint_url:
__snake_case : int = 7_68
__snake_case : Tuple = [1, 1, 1, 0.5]
__snake_case : Union[str, Any] = [2_56, 5_12, 7_68, 7_68]
__snake_case : Optional[int] = 1_50
__snake_case : Any = 16
__snake_case : Optional[Any] = (1, 3_84, 3_84)
__snake_case : int = False
__snake_case : List[str] = 'project'
if "ade" in checkpoint_url:
__snake_case : List[str] = True
__snake_case : List[str] = 7_68
__snake_case : Optional[int] = [1, 1, 1, 0.5]
__snake_case : Optional[Any] = 1_50
__snake_case : int = 16
__snake_case : Any = 'huggingface/label-files'
__snake_case : Optional[Any] = 'ade20k-id2label.json'
__snake_case : Tuple = json.load(open(cached_download(hf_hub_url(A , A , repo_type='dataset' ) ) , 'r' ) )
__snake_case : List[str] = {int(A ): v for k, v in idalabel.items()}
__snake_case : int = idalabel
__snake_case : List[Any] = {v: k for k, v in idalabel.items()}
__snake_case : Tuple = [1, 1_50, 4_80, 4_80]
return config, expected_shape
def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> Dict:
__snake_case : Union[str, Any] = ['pretrained.model.head.weight', 'pretrained.model.head.bias']
for k in ignore_keys:
state_dict.pop(A , A )
def _SCREAMING_SNAKE_CASE ( A : List[Any] ) -> Any:
if (
"pretrained.model" in name
and "cls_token" not in name
and "pos_embed" not in name
and "patch_embed" not in name
):
__snake_case : Union[str, Any] = name.replace('pretrained.model' , 'dpt.encoder' )
if "pretrained.model" in name:
__snake_case : str = name.replace('pretrained.model' , 'dpt.embeddings' )
if "patch_embed" in name:
__snake_case : Union[str, Any] = name.replace('patch_embed' , '' )
if "pos_embed" in name:
__snake_case : Union[str, Any] = name.replace('pos_embed' , 'position_embeddings' )
if "attn.proj" in name:
__snake_case : Union[str, Any] = name.replace('attn.proj' , 'attention.output.dense' )
if "proj" in name and "project" not in name:
__snake_case : Optional[Any] = name.replace('proj' , 'projection' )
if "blocks" in name:
__snake_case : Optional[int] = name.replace('blocks' , 'layer' )
if "mlp.fc1" in name:
__snake_case : int = name.replace('mlp.fc1' , 'intermediate.dense' )
if "mlp.fc2" in name:
__snake_case : Any = name.replace('mlp.fc2' , 'output.dense' )
if "norm1" in name and "backbone" not in name:
__snake_case : Tuple = name.replace('norm1' , 'layernorm_before' )
if "norm2" in name and "backbone" not in name:
__snake_case : Union[str, Any] = name.replace('norm2' , 'layernorm_after' )
if "scratch.output_conv" in name:
__snake_case : List[str] = name.replace('scratch.output_conv' , 'head' )
if "scratch" in name:
__snake_case : Any = name.replace('scratch' , 'neck' )
if "layer1_rn" in name:
__snake_case : List[Any] = name.replace('layer1_rn' , 'convs.0' )
if "layer2_rn" in name:
__snake_case : Optional[Any] = name.replace('layer2_rn' , 'convs.1' )
if "layer3_rn" in name:
__snake_case : List[str] = name.replace('layer3_rn' , 'convs.2' )
if "layer4_rn" in name:
__snake_case : Dict = name.replace('layer4_rn' , 'convs.3' )
if "refinenet" in name:
__snake_case : List[str] = int(name[len('neck.refinenet' ) : len('neck.refinenet' ) + 1] )
# tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3
__snake_case : Optional[Any] = name.replace(F"""refinenet{layer_idx}""" , F"""fusion_stage.layers.{abs(layer_idx-4 )}""" )
if "out_conv" in name:
__snake_case : Dict = name.replace('out_conv' , 'projection' )
if "resConfUnit1" in name:
__snake_case : str = name.replace('resConfUnit1' , 'residual_layer1' )
if "resConfUnit2" in name:
__snake_case : Union[str, Any] = name.replace('resConfUnit2' , 'residual_layer2' )
if "conv1" in name:
__snake_case : Optional[Any] = name.replace('conv1' , 'convolution1' )
if "conv2" in name:
__snake_case : Tuple = name.replace('conv2' , 'convolution2' )
# readout blocks
if "pretrained.act_postprocess1.0.project.0" in name:
__snake_case : str = name.replace('pretrained.act_postprocess1.0.project.0' , 'neck.reassemble_stage.readout_projects.0.0' )
if "pretrained.act_postprocess2.0.project.0" in name:
__snake_case : Dict = name.replace('pretrained.act_postprocess2.0.project.0' , 'neck.reassemble_stage.readout_projects.1.0' )
if "pretrained.act_postprocess3.0.project.0" in name:
__snake_case : Tuple = name.replace('pretrained.act_postprocess3.0.project.0' , 'neck.reassemble_stage.readout_projects.2.0' )
if "pretrained.act_postprocess4.0.project.0" in name:
__snake_case : Optional[int] = name.replace('pretrained.act_postprocess4.0.project.0' , 'neck.reassemble_stage.readout_projects.3.0' )
# resize blocks
if "pretrained.act_postprocess1.3" in name:
__snake_case : Any = name.replace('pretrained.act_postprocess1.3' , 'neck.reassemble_stage.layers.0.projection' )
if "pretrained.act_postprocess1.4" in name:
__snake_case : Optional[int] = name.replace('pretrained.act_postprocess1.4' , 'neck.reassemble_stage.layers.0.resize' )
if "pretrained.act_postprocess2.3" in name:
__snake_case : str = name.replace('pretrained.act_postprocess2.3' , 'neck.reassemble_stage.layers.1.projection' )
if "pretrained.act_postprocess2.4" in name:
__snake_case : str = name.replace('pretrained.act_postprocess2.4' , 'neck.reassemble_stage.layers.1.resize' )
if "pretrained.act_postprocess3.3" in name:
__snake_case : Tuple = name.replace('pretrained.act_postprocess3.3' , 'neck.reassemble_stage.layers.2.projection' )
if "pretrained.act_postprocess4.3" in name:
__snake_case : str = name.replace('pretrained.act_postprocess4.3' , 'neck.reassemble_stage.layers.3.projection' )
if "pretrained.act_postprocess4.4" in name:
__snake_case : Optional[int] = name.replace('pretrained.act_postprocess4.4' , 'neck.reassemble_stage.layers.3.resize' )
if "pretrained" in name:
__snake_case : List[str] = name.replace('pretrained' , 'dpt' )
if "bn" in name:
__snake_case : List[str] = name.replace('bn' , 'batch_norm' )
if "head" in name:
__snake_case : Optional[Any] = name.replace('head' , 'head.head' )
if "encoder.norm" in name:
__snake_case : Optional[int] = name.replace('encoder.norm' , 'layernorm' )
if "auxlayer" in name:
__snake_case : List[Any] = name.replace('auxlayer' , 'auxiliary_head.head' )
if "backbone" in name:
__snake_case : List[str] = name.replace('backbone' , 'backbone.bit.encoder' )
if ".." in name:
__snake_case : List[str] = name.replace('..' , '.' )
if "stem.conv" in name:
__snake_case : Any = name.replace('stem.conv' , 'bit.embedder.convolution' )
if "blocks" in name:
__snake_case : List[str] = name.replace('blocks' , 'layers' )
if "convolution" in name and "backbone" in name:
__snake_case : int = name.replace('convolution' , 'conv' )
if "layer" in name and "backbone" in name:
__snake_case : Optional[int] = name.replace('layer' , 'layers' )
if "backbone.bit.encoder.bit" in name:
__snake_case : Union[str, Any] = name.replace('backbone.bit.encoder.bit' , 'backbone.bit' )
if "embedder.conv" in name:
__snake_case : int = name.replace('embedder.conv' , 'embedder.convolution' )
if "backbone.bit.encoder.stem.norm" in name:
__snake_case : str = name.replace('backbone.bit.encoder.stem.norm' , 'backbone.bit.embedder.norm' )
return name
def _SCREAMING_SNAKE_CASE ( A : Dict , A : Tuple ) -> Union[str, Any]:
for i in range(config.num_hidden_layers ):
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
__snake_case : Any = state_dict.pop(F"""dpt.encoder.layer.{i}.attn.qkv.weight""" )
__snake_case : Optional[int] = state_dict.pop(F"""dpt.encoder.layer.{i}.attn.qkv.bias""" )
# next, add query, keys and values (in that order) to the state dict
__snake_case : Any = in_proj_weight[: config.hidden_size, :]
__snake_case : Dict = in_proj_bias[: config.hidden_size]
__snake_case : Union[str, Any] = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
__snake_case : List[str] = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
__snake_case : Tuple = in_proj_weight[
-config.hidden_size :, :
]
__snake_case : str = in_proj_bias[-config.hidden_size :]
def _SCREAMING_SNAKE_CASE ( ) -> List[Any]:
__snake_case : Tuple = 'http://images.cocodataset.org/val2017/000000039769.jpg'
__snake_case : Tuple = Image.open(requests.get(A , stream=A ).raw )
return im
@torch.no_grad()
def _SCREAMING_SNAKE_CASE ( A : List[str] , A : str , A : int , A : List[Any] , A : List[Any] ) -> List[str]:
__snake_case : int = get_dpt_config(A )
# load original state_dict from URL
# state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")
__snake_case : Any = torch.load(A , map_location='cpu' )
# remove certain keys
remove_ignore_keys_(A )
# rename keys
for key in state_dict.copy().keys():
__snake_case : int = state_dict.pop(A )
__snake_case : List[Any] = val
# read in qkv matrices
read_in_q_k_v(A , A )
# load HuggingFace model
__snake_case : Optional[Any] = DPTForSemanticSegmentation(A ) if 'ade' in checkpoint_url else DPTForDepthEstimation(A )
model.load_state_dict(A )
model.eval()
# Check outputs on an image
__snake_case : str = 4_80 if 'ade' in checkpoint_url else 3_84
__snake_case : Dict = DPTImageProcessor(size=A )
__snake_case : int = prepare_img()
__snake_case : Optional[int] = image_processor(A , return_tensors='pt' )
# forward pass
__snake_case : List[Any] = model(**A ).logits if 'ade' in checkpoint_url else model(**A ).predicted_depth
if show_prediction:
__snake_case : str = (
torch.nn.functional.interpolate(
outputs.unsqueeze(1 ) , size=(image.size[1], image.size[0]) , mode='bicubic' , align_corners=A , )
.squeeze()
.cpu()
.numpy()
)
Image.fromarray((prediction / prediction.max()) * 2_55 ).show()
if pytorch_dump_folder_path is not None:
Path(A ).mkdir(exist_ok=A )
print(F"""Saving model to {pytorch_dump_folder_path}""" )
model.save_pretrained(A )
print(F"""Saving image processor to {pytorch_dump_folder_path}""" )
image_processor.save_pretrained(A )
if push_to_hub:
model.push_to_hub('ybelkada/dpt-hybrid-midas' )
image_processor.push_to_hub('ybelkada/dpt-hybrid-midas' )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--checkpoint_url''',
default='''https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt''',
type=str,
help='''URL of the original DPT checkpoint you\'d like to convert.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''',
default=None,
type=str,
required=False,
help='''Path to the output PyTorch model directory.''',
)
parser.add_argument(
'''--push_to_hub''',
action='''store_true''',
)
parser.add_argument(
'''--model_name''',
default='''dpt-large''',
type=str,
help='''Name of the model, in case you\'re pushing to the hub.''',
)
parser.add_argument(
'''--show_prediction''',
action='''store_true''',
)
__A = parser.parse_args()
convert_dpt_checkpoint(
args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name, args.show_prediction
) | 714 |
'''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 _SCREAMING_SNAKE_CASE ( A : int , A : str , A : LevitConfig , A : Path , A : bool = True ) -> Dict:
"""simple docstring"""
print(F"""Converting {name}...""" )
with torch.no_grad():
if hidden_sizes == 1_28:
if name[-1] == "S":
__snake_case : Optional[int] = timm.create_model('levit_128s' , pretrained=A )
else:
__snake_case : Tuple = timm.create_model('levit_128' , pretrained=A )
if hidden_sizes == 1_92:
__snake_case : int = timm.create_model('levit_192' , pretrained=A )
if hidden_sizes == 2_56:
__snake_case : List[Any] = timm.create_model('levit_256' , pretrained=A )
if hidden_sizes == 3_84:
__snake_case : int = timm.create_model('levit_384' , pretrained=A )
from_model.eval()
__snake_case : str = LevitForImageClassificationWithTeacher(A ).eval()
__snake_case : int = OrderedDict()
__snake_case : Optional[Any] = from_model.state_dict()
__snake_case : Tuple = list(from_model.state_dict().keys() )
__snake_case : List[str] = list(our_model.state_dict().keys() )
print(len(A ) , len(A ) )
for i in range(len(A ) ):
__snake_case : Optional[int] = weights[og_keys[i]]
our_model.load_state_dict(A )
__snake_case : Tuple = torch.randn((2, 3, 2_24, 2_24) )
__snake_case : Union[str, Any] = from_model(A )
__snake_case : List[str] = our_model(A ).logits
assert torch.allclose(A , A ), "The model logits don't match the original one."
__snake_case : int = name
print(A )
if push_to_hub:
our_model.save_pretrained(save_directory / checkpoint_name )
__snake_case : int = LevitImageProcessor()
image_processor.save_pretrained(save_directory / checkpoint_name )
print(F"""Pushed {checkpoint_name}""" )
def _SCREAMING_SNAKE_CASE ( A : Path , A : str = None , A : bool = True ) -> List[Any]:
"""simple docstring"""
__snake_case : Optional[Any] = 'imagenet-1k-id2label.json'
__snake_case : Tuple = 10_00
__snake_case : Dict = (1, num_labels)
__snake_case : List[str] = 'huggingface/label-files'
__snake_case : Any = num_labels
__snake_case : str = json.load(open(hf_hub_download(A , A , repo_type='dataset' ) , 'r' ) )
__snake_case : Any = {int(A ): v for k, v in idalabel.items()}
__snake_case : int = idalabel
__snake_case : Union[str, Any] = {v: k for k, v in idalabel.items()}
__snake_case : Optional[int] = partial(A , num_labels=A , idalabel=A , labelaid=A )
__snake_case : Dict = {
'levit-128S': 1_28,
'levit-128': 1_28,
'levit-192': 1_92,
'levit-256': 2_56,
'levit-384': 3_84,
}
__snake_case : Union[str, Any] = {
'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) | 61 | 0 |
'''simple docstring'''
from __future__ import annotations
from typing import Dict
from ...configuration_utils import PretrainedConfig
__A = {
'''susnato/ernie-m-base_pytorch''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json''',
'''susnato/ernie-m-large_pytorch''': '''https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json''',
}
class a_ ( UpperCamelCase_ ):
_snake_case = """ernie_m"""
_snake_case = {"""dropout""": """classifier_dropout""", """num_classes""": """num_labels"""}
def __init__(self , __a = 2_5_0_0_0_2 , __a = 7_6_8 , __a = 1_2 , __a = 1_2 , __a = 3_0_7_2 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 5_1_4 , __a = 0.02 , __a = 1 , __a = 1E-05 , __a=None , __a=False , __a=0.0 , **__a , ) -> List[str]:
"""simple docstring"""
super().__init__(pad_token_id=__a , **__a)
__snake_case : Optional[Any] = vocab_size
__snake_case : List[Any] = hidden_size
__snake_case : Any = num_hidden_layers
__snake_case : List[str] = num_attention_heads
__snake_case : Union[str, Any] = intermediate_size
__snake_case : str = hidden_act
__snake_case : str = hidden_dropout_prob
__snake_case : Optional[int] = attention_probs_dropout_prob
__snake_case : Optional[Any] = max_position_embeddings
__snake_case : Tuple = initializer_range
__snake_case : Tuple = layer_norm_eps
__snake_case : List[Any] = classifier_dropout
__snake_case : Union[str, Any] = is_decoder
__snake_case : Optional[Any] = act_dropout | 715 |
'''simple docstring'''
import inspect
import unittest
from typing import List
import numpy as np
from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFEfficientFormerForImageClassification,
TFEfficientFormerForImageClassificationWithTeacher,
TFEfficientFormerModel,
)
from transformers.models.efficientformer.modeling_tf_efficientformer import (
TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_vision_available():
from PIL import Image
from transformers import EfficientFormerImageProcessor
class a_ :
def __init__(self , __a , __a = 1_3 , __a = 6_4 , __a = 2 , __a = 3 , __a = 3 , __a = True , __a = True , __a = 1_2_8 , __a=[1_6, 3_2, 6_4, 1_2_8] , __a = 7 , __a = 4 , __a = 3_7 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 1_0 , __a = 0.02 , __a = 2 , __a = 1 , __a = 1_2_8 , __a = [2, 2, 2, 2] , __a = 2 , __a = 2 , ) -> str:
"""simple docstring"""
__snake_case : Optional[Any] = parent
__snake_case : Optional[int] = batch_size
__snake_case : Optional[Any] = image_size
__snake_case : Optional[int] = patch_size
__snake_case : Optional[Any] = num_channels
__snake_case : Optional[Any] = is_training
__snake_case : Tuple = use_labels
__snake_case : Optional[int] = hidden_size
__snake_case : Any = num_hidden_layers
__snake_case : List[str] = num_attention_heads
__snake_case : Tuple = intermediate_size
__snake_case : List[str] = hidden_act
__snake_case : Dict = hidden_dropout_prob
__snake_case : Any = attention_probs_dropout_prob
__snake_case : Dict = type_sequence_label_size
__snake_case : str = initializer_range
__snake_case : int = encoder_stride
__snake_case : List[str] = num_attention_outputs
__snake_case : Optional[Any] = embed_dim
__snake_case : Optional[Any] = embed_dim + 1
__snake_case : List[str] = resolution
__snake_case : Optional[int] = depths
__snake_case : List[Any] = hidden_sizes
__snake_case : List[str] = dim
__snake_case : Union[str, Any] = mlp_expansion_ratio
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
__snake_case : List[str] = None
if self.use_labels:
__snake_case : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size)
__snake_case : Tuple = self.get_config()
return config, pixel_values, labels
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return EfficientFormerConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , )
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Optional[int]:
"""simple docstring"""
__snake_case : Union[str, Any] = TFEfficientFormerModel(config=__a)
__snake_case : int = model(__a , training=__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple:
"""simple docstring"""
__snake_case : Dict = self.type_sequence_label_size
__snake_case : List[Any] = TFEfficientFormerForImageClassification(__a)
__snake_case : Optional[int] = model(__a , labels=__a , training=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size))
# test greyscale images
__snake_case : List[Any] = 1
__snake_case : List[Any] = TFEfficientFormerForImageClassification(__a)
__snake_case : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
__snake_case : str = model(__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size))
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : Union[str, Any] = self.prepare_config_and_inputs()
__snake_case ,__snake_case ,__snake_case : Union[str, Any] = config_and_inputs
__snake_case : Optional[int] = {'pixel_values': pixel_values}
return config, inputs_dict
@require_tf
class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ):
_snake_case = (
(
TFEfficientFormerModel,
TFEfficientFormerForImageClassificationWithTeacher,
TFEfficientFormerForImageClassification,
)
if is_tf_available()
else ()
)
_snake_case = (
{
"""feature-extraction""": TFEfficientFormerModel,
"""image-classification""": (
TFEfficientFormerForImageClassification,
TFEfficientFormerForImageClassificationWithTeacher,
),
}
if is_tf_available()
else {}
)
_snake_case = False
_snake_case = False
_snake_case = False
_snake_case = False
_snake_case = False
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Dict = TFEfficientFormerModelTester(self)
__snake_case : List[Any] = ConfigTester(
self , config_class=__a , has_text_modality=__a , hidden_size=3_7)
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
self.config_tester.run_common_tests()
@unittest.skip(reason='EfficientFormer does not use inputs_embeds')
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
pass
@unittest.skip(reason='EfficientFormer does not support input and output embeddings')
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case ,__snake_case : str = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case : Optional[int] = model_class(__a)
__snake_case : Union[str, Any] = inspect.signature(model.call)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__snake_case : Optional[int] = [*signature.parameters.keys()]
__snake_case : Dict = ['pixel_values']
self.assertListEqual(arg_names[:1] , __a)
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
def check_hidden_states_output(__a , __a , __a):
__snake_case : str = model_class(__a)
__snake_case : List[Any] = model(**self._prepare_for_class(__a , __a) , training=__a)
__snake_case : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
__snake_case : Optional[Any] = getattr(
self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1)
self.assertEqual(len(__a) , __a)
if hasattr(self.model_tester , 'encoder_seq_length'):
__snake_case : List[Any] = self.model_tester.encoder_seq_length
if hasattr(self.model_tester , 'chunk_length') and self.model_tester.chunk_length > 1:
__snake_case : str = seq_length * self.model_tester.chunk_length
else:
__snake_case : Optional[int] = self.model_tester.seq_length
self.assertListEqual(
list(hidden_states[-1].shape[-2:]) , [seq_length, self.model_tester.hidden_size] , )
if config.is_encoder_decoder:
__snake_case : List[Any] = outputs.decoder_hidden_states
self.asseretIsInstance(__a , (list, tuple))
self.assertEqual(len(__a) , __a)
__snake_case : List[str] = getattr(self.model_tester , 'seq_length' , __a)
__snake_case : Tuple = getattr(self.model_tester , 'decoder_seq_length' , __a)
self.assertListEqual(
list(hidden_states[-1].shape[-2:]) , [decoder_seq_length, self.model_tester.hidden_size] , )
__snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case : List[str] = True
check_hidden_states_output(__a , __a , __a)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__snake_case : str = True
check_hidden_states_output(__a , __a , __a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a=False) -> int:
"""simple docstring"""
__snake_case : Optional[int] = super()._prepare_for_class(__a , __a , return_labels=__a)
if return_labels:
if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
del inputs_dict["labels"]
return inputs_dict
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
@unittest.skip(reason='EfficientFormer does not implement masked image modeling yet')
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*__a)
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*__a)
@slow
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__snake_case : Any = TFEfficientFormerModel.from_pretrained(__a)
self.assertIsNotNone(__a)
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case ,__snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case : Tuple = True
__snake_case : Optional[Any] = getattr(self.model_tester , 'seq_length' , __a)
__snake_case : List[Any] = getattr(self.model_tester , 'encoder_seq_length' , __a)
__snake_case : Tuple = getattr(self.model_tester , 'key_length' , __a)
__snake_case : Optional[Any] = getattr(self.model_tester , 'chunk_length' , __a)
if chunk_length is not None and hasattr(self.model_tester , 'num_hashes'):
__snake_case : str = encoder_seq_length * self.model_tester.num_hashes
for model_class in self.all_model_classes:
__snake_case : Optional[Any] = True
__snake_case : Dict = False
__snake_case : Optional[int] = True
__snake_case : Dict = model_class(__a)
__snake_case : Tuple = model(**self._prepare_for_class(__a , __a) , training=__a)
__snake_case : Union[str, Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(__a) , self.model_tester.num_attention_outputs)
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
__snake_case : Dict = True
__snake_case : str = model_class(__a)
__snake_case : str = model(**self._prepare_for_class(__a , __a) , training=__a)
__snake_case : Tuple = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(__a) , self.model_tester.num_attention_outputs)
if chunk_length is not None:
self.assertListEqual(
list(attentions[0].shape[-4:]) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , )
else:
self.assertListEqual(
list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , )
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case ,__snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
# Prepare our model
__snake_case : Tuple = model_class(__a)
# These are maximally general inputs for the model, with multiple None dimensions
# Hopefully this will catch any conditionals that fail for flexible shapes
__snake_case : Optional[Any] = {
key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=__a)
for key, val in model.input_signature.items()
if key in model.dummy_inputs
}
__snake_case : Tuple = model(__a)
self.assertTrue(outputs_dict is not None)
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
__snake_case : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_tf
@require_vision
class a_ ( unittest.TestCase ):
@cached_property
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return (
EfficientFormerImageProcessor.from_pretrained('snap-research/efficientformer-l1-300')
if is_vision_available()
else None
)
@slow
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
__snake_case : List[str] = TFEfficientFormerForImageClassification.from_pretrained('snap-research/efficientformer-l1-300')
__snake_case : Optional[int] = self.default_image_processor
__snake_case : List[Any] = prepare_img()
__snake_case : List[Any] = image_processor(images=__a , return_tensors='tf')
# forward pass
__snake_case : List[str] = model(**__a , training=__a)
# verify the logits
__snake_case : str = tf.TensorShape((1, 1_0_0_0))
self.assertEqual(outputs.logits.shape , __a)
__snake_case : Any = tf.constant([-0.0_555, 0.4_825, -0.0_852])
self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4))
@slow
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[Any] = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
'snap-research/efficientformer-l1-300')
__snake_case : List[Any] = self.default_image_processor
__snake_case : Union[str, Any] = prepare_img()
__snake_case : List[Any] = image_processor(images=__a , return_tensors='tf')
# forward pass
__snake_case : Optional[int] = model(**__a , training=__a)
# verify the logits
__snake_case : Optional[int] = tf.TensorShape((1, 1_0_0_0))
self.assertEqual(outputs.logits.shape , __a)
__snake_case : List[str] = tf.constant([-0.1_312, 0.4_353, -1.0_499])
self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4)) | 61 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__A = {
'''configuration_maskformer''': ['''MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MaskFormerConfig'''],
'''configuration_maskformer_swin''': ['''MaskFormerSwinConfig'''],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ['''MaskFormerFeatureExtractor''']
__A = ['''MaskFormerImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'''MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''MaskFormerForInstanceSegmentation''',
'''MaskFormerModel''',
'''MaskFormerPreTrainedModel''',
]
__A = [
'''MaskFormerSwinBackbone''',
'''MaskFormerSwinModel''',
'''MaskFormerSwinPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig
from .configuration_maskformer_swin import MaskFormerSwinConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_maskformer import MaskFormerFeatureExtractor
from .image_processing_maskformer import MaskFormerImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_maskformer import (
MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
MaskFormerForInstanceSegmentation,
MaskFormerModel,
MaskFormerPreTrainedModel,
)
from .modeling_maskformer_swin import (
MaskFormerSwinBackbone,
MaskFormerSwinModel,
MaskFormerSwinPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure) | 716 |
'''simple docstring'''
__A = {str(digit): digit**5 for digit in range(1_0)}
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
return sum(DIGITS_FIFTH_POWER[digit] for digit in str(A ) )
def _SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
return sum(
number
for number in range(10_00 , 1_00_00_00 )
if number == digits_fifth_powers_sum(A ) )
if __name__ == "__main__":
print(solution()) | 61 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__A = {'''configuration_glpn''': ['''GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GLPNConfig''']}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ['''GLPNFeatureExtractor''']
__A = ['''GLPNImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'''GLPN_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''GLPNForDepthEstimation''',
'''GLPNLayer''',
'''GLPNModel''',
'''GLPNPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_glpn import GLPNFeatureExtractor
from .image_processing_glpn import GLPNImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_glpn import (
GLPN_PRETRAINED_MODEL_ARCHIVE_LIST,
GLPNForDepthEstimation,
GLPNLayer,
GLPNModel,
GLPNPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 717 |
'''simple docstring'''
from __future__ import annotations
from collections import deque
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any
@dataclass
class a_ :
_snake_case = 42
_snake_case = None
_snake_case = None
def _SCREAMING_SNAKE_CASE ( ) -> Node | None:
"""simple docstring"""
__snake_case : str = Node(1 )
__snake_case : Tuple = Node(2 )
__snake_case : Optional[int] = Node(3 )
__snake_case : List[str] = Node(4 )
__snake_case : List[str] = Node(5 )
return tree
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return [root.data, *preorder(root.left ), *preorder(root.right )] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return postorder(root.left ) + postorder(root.right ) + [root.data] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> list[int]:
"""simple docstring"""
return [*inorder(root.left ), root.data, *inorder(root.right )] if root else []
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> int:
"""simple docstring"""
return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
if root is None:
return output
__snake_case : Optional[int] = deque([root] )
while process_queue:
__snake_case : List[str] = process_queue.popleft()
output.append(node.data )
if node.left:
process_queue.append(node.left )
if node.right:
process_queue.append(node.right )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
def populate_output(A : Node | None , A : int ) -> None:
if not root:
return
if level == 1:
output.append(root.data )
elif level > 1:
populate_output(root.left , level - 1 )
populate_output(root.right , level - 1 )
populate_output(A , A )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None , A : int ) -> Sequence[Node | None]:
"""simple docstring"""
__snake_case : list[Any] = []
def populate_output(A : Node | None , A : int ) -> None:
if root is None:
return
if level == 1:
output.append(root.data )
elif level > 1:
populate_output(root.right , level - 1 )
populate_output(root.left , level - 1 )
populate_output(A , A )
return output
def _SCREAMING_SNAKE_CASE ( A : Node | None ) -> Sequence[Node | None] | list[Any]:
"""simple docstring"""
if root is None:
return []
__snake_case : list[Sequence[Node | None]] = []
__snake_case : List[Any] = 0
__snake_case : int = height(A )
for h in range(1 , height_tree + 1 ):
if not flag:
output.append(get_nodes_from_left_to_right(A , A ) )
__snake_case : int = 1
else:
output.append(get_nodes_from_right_to_left(A , A ) )
__snake_case : Tuple = 0
return output
def _SCREAMING_SNAKE_CASE ( ) -> None: # Main function for testing.
"""simple docstring"""
__snake_case : Optional[int] = make_tree()
print(F"""In-order Traversal: {inorder(A )}""" )
print(F"""Pre-order Traversal: {preorder(A )}""" )
print(F"""Post-order Traversal: {postorder(A )}""" , '\n' )
print(F"""Height of Tree: {height(A )}""" , '\n' )
print('Complete Level Order Traversal: ' )
print(level_order(A ) , '\n' )
print('Level-wise order Traversal: ' )
for level in range(1 , height(A ) + 1 ):
print(F"""Level {level}:""" , get_nodes_from_left_to_right(A , level=A ) )
print('\nZigZag order Traversal: ' )
print(zigzag(A ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main() | 61 | 0 |
'''simple docstring'''
import warnings
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class a_ ( UpperCamelCase_ ):
_snake_case = ["""image_processor""", """tokenizer"""]
_snake_case = """LayoutLMv2ImageProcessor"""
_snake_case = ("""LayoutXLMTokenizer""", """LayoutXLMTokenizerFast""")
def __init__(self , __a=None , __a=None , **__a) -> Tuple:
"""simple docstring"""
if "feature_extractor" in kwargs:
warnings.warn(
'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
' instead.' , __a , )
__snake_case : List[str] = kwargs.pop('feature_extractor')
__snake_case : Tuple = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('You need to specify an `image_processor`.')
if tokenizer is None:
raise ValueError('You need to specify a `tokenizer`.')
super().__init__(__a , __a)
def __call__(self , __a , __a = None , __a = None , __a = None , __a = None , __a = True , __a = False , __a = None , __a = None , __a = 0 , __a = None , __a = None , __a = None , __a = False , __a = False , __a = False , __a = False , __a = True , __a = None , **__a , ) -> BatchEncoding:
"""simple docstring"""
if self.image_processor.apply_ocr and (boxes is not None):
raise ValueError(
'You cannot provide bounding boxes '
'if you initialized the image processor with apply_ocr set to True.')
if self.image_processor.apply_ocr and (word_labels is not None):
raise ValueError(
'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.')
if return_overflowing_tokens is True and return_offsets_mapping is False:
raise ValueError('You cannot return overflowing tokens without returning the offsets mapping.')
# first, apply the image processor
__snake_case : str = self.image_processor(images=__a , return_tensors=__a)
# second, apply the tokenizer
if text is not None and self.image_processor.apply_ocr and text_pair is None:
if isinstance(__a , __a):
__snake_case : Optional[int] = [text] # add batch dimension (as the image processor always adds a batch dimension)
__snake_case : str = features['words']
__snake_case : Union[str, Any] = self.tokenizer(
text=text if text is not None else features['words'] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['boxes'] , word_labels=__a , add_special_tokens=__a , padding=__a , truncation=__a , max_length=__a , stride=__a , pad_to_multiple_of=__a , return_token_type_ids=__a , return_attention_mask=__a , return_overflowing_tokens=__a , return_special_tokens_mask=__a , return_offsets_mapping=__a , return_length=__a , verbose=__a , return_tensors=__a , **__a , )
# add pixel values
__snake_case : Any = features.pop('pixel_values')
if return_overflowing_tokens is True:
__snake_case : str = self.get_overflowing_images(__a , encoded_inputs['overflow_to_sample_mapping'])
__snake_case : str = images
return encoded_inputs
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> str:
"""simple docstring"""
__snake_case : Union[str, Any] = []
for sample_idx in overflow_to_sample_mapping:
images_with_overflow.append(images[sample_idx])
if len(__a) != len(__a):
raise ValueError(
'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'
F""" {len(__a)} and {len(__a)}""")
return images_with_overflow
def SCREAMING_SNAKE_CASE__ (self , *__a , **__a) -> List[str]:
"""simple docstring"""
return self.tokenizer.batch_decode(*__a , **__a)
def SCREAMING_SNAKE_CASE__ (self , *__a , **__a) -> Any:
"""simple docstring"""
return self.tokenizer.decode(*__a , **__a)
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return ["input_ids", "bbox", "attention_mask", "image"]
@property
def SCREAMING_SNAKE_CASE__ (self) -> str:
"""simple docstring"""
warnings.warn(
'`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , __a , )
return self.image_processor_class
@property
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
warnings.warn(
'`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , __a , )
return self.image_processor | 718 |
'''simple docstring'''
from __future__ import annotations
import math
import random
from collections.abc import Collection
from typing import overload
class a_ :
def __init__(self , __a = None) -> None:
"""simple docstring"""
if components is None:
__snake_case : List[str] = []
__snake_case : Optional[int] = list(__a)
def __len__(self) -> int:
"""simple docstring"""
return len(self.__components)
def __str__(self) -> str:
"""simple docstring"""
return "(" + ",".join(map(__a , self.__components)) + ")"
def __add__(self , __a) -> Vector:
"""simple docstring"""
__snake_case : Optional[Any] = len(self)
if size == len(__a):
__snake_case : Optional[int] = [self.__components[i] + other.component(__a) for i in range(__a)]
return Vector(__a)
else:
raise Exception('must have the same size')
def __sub__(self , __a) -> Vector:
"""simple docstring"""
__snake_case : Optional[Any] = len(self)
if size == len(__a):
__snake_case : Optional[int] = [self.__components[i] - other.component(__a) for i in range(__a)]
return Vector(__a)
else: # error case
raise Exception('must have the same size')
@overload
def __mul__(self , __a) -> Vector:
"""simple docstring"""
...
@overload
def __mul__(self , __a) -> float:
"""simple docstring"""
...
def __mul__(self , __a) -> float | Vector:
"""simple docstring"""
if isinstance(__a , (float, int)):
__snake_case : str = [c * other for c in self.__components]
return Vector(__a)
elif isinstance(__a , __a) and len(self) == len(__a):
__snake_case : List[Any] = len(self)
__snake_case : Dict = [self.__components[i] * other.component(__a) for i in range(__a)]
return sum(__a)
else: # error case
raise Exception('invalid operand!')
def SCREAMING_SNAKE_CASE__ (self) -> Vector:
"""simple docstring"""
return Vector(self.__components)
def SCREAMING_SNAKE_CASE__ (self , __a) -> float:
"""simple docstring"""
if isinstance(__a , __a) and -len(self.__components) <= i < len(self.__components):
return self.__components[i]
else:
raise Exception('index out of range')
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> None:
"""simple docstring"""
assert -len(self.__components) <= pos < len(self.__components)
__snake_case : int = value
def SCREAMING_SNAKE_CASE__ (self) -> float:
"""simple docstring"""
if len(self.__components) == 0:
raise Exception('Vector is empty')
__snake_case : Tuple = [c**2 for c in self.__components]
return math.sqrt(sum(__a))
def SCREAMING_SNAKE_CASE__ (self , __a , __a = False) -> float:
"""simple docstring"""
__snake_case : Tuple = self * other
__snake_case : Optional[int] = self.euclidean_length() * other.euclidean_length()
if deg:
return math.degrees(math.acos(num / den))
else:
return math.acos(num / den)
def _SCREAMING_SNAKE_CASE ( A : int ) -> Vector:
"""simple docstring"""
assert isinstance(A , A )
return Vector([0] * dimension )
def _SCREAMING_SNAKE_CASE ( A : int , A : int ) -> Vector:
"""simple docstring"""
assert isinstance(A , A ) and (isinstance(A , A ))
__snake_case : Any = [0] * dimension
__snake_case : int = 1
return Vector(A )
def _SCREAMING_SNAKE_CASE ( A : float , A : Vector , A : Vector ) -> Vector:
"""simple docstring"""
assert (
isinstance(A , A )
and isinstance(A , A )
and (isinstance(A , (int, float) ))
)
return x * scalar + y
def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int ) -> Vector:
"""simple docstring"""
random.seed(A )
__snake_case : List[Any] = [random.randint(A , A ) for _ in range(A )]
return Vector(A )
class a_ :
def __init__(self , __a , __a , __a) -> None:
"""simple docstring"""
__snake_case : Union[str, Any] = matrix
__snake_case : int = w
__snake_case : str = h
def __str__(self) -> str:
"""simple docstring"""
__snake_case : Dict = ''
for i in range(self.__height):
ans += "|"
for j in range(self.__width):
if j < self.__width - 1:
ans += str(self.__matrix[i][j]) + ","
else:
ans += str(self.__matrix[i][j]) + "|\n"
return ans
def __add__(self , __a) -> Matrix:
"""simple docstring"""
if self.__width == other.width() and self.__height == other.height():
__snake_case : Tuple = []
for i in range(self.__height):
__snake_case : List[Any] = [
self.__matrix[i][j] + other.component(__a , __a)
for j in range(self.__width)
]
matrix.append(__a)
return Matrix(__a , self.__width , self.__height)
else:
raise Exception('matrix must have the same dimension!')
def __sub__(self , __a) -> Matrix:
"""simple docstring"""
if self.__width == other.width() and self.__height == other.height():
__snake_case : str = []
for i in range(self.__height):
__snake_case : List[str] = [
self.__matrix[i][j] - other.component(__a , __a)
for j in range(self.__width)
]
matrix.append(__a)
return Matrix(__a , self.__width , self.__height)
else:
raise Exception('matrices must have the same dimension!')
@overload
def __mul__(self , __a) -> Matrix:
"""simple docstring"""
...
@overload
def __mul__(self , __a) -> Vector:
"""simple docstring"""
...
def __mul__(self , __a) -> Vector | Matrix:
"""simple docstring"""
if isinstance(__a , __a): # matrix-vector
if len(__a) == self.__width:
__snake_case : Tuple = zero_vector(self.__height)
for i in range(self.__height):
__snake_case : Union[str, Any] = [
self.__matrix[i][j] * other.component(__a)
for j in range(self.__width)
]
ans.change_component(__a , sum(__a))
return ans
else:
raise Exception(
'vector must have the same size as the '
'number of columns of the matrix!')
elif isinstance(__a , (int, float)): # matrix-scalar
__snake_case : str = [
[self.__matrix[i][j] * other for j in range(self.__width)]
for i in range(self.__height)
]
return Matrix(__a , self.__width , self.__height)
return None
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return self.__height
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return self.__width
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float:
"""simple docstring"""
if 0 <= x < self.__height and 0 <= y < self.__width:
return self.__matrix[x][y]
else:
raise Exception('change_component: indices out of bounds')
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> None:
"""simple docstring"""
if 0 <= x < self.__height and 0 <= y < self.__width:
__snake_case : List[Any] = value
else:
raise Exception('change_component: indices out of bounds')
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float:
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square')
__snake_case : List[Any] = self.__matrix[:x] + self.__matrix[x + 1 :]
for i in range(len(__a)):
__snake_case : Tuple = minor[i][:y] + minor[i][y + 1 :]
return Matrix(__a , self.__width - 1 , self.__height - 1).determinant()
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> float:
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square')
if 0 <= x < self.__height and 0 <= y < self.__width:
return (-1) ** (x + y) * self.minor(__a , __a)
else:
raise Exception('Indices out of bounds')
def SCREAMING_SNAKE_CASE__ (self) -> float:
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square')
if self.__height < 1:
raise Exception('Matrix has no element')
elif self.__height == 1:
return self.__matrix[0][0]
elif self.__height == 2:
return (
self.__matrix[0][0] * self.__matrix[1][1]
- self.__matrix[0][1] * self.__matrix[1][0]
)
else:
__snake_case : Any = [
self.__matrix[0][y] * self.cofactor(0 , __a) for y in range(self.__width)
]
return sum(__a)
def _SCREAMING_SNAKE_CASE ( A : int ) -> Matrix:
"""simple docstring"""
__snake_case : list[list[float]] = [[0] * n for _ in range(A )]
return Matrix(A , A , A )
def _SCREAMING_SNAKE_CASE ( A : int , A : int , A : int , A : int ) -> Matrix:
"""simple docstring"""
random.seed(A )
__snake_case : list[list[float]] = [
[random.randint(A , A ) for _ in range(A )] for _ in range(A )
]
return Matrix(A , A , A ) | 61 | 0 |
'''simple docstring'''
import json
import pathlib
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DetaImageProcessor
class a_ ( unittest.TestCase ):
def __init__(self , __a , __a=7 , __a=3 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=[0.5, 0.5, 0.5] , __a=[0.5, 0.5, 0.5] , __a=True , __a=1 / 2_5_5 , __a=True , ) -> Optional[int]:
"""simple docstring"""
__snake_case : Union[str, Any] = size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}
__snake_case : Tuple = parent
__snake_case : Any = batch_size
__snake_case : Union[str, Any] = num_channels
__snake_case : str = min_resolution
__snake_case : Tuple = max_resolution
__snake_case : List[str] = do_resize
__snake_case : int = size
__snake_case : Optional[Any] = do_normalize
__snake_case : Any = image_mean
__snake_case : Any = image_std
__snake_case : Optional[Any] = do_rescale
__snake_case : Optional[Any] = rescale_factor
__snake_case : List[str] = do_pad
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_pad": self.do_pad,
}
def SCREAMING_SNAKE_CASE__ (self , __a , __a=False) -> Any:
"""simple docstring"""
if not batched:
__snake_case : List[str] = image_inputs[0]
if isinstance(__a , Image.Image):
__snake_case : Tuple = image.size
else:
__snake_case : str = image.shape[1], image.shape[2]
if w < h:
__snake_case : List[Any] = int(self.size['shortest_edge'] * h / w)
__snake_case : List[Any] = self.size['shortest_edge']
elif w > h:
__snake_case : Optional[Any] = self.size['shortest_edge']
__snake_case : List[str] = int(self.size['shortest_edge'] * w / h)
else:
__snake_case : Any = self.size['shortest_edge']
__snake_case : str = self.size['shortest_edge']
else:
__snake_case : List[Any] = []
for image in image_inputs:
__snake_case : List[Any] = self.get_expected_values([image])
expected_values.append((expected_height, expected_width))
__snake_case : Optional[Any] = max(__a , key=lambda __a: item[0])[0]
__snake_case : int = max(__a , key=lambda __a: item[1])[1]
return expected_height, expected_width
@require_torch
@require_vision
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = DetaImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Optional[Any] = DetaImageProcessingTester(self)
@property
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : str = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , 'image_mean'))
self.assertTrue(hasattr(__a , 'image_std'))
self.assertTrue(hasattr(__a , 'do_normalize'))
self.assertTrue(hasattr(__a , 'do_resize'))
self.assertTrue(hasattr(__a , 'do_rescale'))
self.assertTrue(hasattr(__a , 'do_pad'))
self.assertTrue(hasattr(__a , 'size'))
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : List[Any] = 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 , __a)
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Optional[int] = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
__snake_case : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
__snake_case : List[str] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
__snake_case : Any = self.image_processor_tester.get_expected_values(__a)
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__snake_case : List[Any] = self.image_processor_tester.get_expected_values(__a , batched=__a)
__snake_case : List[Any] = image_processing(__a , 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 SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
__snake_case : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a)
for image in image_inputs:
self.assertIsInstance(__a , np.ndarray)
# Test not batched input
__snake_case : str = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
__snake_case : List[str] = self.image_processor_tester.get_expected_values(__a)
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__snake_case : Any = image_processing(__a , return_tensors='pt').pixel_values
__snake_case : List[str] = self.image_processor_tester.get_expected_values(__a , batched=__a)
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
__snake_case : str = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
__snake_case : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a)
for image in image_inputs:
self.assertIsInstance(__a , torch.Tensor)
# Test not batched input
__snake_case : List[str] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
__snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(__a)
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__snake_case : Any = image_processing(__a , return_tensors='pt').pixel_values
__snake_case : str = self.image_processor_tester.get_expected_values(__a , batched=__a)
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
@slow
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r') as f:
__snake_case : Optional[int] = json.loads(f.read())
__snake_case : str = {'image_id': 3_9_7_6_9, 'annotations': target}
# encode them
__snake_case : List[Any] = DetaImageProcessor()
__snake_case : Optional[Any] = image_processing(images=__a , annotations=__a , return_tensors='pt')
# verify pixel values
__snake_case : Union[str, Any] = torch.Size([1, 3, 8_0_0, 1_0_6_6])
self.assertEqual(encoding['pixel_values'].shape , __a)
__snake_case : List[str] = torch.tensor([0.2_796, 0.3_138, 0.3_481])
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __a , atol=1E-4))
# verify area
__snake_case : Optional[int] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8])
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __a))
# verify boxes
__snake_case : Any = torch.Size([6, 4])
self.assertEqual(encoding['labels'][0]['boxes'].shape , __a)
__snake_case : str = torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215])
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __a , atol=1E-3))
# verify image_id
__snake_case : List[str] = torch.tensor([3_9_7_6_9])
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __a))
# verify is_crowd
__snake_case : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0])
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __a))
# verify class_labels
__snake_case : Optional[Any] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7])
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __a))
# verify orig_size
__snake_case : Dict = torch.tensor([4_8_0, 6_4_0])
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __a))
# verify size
__snake_case : Dict = torch.tensor([8_0_0, 1_0_6_6])
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __a))
@slow
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r') as f:
__snake_case : List[Any] = json.loads(f.read())
__snake_case : List[str] = {'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target}
__snake_case : int = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic')
# encode them
__snake_case : Union[str, Any] = DetaImageProcessor(format='coco_panoptic')
__snake_case : Dict = image_processing(images=__a , annotations=__a , masks_path=__a , return_tensors='pt')
# verify pixel values
__snake_case : List[Any] = torch.Size([1, 3, 8_0_0, 1_0_6_6])
self.assertEqual(encoding['pixel_values'].shape , __a)
__snake_case : List[str] = torch.tensor([0.2_796, 0.3_138, 0.3_481])
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __a , atol=1E-4))
# verify area
__snake_case : Dict = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7])
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __a))
# verify boxes
__snake_case : Tuple = torch.Size([6, 4])
self.assertEqual(encoding['labels'][0]['boxes'].shape , __a)
__snake_case : Tuple = torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625])
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __a , atol=1E-3))
# verify image_id
__snake_case : Dict = torch.tensor([3_9_7_6_9])
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __a))
# verify is_crowd
__snake_case : Tuple = torch.tensor([0, 0, 0, 0, 0, 0])
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __a))
# verify class_labels
__snake_case : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3])
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __a))
# verify masks
__snake_case : Optional[int] = 8_2_2_8_7_3
self.assertEqual(encoding['labels'][0]['masks'].sum().item() , __a)
# verify orig_size
__snake_case : Optional[int] = torch.tensor([4_8_0, 6_4_0])
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __a))
# verify size
__snake_case : Tuple = torch.tensor([8_0_0, 1_0_6_6])
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __a)) | 719 |
'''simple docstring'''
import contextlib
import importlib
import io
import unittest
import transformers
# Try to import everything from transformers to ensure every object can be loaded.
from transformers import * # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available
if is_torch_available():
from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification
if is_tf_available():
from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification
if is_flax_available():
from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification
__A = DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co
__A = '''main'''
# Default branch name
__A = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
__A = '''aaaaaaa'''
# This commit does not exist, so we should 404.
__A = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
__A = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''
@contextlib.contextmanager
def _SCREAMING_SNAKE_CASE ( ) -> List[Any]:
"""simple docstring"""
print('Welcome!' )
yield
print('Bye!' )
@contextlib.contextmanager
def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]:
"""simple docstring"""
print('Bonjour!' )
yield
print('Au revoir!' )
class a_ ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
assert transformers.__spec__ is not None
assert importlib.util.find_spec('transformers') is not None
class a_ ( unittest.TestCase ):
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> int:
"""simple docstring"""
with ContextManagers([]):
print('Transformers are awesome!')
# The print statement adds a new line at the end of the output
self.assertEqual(mock_stdout.getvalue() , 'Transformers are awesome!\n')
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> List[str]:
"""simple docstring"""
with ContextManagers([context_en()]):
print('Transformers are awesome!')
# The output should be wrapped with an English welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , 'Welcome!\nTransformers are awesome!\nBye!\n')
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO)
def SCREAMING_SNAKE_CASE__ (self , __a) -> Tuple:
"""simple docstring"""
with ContextManagers([context_fr(), context_en()]):
print('Transformers are awesome!')
# The output should be wrapped with an English and French welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , 'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n')
@require_torch
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
self.assertEqual(find_labels(__a) , ['labels'])
self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label'])
self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions'])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , ['labels'])
@require_tf
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
self.assertEqual(find_labels(__a) , ['labels'])
self.assertEqual(find_labels(__a) , ['labels', 'next_sentence_label'])
self.assertEqual(find_labels(__a) , ['start_positions', 'end_positions'])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , ['labels'])
@require_flax
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
self.assertEqual(find_labels(__a) , [])
self.assertEqual(find_labels(__a) , [])
self.assertEqual(find_labels(__a) , [])
class a_ ( UpperCamelCase_ ):
pass
self.assertEqual(find_labels(__a) , []) | 61 | 0 |
'''simple docstring'''
from __future__ import annotations
__A = '''#'''
class a_ :
def __init__(self) -> None:
"""simple docstring"""
__snake_case : dict = {}
def SCREAMING_SNAKE_CASE__ (self , __a) -> None:
"""simple docstring"""
__snake_case : Optional[int] = self._trie
for char in text:
if char not in trie:
__snake_case : str = {}
__snake_case : Tuple = trie[char]
__snake_case : int = True
def SCREAMING_SNAKE_CASE__ (self , __a) -> tuple | list:
"""simple docstring"""
__snake_case : Optional[Any] = self._trie
for char in prefix:
if char in trie:
__snake_case : str = trie[char]
else:
return []
return self._elements(__a)
def SCREAMING_SNAKE_CASE__ (self , __a) -> tuple:
"""simple docstring"""
__snake_case : Union[str, Any] = []
for c, v in d.items():
__snake_case : List[str] = [' '] if c == END else [(c + s) for s in self._elements(__a)]
result.extend(__a)
return tuple(__a)
__A = Trie()
__A = ('''depart''', '''detergent''', '''daring''', '''dog''', '''deer''', '''deal''')
for word in words:
trie.insert_word(word)
def _SCREAMING_SNAKE_CASE ( A : str ) -> tuple:
"""simple docstring"""
__snake_case : int = trie.find_word(A )
return tuple(string + word for word in suffixes )
def _SCREAMING_SNAKE_CASE ( ) -> None:
"""simple docstring"""
print(autocomplete_using_trie('de' ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main() | 720 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__A = {'''configuration_timm_backbone''': ['''TimmBackboneConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ['''TimmBackbone''']
if TYPE_CHECKING:
from .configuration_timm_backbone import TimmBackboneConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_timm_backbone import TimmBackbone
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 61 | 0 |
'''simple docstring'''
class a_ :
def __init__(self , __a) -> None:
"""simple docstring"""
__snake_case : Optional[int] = size
__snake_case : Dict = [0] * size
__snake_case : str = [0] * size
@staticmethod
def SCREAMING_SNAKE_CASE__ (__a) -> int:
"""simple docstring"""
return index | (index + 1)
@staticmethod
def SCREAMING_SNAKE_CASE__ (__a) -> int:
"""simple docstring"""
return (index & (index + 1)) - 1
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> None:
"""simple docstring"""
__snake_case : str = value
while index < self.size:
__snake_case : Any = self.get_prev(__a) + 1
if current_left_border == index:
__snake_case : Any = value
else:
__snake_case : List[Any] = max(__a , __a , __a)
__snake_case : List[str] = self.get_next(__a)
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> int:
"""simple docstring"""
right -= 1 # Because of right is exclusive
__snake_case : int = 0
while left <= right:
__snake_case : Dict = self.get_prev(__a)
if left <= current_left:
__snake_case : List[str] = max(__a , self.tree[right])
__snake_case : Any = current_left
else:
__snake_case : Any = max(__a , self.arr[right])
right -= 1
return result
if __name__ == "__main__":
import doctest
doctest.testmod() | 721 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
__snake_case : str = 1
for i in range(1 , num + 1 ):
fact *= i
return fact
def _SCREAMING_SNAKE_CASE ( A : int ) -> int:
"""simple docstring"""
__snake_case : Union[str, Any] = 0
while number > 0:
__snake_case : Dict = number % 10
sum_of_digits += last_digit
__snake_case : Union[str, Any] = number // 10 # Removing the last_digit from the given number
return sum_of_digits
def _SCREAMING_SNAKE_CASE ( A : int = 1_00 ) -> int:
"""simple docstring"""
__snake_case : List[Any] = factorial(A )
__snake_case : Dict = split_and_add(A )
return result
if __name__ == "__main__":
print(solution(int(input('''Enter the Number: ''').strip()))) | 61 | 0 |
'''simple docstring'''
from math import factorial
def _SCREAMING_SNAKE_CASE ( A : int = 20 ) -> int:
"""simple docstring"""
__snake_case : Union[str, Any] = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1,
# 2, 3,...
__snake_case : Tuple = n // 2
return int(factorial(A ) / (factorial(A ) * factorial(n - k )) )
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
print(solution(2_0))
else:
try:
__A = int(sys.argv[1])
print(solution(n))
except ValueError:
print('''Invalid entry - please enter a number.''') | 700 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import ChineseCLIPImageProcessor
class a_ ( unittest.TestCase ):
def __init__(self , __a , __a=7 , __a=3 , __a=1_8 , __a=3_0 , __a=4_0_0 , __a=True , __a=None , __a=True , __a=None , __a=True , __a=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __a=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __a=True , ) -> List[Any]:
"""simple docstring"""
__snake_case : Tuple = size if size is not None else {'height': 2_2_4, 'width': 2_2_4}
__snake_case : Any = crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8}
__snake_case : Optional[int] = parent
__snake_case : Dict = batch_size
__snake_case : str = num_channels
__snake_case : Optional[Any] = image_size
__snake_case : Optional[int] = min_resolution
__snake_case : Tuple = max_resolution
__snake_case : Optional[int] = do_resize
__snake_case : Optional[int] = size
__snake_case : Union[str, Any] = do_center_crop
__snake_case : List[Any] = crop_size
__snake_case : int = do_normalize
__snake_case : Optional[Any] = image_mean
__snake_case : str = image_std
__snake_case : Optional[Any] = do_convert_rgb
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_convert_rgb": self.do_convert_rgb,
}
def SCREAMING_SNAKE_CASE__ (self , __a=False , __a=False , __a=False) -> List[str]:
"""simple docstring"""
assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"
if equal_resolution:
__snake_case : Optional[int] = []
for i in range(self.batch_size):
image_inputs.append(
np.random.randint(
2_5_5 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta))
else:
__snake_case : Dict = []
for i in range(self.batch_size):
__snake_case ,__snake_case : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution) , 2)
image_inputs.append(np.random.randint(2_5_5 , size=(self.num_channels, width, height) , dtype=np.uinta))
if not numpify and not torchify:
# PIL expects the channel dimension as last dimension
__snake_case : int = [Image.fromarray(np.moveaxis(__a , 0 , -1)) for x in image_inputs]
if torchify:
__snake_case : List[Any] = [torch.from_numpy(__a) for x in image_inputs]
return image_inputs
@require_torch
@require_vision
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = ChineseCLIPImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Union[str, Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=__a)
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : int = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , 'do_resize'))
self.assertTrue(hasattr(__a , 'size'))
self.assertTrue(hasattr(__a , 'do_center_crop'))
self.assertTrue(hasattr(__a , 'center_crop'))
self.assertTrue(hasattr(__a , 'do_normalize'))
self.assertTrue(hasattr(__a , 'image_mean'))
self.assertTrue(hasattr(__a , 'image_std'))
self.assertTrue(hasattr(__a , 'do_convert_rgb'))
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'height': 2_2_4, 'width': 2_2_4})
self.assertEqual(image_processor.crop_size , {'height': 1_8, 'width': 1_8})
__snake_case : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4)
self.assertEqual(image_processor.size , {'shortest_edge': 4_2})
self.assertEqual(image_processor.crop_size , {'height': 8_4, 'width': 8_4})
def SCREAMING_SNAKE_CASE__ (self) -> Union[str, Any]:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
__snake_case : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
__snake_case : int = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : List[Any] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
__snake_case : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=__a , numpify=__a)
for image in image_inputs:
self.assertIsInstance(__a , np.ndarray)
# Test not batched input
__snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : int = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Any = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
__snake_case : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__a , torchify=__a)
for image in image_inputs:
self.assertIsInstance(__a , torch.Tensor)
# Test not batched input
__snake_case : Any = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : Union[str, Any] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
@require_torch
@require_vision
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = ChineseCLIPImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ (self) -> Optional[int]:
"""simple docstring"""
__snake_case : Optional[Any] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__a)
__snake_case : List[Any] = 3
@property
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : Any = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , 'do_resize'))
self.assertTrue(hasattr(__a , 'size'))
self.assertTrue(hasattr(__a , 'do_center_crop'))
self.assertTrue(hasattr(__a , 'center_crop'))
self.assertTrue(hasattr(__a , 'do_normalize'))
self.assertTrue(hasattr(__a , 'image_mean'))
self.assertTrue(hasattr(__a , 'image_std'))
self.assertTrue(hasattr(__a , 'do_convert_rgb'))
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
__snake_case : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
__snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.expected_encoded_image_num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
__snake_case : Optional[int] = image_processing(__a , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.expected_encoded_image_num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , ) | 61 | 0 |
'''simple docstring'''
import cva
import numpy as np
class a_ :
def __init__(self , __a , __a) -> int:
"""simple docstring"""
if k in (0.04, 0.06):
__snake_case : List[str] = k
__snake_case : str = window_size
else:
raise ValueError('invalid k value')
def __str__(self) -> str:
"""simple docstring"""
return str(self.k)
def SCREAMING_SNAKE_CASE__ (self , __a) -> tuple[cva.Mat, list[list[int]]]:
"""simple docstring"""
__snake_case : Any = cva.imread(__a , 0)
__snake_case : Optional[Any] = img.shape
__snake_case : list[list[int]] = []
__snake_case : str = img.copy()
__snake_case : Optional[int] = cva.cvtColor(__a , cva.COLOR_GRAY2RGB)
__snake_case : List[str] = np.gradient(__a)
__snake_case : Optional[Any] = dx**2
__snake_case : int = dy**2
__snake_case : List[str] = dx * dy
__snake_case : Any = 0.04
__snake_case : List[Any] = self.window_size // 2
for y in range(__a , h - offset):
for x in range(__a , w - offset):
__snake_case : Union[str, Any] = ixx[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
__snake_case : int = iyy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
__snake_case : List[Any] = ixy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
__snake_case : Dict = (wxx * wyy) - (wxy**2)
__snake_case : List[str] = wxx + wyy
__snake_case : Tuple = det - k * (trace**2)
# Can change the value
if r > 0.5:
corner_list.append([x, y, r])
color_img.itemset((y, x, 0) , 0)
color_img.itemset((y, x, 1) , 0)
color_img.itemset((y, x, 2) , 2_5_5)
return color_img, corner_list
if __name__ == "__main__":
__A = HarrisCorner(0.04, 3)
__A , __A = edge_detect.detect('''path_to_image''')
cva.imwrite('''detect.png''', color_img) | 701 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json''',
# See all ViT MSN models at https://huggingface.co/models?filter=vit_msn
}
class a_ ( UpperCamelCase_ ):
_snake_case = """vit_msn"""
def __init__(self , __a=7_6_8 , __a=1_2 , __a=1_2 , __a=3_0_7_2 , __a="gelu" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-06 , __a=2_2_4 , __a=1_6 , __a=3 , __a=True , **__a , ) -> Any:
"""simple docstring"""
super().__init__(**__a)
__snake_case : List[str] = hidden_size
__snake_case : Optional[int] = num_hidden_layers
__snake_case : Optional[Any] = num_attention_heads
__snake_case : str = intermediate_size
__snake_case : List[str] = hidden_act
__snake_case : List[Any] = hidden_dropout_prob
__snake_case : Tuple = attention_probs_dropout_prob
__snake_case : List[str] = initializer_range
__snake_case : Optional[int] = layer_norm_eps
__snake_case : Dict = image_size
__snake_case : int = patch_size
__snake_case : Dict = num_channels
__snake_case : Tuple = qkv_bias | 61 | 0 |
'''simple docstring'''
from __future__ import annotations
from collections import namedtuple
from dataclasses import dataclass
@dataclass
class a_ :
_snake_case = 42
_snake_case = None
_snake_case = None
__A = namedtuple('''CoinsDistribResult''', '''moves excess''')
def _SCREAMING_SNAKE_CASE ( A : TreeNode | None ) -> int:
"""simple docstring"""
if root is None:
return 0
# Validation
def count_nodes(A : TreeNode | None ) -> int:
if node is None:
return 0
return count_nodes(node.left ) + count_nodes(node.right ) + 1
def count_coins(A : TreeNode | None ) -> int:
if node is None:
return 0
return count_coins(node.left ) + count_coins(node.right ) + node.data
if count_nodes(A ) != count_coins(A ):
raise ValueError('The nodes number should be same as the number of coins' )
# Main calculation
def get_distrib(A : TreeNode | None ) -> CoinsDistribResult:
if node is None:
return CoinsDistribResult(0 , 1 )
__snake_case : List[str] = get_distrib(node.left )
__snake_case : Optional[int] = get_distrib(node.right )
__snake_case : Any = 1 - left_distrib_excess
__snake_case : str = 1 - right_distrib_excess
__snake_case : List[str] = (
left_distrib_moves
+ right_distrib_moves
+ abs(A )
+ abs(A )
)
__snake_case : List[str] = node.data - coins_to_left - coins_to_right
return CoinsDistribResult(A , A )
return get_distrib(A )[0]
if __name__ == "__main__":
import doctest
doctest.testmod() | 702 |
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( A : float , A : list[float] ) -> float:
"""simple docstring"""
if discount_rate < 0:
raise ValueError('Discount rate cannot be negative' )
if not cash_flows:
raise ValueError('Cash flows list cannot be empty' )
__snake_case : List[str] = sum(
cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(A ) )
return round(A , ndigits=2 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 61 | 0 |
'''simple docstring'''
from __future__ import annotations
def _SCREAMING_SNAKE_CASE ( A : list[int] , A : list[int] , A : list[int] , A : list[list[str]] , A : int , ) -> None:
"""simple docstring"""
__snake_case : str = len(A )
# If row is equal to the size of the board it means there are a queen in each row in
# the current board (possible_board)
if row == n:
# We convert the variable possible_board that looks like this: [1, 3, 0, 2] to
# this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . ']
boards.append(['. ' * i + 'Q ' + '. ' * (n - 1 - i) for i in possible_board] )
return
# We iterate each column in the row to find all possible results in each row
for col in range(A ):
# We apply that we learned previously. First we check that in the current board
# (possible_board) there are not other same value because if there is it means
# that there are a collision in vertical. Then we apply the two formulas we
# learned before:
#
# 45º: y - x = b or 45: row - col = b
# 135º: y + x = b or row + col = b.
#
# And we verify if the results of this two formulas not exist in their variables
# respectively. (diagonal_right_collisions, diagonal_left_collisions)
#
# If any or these are True it means there is a collision so we continue to the
# next value in the for loop.
if (
col in possible_board
or row - col in diagonal_right_collisions
or row + col in diagonal_left_collisions
):
continue
# If it is False we call dfs function again and we update the inputs
depth_first_search(
[*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , A , A , )
def _SCREAMING_SNAKE_CASE ( A : int ) -> None:
"""simple docstring"""
__snake_case : list[list[str]] = []
depth_first_search([] , [] , [] , A , A )
# Print all the boards
for board in boards:
for column in board:
print(A )
print('' )
print(len(A ) , 'solutions were found.' )
if __name__ == "__main__":
import doctest
doctest.testmod()
n_queens_solution(4) | 703 |
'''simple docstring'''
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__) | 61 | 0 |
'''simple docstring'''
from collections import OrderedDict
from typing import Any, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'''EleutherAI/gpt-neo-1.3B''': '''https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json''',
# See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo
}
class a_ ( UpperCamelCase_ ):
_snake_case = """gpt_neo"""
_snake_case = ["""past_key_values"""]
_snake_case = {"""num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""}
def __init__(self , __a=5_0_2_5_7 , __a=2_0_4_8 , __a=2_0_4_8 , __a=2_4 , __a=[[["global", "local"], 1_2]] , __a=1_6 , __a=None , __a=2_5_6 , __a="gelu_new" , __a=0.0 , __a=0.0 , __a=0.0 , __a=0.1 , __a=1E-5 , __a=0.02 , __a=True , __a=5_0_2_5_6 , __a=5_0_2_5_6 , **__a , ) -> Dict:
"""simple docstring"""
__snake_case : Tuple = vocab_size
__snake_case : Tuple = max_position_embeddings
__snake_case : List[Any] = hidden_size
__snake_case : int = num_layers
__snake_case : Dict = num_heads
__snake_case : Optional[int] = intermediate_size
__snake_case : List[Any] = window_size
__snake_case : Optional[Any] = activation_function
__snake_case : str = resid_dropout
__snake_case : str = embed_dropout
__snake_case : Union[str, Any] = attention_dropout
__snake_case : Any = classifier_dropout
__snake_case : Tuple = layer_norm_epsilon
__snake_case : Any = initializer_range
__snake_case : Optional[int] = use_cache
__snake_case : List[str] = bos_token_id
__snake_case : int = eos_token_id
__snake_case : Any = attention_types
__snake_case : Tuple = self.expand_attention_types_params(__a)
if len(self.attention_layers) != self.num_layers:
raise ValueError(
'Configuration for convolutional module is incorrect. '
'It is required that `len(config.attention_layers)` == `config.num_layers` '
F"""but is `len(config.attention_layers) = {len(self.attention_layers)}`, """
F"""`config.num_layers = {self.num_layers}`. """
'`config.attention_layers` is prepared using `config.attention_types`. '
'Please verify the value of `config.attention_types` argument.')
super().__init__(bos_token_id=__a , eos_token_id=__a , **__a)
@staticmethod
def SCREAMING_SNAKE_CASE__ (__a) -> Tuple:
"""simple docstring"""
__snake_case : List[str] = []
for item in attention_types:
for _ in range(item[1]):
attentions.extend(item[0])
return attentions
def _SCREAMING_SNAKE_CASE ( A : Any , A : Tuple , A : Dict , A : List[str] ) -> Optional[int]:
"""simple docstring"""
import torch
__snake_case : str = input.size()
__snake_case : str = len(A )
__snake_case : List[Any] = shape[dimension]
__snake_case : int = torch.arange(0 , A , A )
__snake_case : List[Any] = torch.div(sizedim - size , A , rounding_mode='floor' ) + 1
__snake_case : Dict = torch.arange(A ) + low_indices[:min_length][:, None]
__snake_case : int = [slice(A )] * rank
__snake_case : Dict = indices
__snake_case : List[str] = input[s]
__snake_case : Tuple = list(range(0 , rank + 1 ) )
perm.append(perm.pop(dimension + 1 ) )
return sliced.permute(A )
def _SCREAMING_SNAKE_CASE ( A : Tuple , A : List[Any] ) -> Union[str, Any]:
"""simple docstring"""
import torch
__snake_case : Tuple = torch.arange(1 , A )
__snake_case : Tuple = torch.remainder(A , A )
__snake_case : Optional[Any] = remainders == 0
__snake_case : Optional[int] = candidates[divisor_indices]
__snake_case : Tuple = torch.max(A )
return largest_divisor, torch.div(A , A , rounding_mode='floor' )
class a_ ( UpperCamelCase_ ):
@property
def SCREAMING_SNAKE_CASE__ (self) -> Mapping[str, Mapping[int, str]]:
"""simple docstring"""
__snake_case : str = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}})
if self.use_past:
self.fill_with_past_key_values_(__a , direction='inputs')
__snake_case : List[str] = {0: 'batch', 1: 'past_sequence + sequence'}
else:
__snake_case : Dict = {0: 'batch', 1: 'sequence'}
return common_inputs
@property
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return self._config.num_heads
def SCREAMING_SNAKE_CASE__ (self , __a , __a = -1 , __a = -1 , __a = False , __a = None , ) -> Mapping[str, Any]:
"""simple docstring"""
__snake_case : int = super(__a , self).generate_dummy_inputs(
__a , batch_size=__a , seq_length=__a , is_pair=__a , framework=__a)
# We need to order the input in the way they appears in the forward()
__snake_case : str = OrderedDict({'input_ids': common_inputs['input_ids']})
# Need to add the past_keys
if self.use_past:
if not is_torch_available():
raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.')
else:
import torch
__snake_case : Optional[Any] = common_inputs['input_ids'].shape
# Not using the same length for past_key_values
__snake_case : Optional[Any] = seqlen + 2
__snake_case : str = (
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
__snake_case : List[Any] = [
(torch.zeros(__a), torch.zeros(__a)) for _ in range(self.num_layers)
]
__snake_case : Any = common_inputs['attention_mask']
if self.use_past:
__snake_case : Any = ordered_inputs['attention_mask'].dtype
__snake_case : Optional[Any] = torch.cat(
[ordered_inputs['attention_mask'], torch.ones(__a , __a , dtype=__a)] , dim=1)
return ordered_inputs
@property
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
return 1_3 | 704 |
'''simple docstring'''
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run
import sys
import warnings
from os.path import abspath, dirname, join
# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
__A = abspath(join(dirname(dirname(__file__)), '''src'''))
sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='''ignore''', category=FutureWarning)
def _SCREAMING_SNAKE_CASE ( A : Tuple ) -> str:
"""simple docstring"""
from diffusers.utils.testing_utils import pytest_addoption_shared
pytest_addoption_shared(A )
def _SCREAMING_SNAKE_CASE ( A : int ) -> Optional[int]:
"""simple docstring"""
from diffusers.utils.testing_utils import pytest_terminal_summary_main
__snake_case : Any = terminalreporter.config.getoption('--make-reports' )
if make_reports:
pytest_terminal_summary_main(A , id=A ) | 61 | 0 |
'''simple docstring'''
import os
import unittest
from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer
from transformers.testing_utils import require_jieba, tooslow
from ...test_tokenization_common import TokenizerTesterMixin
@require_jieba
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = CpmAntTokenizer
_snake_case = False
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
super().setUp()
__snake_case : List[Any] = [
'<d>',
'</d>',
'<s>',
'</s>',
'</_>',
'<unk>',
'<pad>',
'</n>',
'我',
'是',
'C',
'P',
'M',
'A',
'n',
't',
]
__snake_case : List[Any] = 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]))
@tooslow
def SCREAMING_SNAKE_CASE__ (self) -> int:
"""simple docstring"""
__snake_case : Any = CpmAntTokenizer.from_pretrained('openbmb/cpm-ant-10b')
__snake_case : Union[str, Any] = '今天天气真好!'
__snake_case : Tuple = ['今天', '天气', '真', '好', '!']
__snake_case : Tuple = tokenizer.tokenize(__a)
self.assertListEqual(__a , __a)
__snake_case : Optional[int] = '今天天气真好!'
__snake_case : str = [tokenizer.bos_token] + tokens
__snake_case : Any = [6, 9_8_0_2, 1_4_9_6_2, 2_0_8_2, 8_3_1, 2_4_4]
self.assertListEqual(tokenizer.convert_tokens_to_ids(__a) , __a)
__snake_case : List[Any] = tokenizer.decode(__a)
self.assertEqual(__a , __a)
| 705 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
__A = {
'''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''],
'''tokenization_biogpt''': ['''BioGptTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''BioGptForCausalLM''',
'''BioGptForTokenClassification''',
'''BioGptForSequenceClassification''',
'''BioGptModel''',
'''BioGptPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig
from .tokenization_biogpt import BioGptTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_biogpt import (
BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST,
BioGptForCausalLM,
BioGptForSequenceClassification,
BioGptForTokenClassification,
BioGptModel,
BioGptPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 61 | 0 |
'''simple docstring'''
import unittest
import numpy as np
from transformers import RobertaPreLayerNormConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
if is_flax_available():
import jax.numpy as jnp
from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import (
FlaxRobertaPreLayerNormForCausalLM,
FlaxRobertaPreLayerNormForMaskedLM,
FlaxRobertaPreLayerNormForMultipleChoice,
FlaxRobertaPreLayerNormForQuestionAnswering,
FlaxRobertaPreLayerNormForSequenceClassification,
FlaxRobertaPreLayerNormForTokenClassification,
FlaxRobertaPreLayerNormModel,
)
class a_ ( unittest.TestCase ):
def __init__(self , __a , __a=1_3 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=9_9 , __a=3_2 , __a=5 , __a=4 , __a=3_7 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_1_2 , __a=1_6 , __a=2 , __a=0.02 , __a=4 , ) -> Dict:
"""simple docstring"""
__snake_case : List[Any] = parent
__snake_case : Union[str, Any] = batch_size
__snake_case : int = seq_length
__snake_case : Optional[int] = is_training
__snake_case : Dict = use_attention_mask
__snake_case : List[str] = use_token_type_ids
__snake_case : Tuple = use_labels
__snake_case : List[str] = vocab_size
__snake_case : List[Any] = hidden_size
__snake_case : Union[str, Any] = num_hidden_layers
__snake_case : Union[str, Any] = num_attention_heads
__snake_case : str = intermediate_size
__snake_case : List[Any] = hidden_act
__snake_case : Optional[Any] = hidden_dropout_prob
__snake_case : List[str] = attention_probs_dropout_prob
__snake_case : Tuple = max_position_embeddings
__snake_case : Union[str, Any] = type_vocab_size
__snake_case : Any = type_sequence_label_size
__snake_case : int = initializer_range
__snake_case : Tuple = num_choices
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
__snake_case : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
__snake_case : List[Any] = None
if self.use_attention_mask:
__snake_case : List[str] = random_attention_mask([self.batch_size, self.seq_length])
__snake_case : Optional[Any] = None
if self.use_token_type_ids:
__snake_case : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size)
__snake_case : List[str] = RobertaPreLayerNormConfig(
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=__a , initializer_range=self.initializer_range , )
return config, input_ids, token_type_ids, attention_mask
def SCREAMING_SNAKE_CASE__ (self) -> Dict:
"""simple docstring"""
__snake_case : List[str] = self.prepare_config_and_inputs()
__snake_case : Tuple = config_and_inputs
__snake_case : Union[str, Any] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask}
return config, inputs_dict
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
__snake_case : Optional[Any] = self.prepare_config_and_inputs()
__snake_case : int = config_and_inputs
__snake_case : int = True
__snake_case : Union[str, Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
__snake_case : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2)
return (
config,
input_ids,
token_type_ids,
encoder_hidden_states,
encoder_attention_mask,
)
@require_flax
# Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40
class a_ ( UpperCamelCase_ , unittest.TestCase ):
_snake_case = True
_snake_case = (
(
FlaxRobertaPreLayerNormModel,
FlaxRobertaPreLayerNormForCausalLM,
FlaxRobertaPreLayerNormForMaskedLM,
FlaxRobertaPreLayerNormForSequenceClassification,
FlaxRobertaPreLayerNormForTokenClassification,
FlaxRobertaPreLayerNormForMultipleChoice,
FlaxRobertaPreLayerNormForQuestionAnswering,
)
if is_flax_available()
else ()
)
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : str = FlaxRobertaPreLayerNormModelTester(self)
@slow
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
for model_class_name in self.all_model_classes:
__snake_case : str = model_class_name.from_pretrained('andreasmadsen/efficient_mlm_m0.40' , from_pt=__a)
__snake_case : List[Any] = model(np.ones((1, 1)))
self.assertIsNotNone(__a)
@require_flax
class a_ ( unittest.TestCase ):
@slow
def SCREAMING_SNAKE_CASE__ (self) -> Any:
"""simple docstring"""
__snake_case : List[Any] = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('andreasmadsen/efficient_mlm_m0.40' , from_pt=__a)
__snake_case : Optional[int] = np.array([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] , dtype=jnp.intaa)
__snake_case : List[str] = model(__a)[0]
__snake_case : Dict = [1, 1_1, 5_0_2_6_5]
self.assertEqual(list(output.shape) , __a)
# compare the actual values for a slice.
__snake_case : Optional[Any] = np.array(
[[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa)
self.assertTrue(np.allclose(output[:, :3, :3] , __a , atol=1E-4))
@slow
def SCREAMING_SNAKE_CASE__ (self) -> List[str]:
"""simple docstring"""
__snake_case : Optional[int] = FlaxRobertaPreLayerNormModel.from_pretrained('andreasmadsen/efficient_mlm_m0.40' , from_pt=__a)
__snake_case : Dict = np.array([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] , dtype=jnp.intaa)
__snake_case : List[str] = model(__a)[0]
# compare the actual values for a slice.
__snake_case : Tuple = np.array(
[[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa)
self.assertTrue(np.allclose(output[:, :3, :3] , __a , atol=1E-4)) | 706 |
'''simple docstring'''
from packaging import version
from .import_utils import is_accelerate_available
if is_accelerate_available():
import accelerate
def _SCREAMING_SNAKE_CASE ( A : Optional[Any] ) -> int:
"""simple docstring"""
if not is_accelerate_available():
return method
__snake_case : Optional[Any] = version.parse(accelerate.__version__ ).base_version
if version.parse(A ) < version.parse('0.17.0' ):
return method
def wrapper(self : Optional[Any] , *A : Optional[Any] , **A : Optional[int] ):
if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ):
self._hf_hook.pre_forward(self )
return method(self , *A , **A )
return wrapper | 61 | 0 |
'''simple docstring'''
import warnings
from ...utils import logging
from .image_processing_dpt import DPTImageProcessor
__A = logging.get_logger(__name__)
class a_ ( UpperCamelCase_ ):
def __init__(self , *__a , **__a) -> None:
"""simple docstring"""
warnings.warn(
'The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'
' use DPTImageProcessor instead.' , __a , )
super().__init__(*__a , **__a) | 707 |
'''simple docstring'''
import unittest
from transformers import load_tool
from transformers.utils import is_torch_available
if is_torch_available():
import torch
from transformers.testing_utils import require_torch
from .test_tools_common import ToolTesterMixin
@require_torch
class a_ ( unittest.TestCase , UpperCamelCase_ ):
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
__snake_case : List[str] = load_tool('text-to-speech')
self.tool.setup()
def SCREAMING_SNAKE_CASE__ (self) -> Optional[Any]:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : Dict = self.tool('hey')
__snake_case : List[Any] = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , ))
def SCREAMING_SNAKE_CASE__ (self) -> List[Any]:
"""simple docstring"""
torch.manual_seed(0)
__snake_case : Any = self.tool('hey')
__snake_case : Any = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485]) , )) | 61 | 0 |
'''simple docstring'''
import argparse
import os
import re
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
__A = '''src/diffusers'''
# Matches is_xxx_available()
__A = re.compile(r'''is\_([a-z_]*)_available\(\)''')
# Matches from xxx import bla
__A = re.compile(r'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''')
__A = '''
{0} = None
'''
__A = '''
class {0}(metaclass=DummyObject):
_backends = {1}
def __init__(self, *args, **kwargs):
requires_backends(self, {1})
@classmethod
def from_config(cls, *args, **kwargs):
requires_backends(cls, {1})
@classmethod
def from_pretrained(cls, *args, **kwargs):
requires_backends(cls, {1})
'''
__A = '''
def {0}(*args, **kwargs):
requires_backends({0}, {1})
'''
def _SCREAMING_SNAKE_CASE ( A : str ) -> Dict:
"""simple docstring"""
__snake_case : str = _re_backend.findall(A )
if len(A ) == 0:
return None
return "_and_".join(A )
def _SCREAMING_SNAKE_CASE ( ) -> Tuple:
"""simple docstring"""
with open(os.path.join(A , '__init__.py' ) , 'r' , encoding='utf-8' , newline='\n' ) as f:
__snake_case : List[str] = f.readlines()
# Get to the point we do the actual imports for type checking
__snake_case : Dict = 0
__snake_case : int = {}
# Go through the end of the file
while line_index < len(A ):
# If the line contains is_backend_available, we grab all objects associated with the `else` block
__snake_case : Tuple = find_backend(lines[line_index] )
if backend is not None:
while not lines[line_index].startswith('else:' ):
line_index += 1
line_index += 1
__snake_case : int = []
# Until we unindent, add backend objects to the list
while line_index < len(A ) and len(lines[line_index] ) > 1:
__snake_case : Dict = lines[line_index]
__snake_case : Optional[Any] = _re_single_line_import.search(A )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(', ' ) )
elif line.startswith(' ' * 8 ):
objects.append(line[8:-2] )
line_index += 1
if len(A ) > 0:
__snake_case : List[str] = objects
else:
line_index += 1
return backend_specific_objects
def _SCREAMING_SNAKE_CASE ( A : Tuple , A : Optional[int] ) -> Dict:
"""simple docstring"""
if name.isupper():
return DUMMY_CONSTANT.format(A )
elif name.islower():
return DUMMY_FUNCTION.format(A , A )
else:
return DUMMY_CLASS.format(A , A )
def _SCREAMING_SNAKE_CASE ( A : int=None ) -> List[str]:
"""simple docstring"""
if backend_specific_objects is None:
__snake_case : Optional[Any] = read_init()
# For special correspondence backend to module name as used in the function requires_modulename
__snake_case : Optional[int] = {}
for backend, objects in backend_specific_objects.items():
__snake_case : Tuple = '[' + ', '.join(F"""\"{b}\"""" for b in backend.split('_and_' ) ) + ']'
__snake_case : Union[str, Any] = '# This file is autogenerated by the command `make fix-copies`, do not edit.\n'
dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
dummy_file += "\n".join([create_dummy_object(A , A ) for o in objects] )
__snake_case : List[str] = dummy_file
return dummy_files
def _SCREAMING_SNAKE_CASE ( A : List[str]=False ) -> List[Any]:
"""simple docstring"""
__snake_case : Dict = create_dummy_files()
# For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
__snake_case : Union[str, Any] = {'torch': 'pt'}
# Locate actual dummy modules and read their content.
__snake_case : List[Any] = os.path.join(A , 'utils' )
__snake_case : int = {
backend: os.path.join(A , F"""dummy_{short_names.get(A , A )}_objects.py""" )
for backend in dummy_files.keys()
}
__snake_case : int = {}
for backend, file_path in dummy_file_paths.items():
if os.path.isfile(A ):
with open(A , 'r' , encoding='utf-8' , newline='\n' ) as f:
__snake_case : List[Any] = f.read()
else:
__snake_case : Tuple = ''
for backend in dummy_files.keys():
if dummy_files[backend] != actual_dummies[backend]:
if overwrite:
print(
F"""Updating diffusers.utils.dummy_{short_names.get(A , A )}_objects.py as the main """
'__init__ has new objects.' )
with open(dummy_file_paths[backend] , 'w' , encoding='utf-8' , newline='\n' ) as f:
f.write(dummy_files[backend] )
else:
raise ValueError(
'The main __init__ has objects that are not present in '
F"""diffusers.utils.dummy_{short_names.get(A , A )}_objects.py. Run `make fix-copies` """
'to fix this.' )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''')
__A = parser.parse_args()
check_dummies(args.fix_and_overwrite) | 708 |
'''simple docstring'''
import math
class a_ :
def __init__(self , __a=0) -> Any: # a graph with Node 0,1,...,N-1
"""simple docstring"""
__snake_case : List[str] = n
__snake_case : Tuple = [
[math.inf for j in range(0 , __a)] for i in range(0 , __a)
] # adjacency matrix for weight
__snake_case : Union[str, Any] = [
[math.inf for j in range(0 , __a)] for i in range(0 , __a)
] # dp[i][j] stores minimum distance from i to j
def SCREAMING_SNAKE_CASE__ (self , __a , __a , __a) -> Tuple:
"""simple docstring"""
__snake_case : Union[str, Any] = w
def SCREAMING_SNAKE_CASE__ (self) -> Tuple:
"""simple docstring"""
for k in range(0 , self.n):
for i in range(0 , self.n):
for j in range(0 , self.n):
__snake_case : List[Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j])
def SCREAMING_SNAKE_CASE__ (self , __a , __a) -> Optional[int]:
"""simple docstring"""
return self.dp[u][v]
if __name__ == "__main__":
__A = Graph(5)
graph.add_edge(0, 2, 9)
graph.add_edge(0, 4, 1_0)
graph.add_edge(1, 3, 5)
graph.add_edge(2, 3, 7)
graph.add_edge(3, 0, 1_0)
graph.add_edge(3, 1, 2)
graph.add_edge(3, 2, 1)
graph.add_edge(3, 4, 6)
graph.add_edge(4, 1, 3)
graph.add_edge(4, 2, 4)
graph.add_edge(4, 3, 9)
graph.floyd_warshall()
graph.show_min(1, 4)
graph.show_min(0, 3) | 61 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.