code stringlengths 82 53.2k | code_codestyle int64 0 721 | style_context stringlengths 91 41.9k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
'''simple docstring'''
import argparse
import os
import torch
from transformers.utils import WEIGHTS_NAME
lowercase__ =['small', 'medium', 'large']
lowercase__ ='lm_head.decoder.weight'
lowercase__ ='lm_head.weight'
def UpperCamelCase_ ( A__ , A__ ):
a_ = torch.load(A__ )
a_ = d.pop(A__ )
os.makedirs(A__ , exist_ok=A__ )
torch.save(A__ , os.path.join(A__ , A__ ) )
if __name__ == "__main__":
lowercase__ =argparse.ArgumentParser()
parser.add_argument('--dialogpt_path', default='.', type=str)
lowercase__ =parser.parse_args()
for MODEL in DIALOGPT_MODELS:
lowercase__ =os.path.join(args.dialogpt_path, F"""{MODEL}_ft.pkl""")
lowercase__ =F"""./DialoGPT-{MODEL}"""
convert_dialogpt_checkpoint(
checkpoint_path,
pytorch_dump_folder_path,
)
| 263 |
'''simple docstring'''
import comet # From: unbabel-comet
import torch
import datasets
lowercase__ =datasets.logging.get_logger(__name__)
lowercase__ ='\\n@inproceedings{rei-EtAl:2020:WMT,\n author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon},\n title = {Unbabel\'s Participation in the WMT20 Metrics Shared Task},\n booktitle = {Proceedings of the Fifth Conference on Machine Translation},\n month = {November},\n year = {2020},\n address = {Online},\n publisher = {Association for Computational Linguistics},\n pages = {909--918},\n}\n@inproceedings{rei-etal-2020-comet,\n title = "{COMET}: A Neural Framework for {MT} Evaluation",\n author = "Rei, Ricardo and\n Stewart, Craig and\n Farinha, Ana C and\n Lavie, Alon",\n booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",\n month = nov,\n year = "2020",\n address = "Online",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/2020.emnlp-main.213",\n pages = "2685--2702",\n}\n'
lowercase__ ='\\nCrosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM).\nWith the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n'
lowercase__ ='\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n `scores`: List of scores.\n\nExamples:\n\n >>> comet_metric = datasets.load_metric(\'comet\')\n >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\') # you can also choose which model to use\n >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]\n >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]\n >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]\n >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n >>> print([round(v, 2) for v in results["scores"]])\n [0.19, 0.92]\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class a_ ( datasets.Metric ):
def lowerCAmelCase__ ( self ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , homepage="""https://unbabel.github.io/COMET/html/index.html""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"""sources""": datasets.Value("""string""" , id="""sequence""" ),
"""predictions""": datasets.Value("""string""" , id="""sequence""" ),
"""references""": datasets.Value("""string""" , id="""sequence""" ),
} ) , codebase_urls=["""https://github.com/Unbabel/COMET"""] , reference_urls=[
"""https://github.com/Unbabel/COMET""",
"""https://www.aclweb.org/anthology/2020.emnlp-main.213/""",
"""http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6""",
] , )
def lowerCAmelCase__ ( self , UpperCAmelCase ):
if self.config_name == "default":
a_ = comet.load_from_checkpoint(comet.download_model("""wmt20-comet-da""" ) )
else:
a_ = comet.load_from_checkpoint(comet.download_model(self.config_name ) )
def lowerCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=False ):
if gpus is None:
a_ = 1 if torch.cuda.is_available() else 0
a_ = {"""src""": sources, """mt""": predictions, """ref""": references}
a_ = [dict(zip(UpperCAmelCase , UpperCAmelCase ) ) for t in zip(*data.values() )]
a_ , a_ = self.scorer.predict(UpperCAmelCase , gpus=UpperCAmelCase , progress_bar=UpperCAmelCase )
return {"mean_score": mean_score, "scores": scores}
| 263 | 1 |
"""simple docstring"""
class UpperCAmelCase_ :
def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Optional[Any]:
__lowercase : Tuple = None
__lowercase : Optional[Any] = None
__lowercase : Union[str, Any] = graph
self._normalize_graph(UpperCamelCase_ , UpperCamelCase_ )
__lowercase : Optional[Any] = len(UpperCamelCase_ )
__lowercase : Tuple = None
def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ ) -> Dict:
if sources is int:
__lowercase : int = [sources]
if sinks is int:
__lowercase : Optional[Any] = [sinks]
if len(UpperCamelCase_ ) == 0 or len(UpperCamelCase_ ) == 0:
return
__lowercase : List[Any] = sources[0]
__lowercase : Tuple = sinks[0]
# make fake vertex if there are more
# than one source or sink
if len(UpperCamelCase_ ) > 1 or len(UpperCamelCase_ ) > 1:
__lowercase : int = 0
for i in sources:
max_input_flow += sum(self.graph[i] )
__lowercase : Optional[int] = len(self.graph ) + 1
for room in self.graph:
room.insert(0 , 0 )
self.graph.insert(0 , [0] * size )
for i in sources:
__lowercase : List[str] = max_input_flow
__lowercase : str = 0
__lowercase : Any = len(self.graph ) + 1
for room in self.graph:
room.append(0 )
self.graph.append([0] * size )
for i in sinks:
__lowercase : Union[str, Any] = max_input_flow
__lowercase : Tuple = size - 1
def _lowerCamelCase ( self ) -> int:
if self.maximum_flow_algorithm is None:
raise Exception('''You need to set maximum flow algorithm before.''' )
if self.source_index is None or self.sink_index is None:
return 0
self.maximum_flow_algorithm.execute()
return self.maximum_flow_algorithm.getMaximumFlow()
def _lowerCamelCase ( self , UpperCamelCase_ ) -> Tuple:
__lowercase : Optional[int] = algorithm(self )
class UpperCAmelCase_ :
def __init__( self , UpperCamelCase_ ) -> str:
__lowercase : Optional[Any] = flow_network
__lowercase : Optional[int] = flow_network.verticesCount
__lowercase : Dict = flow_network.sourceIndex
__lowercase : int = flow_network.sinkIndex
# it's just a reference, so you shouldn't change
# it in your algorithms, use deep copy before doing that
__lowercase : Optional[int] = flow_network.graph
__lowercase : Any = False
def _lowerCamelCase ( self ) -> List[Any]:
if not self.executed:
self._algorithm()
__lowercase : Optional[Any] = True
def _lowerCamelCase ( self ) -> List[str]:
pass
class UpperCAmelCase_ ( snake_case ):
def __init__( self , UpperCamelCase_ ) -> Any:
super().__init__(UpperCamelCase_ )
# use this to save your result
__lowercase : Optional[int] = -1
def _lowerCamelCase ( self ) -> Optional[Any]:
if not self.executed:
raise Exception('''You should execute algorithm before using its result!''' )
return self.maximum_flow
class UpperCAmelCase_ ( snake_case ):
def __init__( self , UpperCamelCase_ ) -> Optional[Any]:
super().__init__(UpperCamelCase_ )
__lowercase : str = [[0] * self.verticies_count for i in range(self.verticies_count )]
__lowercase : Optional[int] = [0] * self.verticies_count
__lowercase : Dict = [0] * self.verticies_count
def _lowerCamelCase ( self ) -> List[Any]:
__lowercase : Tuple = self.verticies_count
# push some substance to graph
for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ):
self.preflow[self.source_index][nextvertex_index] += bandwidth
self.preflow[nextvertex_index][self.source_index] -= bandwidth
self.excesses[nextvertex_index] += bandwidth
# Relabel-to-front selection rule
__lowercase : Tuple = [
i
for i in range(self.verticies_count )
if i != self.source_index and i != self.sink_index
]
# move through list
__lowercase : List[str] = 0
while i < len(UpperCamelCase_ ):
__lowercase : Dict = vertices_list[i]
__lowercase : Optional[int] = self.heights[vertex_index]
self.process_vertex(UpperCamelCase_ )
if self.heights[vertex_index] > previous_height:
# if it was relabeled, swap elements
# and start from 0 index
vertices_list.insert(0 , vertices_list.pop(UpperCamelCase_ ) )
__lowercase : Optional[Any] = 0
else:
i += 1
__lowercase : Union[str, Any] = sum(self.preflow[self.source_index] )
def _lowerCamelCase ( self , UpperCamelCase_ ) -> List[Any]:
while self.excesses[vertex_index] > 0:
for neighbour_index in range(self.verticies_count ):
# if it's neighbour and current vertex is higher
if (
self.graph[vertex_index][neighbour_index]
- self.preflow[vertex_index][neighbour_index]
> 0
and self.heights[vertex_index] > self.heights[neighbour_index]
):
self.push(UpperCamelCase_ , UpperCamelCase_ )
self.relabel(UpperCamelCase_ )
def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ ) -> str:
__lowercase : int = min(
self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , )
self.preflow[from_index][to_index] += preflow_delta
self.preflow[to_index][from_index] -= preflow_delta
self.excesses[from_index] -= preflow_delta
self.excesses[to_index] += preflow_delta
def _lowerCamelCase ( self , UpperCamelCase_ ) -> Dict:
__lowercase : Any = None
for to_index in range(self.verticies_count ):
if (
self.graph[vertex_index][to_index]
- self.preflow[vertex_index][to_index]
> 0
) and (min_height is None or self.heights[to_index] < min_height):
__lowercase : Optional[Any] = self.heights[to_index]
if min_height is not None:
__lowercase : Tuple = min_height + 1
if __name__ == "__main__":
a_ = [0]
a_ = [3]
# graph = [
# [0, 0, 4, 6, 0, 0],
# [0, 0, 5, 2, 0, 0],
# [0, 0, 0, 0, 4, 4],
# [0, 0, 0, 0, 6, 6],
# [0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0],
# ]
a_ = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]]
# prepare our network
a_ = FlowNetwork(graph, entrances, exits)
# set algorithm
flow_network.set_maximum_flow_algorithm(PushRelabelExecutor)
# and calculate
a_ = flow_network.find_maximum_flow()
print(F"maximum flow is {maximum_flow}")
| 523 |
"""simple docstring"""
import unittest
import numpy as np
import torch
from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad
class UpperCAmelCase_ ( unittest.TestCase ):
def _lowerCamelCase ( self ) -> List[str]:
__lowercase : Union[str, Any] = 10
def _lowerCamelCase ( self ) -> str:
__lowercase : List[str] = [1, 2, 3, 4]
__lowercase : List[Any] = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0]
self.assertEqual(truncate_or_pad(UpperCamelCase_ , self.block_size , 0 ) , UpperCamelCase_ )
def _lowerCamelCase ( self ) -> Optional[int]:
__lowercase : Optional[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
__lowercase : Any = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.assertEqual(truncate_or_pad(UpperCamelCase_ , self.block_size , 0 ) , UpperCamelCase_ )
def _lowerCamelCase ( self ) -> int:
__lowercase : List[str] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
__lowercase : List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.assertEqual(truncate_or_pad(UpperCamelCase_ , self.block_size , 0 ) , UpperCamelCase_ )
def _lowerCamelCase ( self ) -> List[Any]:
__lowercase : List[Any] = '''It was the year of Our Lord one thousand seven hundred and
seventy-five.\n\nSpiritual revelations were conceded to England at that
favoured period, as at this.'''
__lowercase ,__lowercase : Optional[Any] = process_story(UpperCamelCase_ )
self.assertEqual(UpperCamelCase_ , [] )
def _lowerCamelCase ( self ) -> Optional[Any]:
__lowercase : Optional[int] = ''''''
__lowercase ,__lowercase : Any = process_story(UpperCamelCase_ )
self.assertEqual(UpperCamelCase_ , [] )
self.assertEqual(UpperCamelCase_ , [] )
def _lowerCamelCase ( self ) -> Dict:
__lowercase : List[str] = (
'''It was the year of Our Lord one thousand seven hundred and '''
'''seventy-five\n\nSpiritual revelations were conceded to England '''
'''at that favoured period, as at this.\n@highlight\n\nIt was the best of times'''
)
__lowercase ,__lowercase : int = process_story(UpperCamelCase_ )
__lowercase : Union[str, Any] = [
'''It was the year of Our Lord one thousand seven hundred and seventy-five.''',
'''Spiritual revelations were conceded to England at that favoured period, as at this.''',
]
self.assertEqual(UpperCamelCase_ , UpperCamelCase_ )
__lowercase : List[str] = ['''It was the best of times.''']
self.assertEqual(UpperCamelCase_ , UpperCamelCase_ )
def _lowerCamelCase ( self ) -> Tuple:
__lowercase : Union[str, Any] = torch.tensor([1, 2, 3, 4] )
__lowercase : Union[str, Any] = torch.tensor([1, 1, 1, 1] )
np.testing.assert_array_equal(build_mask(UpperCamelCase_ , 0 ).numpy() , expected.numpy() )
def _lowerCamelCase ( self ) -> List[str]:
__lowercase : Optional[Any] = torch.tensor([1, 2, 3, 4, 23, 23, 23] )
__lowercase : Any = torch.tensor([1, 1, 1, 1, 0, 0, 0] )
np.testing.assert_array_equal(build_mask(UpperCamelCase_ , 23 ).numpy() , expected.numpy() )
def _lowerCamelCase ( self ) -> Optional[int]:
__lowercase : Tuple = torch.tensor([8, 2, 3, 4, 1, 1, 1] )
__lowercase : str = torch.tensor([1, 1, 1, 1, 0, 0, 0] )
np.testing.assert_array_equal(build_mask(UpperCamelCase_ , 1 ).numpy() , expected.numpy() )
def _lowerCamelCase ( self ) -> Dict:
__lowercase : List[Any] = 1_01
__lowercase : Union[str, Any] = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_01, 5, 6], [1, 1_01, 3, 4, 1_01, 6]] )
__lowercase : Optional[Any] = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] )
__lowercase : Optional[int] = compute_token_type_ids(UpperCamelCase_ , UpperCamelCase_ )
np.testing.assert_array_equal(UpperCamelCase_ , UpperCamelCase_ )
| 523 | 1 |
import logging
import os
from typing import List, TextIO, Union
from conllu import parse_incr
from utils_ner import InputExample, Split, TokenClassificationTask
SCREAMING_SNAKE_CASE__ : List[Any] = logging.getLogger(__name__)
class lowerCamelCase_ ( lowerCamelCase ):
def __init__( self , __lowerCAmelCase=-1 ):
"""simple docstring"""
# in NER datasets, the last column is usually reserved for NER label
__magic_name__ :int = label_idx
def A ( self , __lowerCAmelCase , __lowerCAmelCase ):
"""simple docstring"""
if isinstance(__lowerCAmelCase , __lowerCAmelCase ):
__magic_name__ :Dict = mode.value
__magic_name__ :List[Any] = os.path.join(__lowerCAmelCase , F'''{mode}.txt''' )
__magic_name__ :List[str] = 1
__magic_name__ :Tuple = []
with open(__lowerCAmelCase , encoding='''utf-8''' ) as f:
__magic_name__ :Tuple = []
__magic_name__ :int = []
for line in f:
if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n":
if words:
examples.append(InputExample(guid=F'''{mode}-{guid_index}''' , words=__lowerCAmelCase , labels=__lowerCAmelCase ) )
guid_index += 1
__magic_name__ :str = []
__magic_name__ :Tuple = []
else:
__magic_name__ :Optional[Any] = line.split(''' ''' )
words.append(splits[0] )
if len(__lowerCAmelCase ) > 1:
labels.append(splits[self.label_idx].replace('''\n''' , '''''' ) )
else:
# Examples could have no label for mode = "test"
labels.append('''O''' )
if words:
examples.append(InputExample(guid=F'''{mode}-{guid_index}''' , words=__lowerCAmelCase , labels=__lowerCAmelCase ) )
return examples
def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ):
"""simple docstring"""
__magic_name__ :str = 0
for line in test_input_reader:
if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n":
writer.write(__lowerCAmelCase )
if not preds_list[example_id]:
example_id += 1
elif preds_list[example_id]:
__magic_name__ :Dict = line.split()[0] + ''' ''' + preds_list[example_id].pop(0 ) + '''\n'''
writer.write(__lowerCAmelCase )
else:
logger.warning('''Maximum sequence length exceeded: No prediction for \'%s\'.''' , line.split()[0] )
def A ( self , __lowerCAmelCase ):
"""simple docstring"""
if path:
with open(__lowerCAmelCase , '''r''' ) as f:
__magic_name__ :str = f.read().splitlines()
if "O" not in labels:
__magic_name__ :Optional[int] = ['''O'''] + labels
return labels
else:
return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
class lowerCamelCase_ ( lowerCamelCase ):
def __init__( self ):
"""simple docstring"""
# in CONLL2003 dataset chunk column is second-to-last
super().__init__(label_idx=-2 )
def A ( self , __lowerCAmelCase ):
"""simple docstring"""
if path:
with open(__lowerCAmelCase , '''r''' ) as f:
__magic_name__ :Optional[Any] = f.read().splitlines()
if "O" not in labels:
__magic_name__ :Optional[Any] = ['''O'''] + labels
return labels
else:
return [
"O",
"B-ADVP",
"B-INTJ",
"B-LST",
"B-PRT",
"B-NP",
"B-SBAR",
"B-VP",
"B-ADJP",
"B-CONJP",
"B-PP",
"I-ADVP",
"I-INTJ",
"I-LST",
"I-PRT",
"I-NP",
"I-SBAR",
"I-VP",
"I-ADJP",
"I-CONJP",
"I-PP",
]
class lowerCamelCase_ ( lowerCamelCase ):
def A ( self , __lowerCAmelCase , __lowerCAmelCase ):
"""simple docstring"""
if isinstance(__lowerCAmelCase , __lowerCAmelCase ):
__magic_name__ :Optional[Any] = mode.value
__magic_name__ :Optional[Any] = os.path.join(__lowerCAmelCase , F'''{mode}.txt''' )
__magic_name__ :str = 1
__magic_name__ :Tuple = []
with open(__lowerCAmelCase , encoding='''utf-8''' ) as f:
for sentence in parse_incr(__lowerCAmelCase ):
__magic_name__ :Tuple = []
__magic_name__ :Any = []
for token in sentence:
words.append(token['''form'''] )
labels.append(token['''upos'''] )
assert len(__lowerCAmelCase ) == len(__lowerCAmelCase )
if words:
examples.append(InputExample(guid=F'''{mode}-{guid_index}''' , words=__lowerCAmelCase , labels=__lowerCAmelCase ) )
guid_index += 1
return examples
def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ):
"""simple docstring"""
__magic_name__ :List[Any] = 0
for sentence in parse_incr(__lowerCAmelCase ):
__magic_name__ :Tuple = preds_list[example_id]
__magic_name__ :int = ''''''
for token in sentence:
out += F'''{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) '''
out += "\n"
writer.write(__lowerCAmelCase )
example_id += 1
def A ( self , __lowerCAmelCase ):
"""simple docstring"""
if path:
with open(__lowerCAmelCase , '''r''' ) as f:
return f.read().splitlines()
else:
return [
"ADJ",
"ADP",
"ADV",
"AUX",
"CCONJ",
"DET",
"INTJ",
"NOUN",
"NUM",
"PART",
"PRON",
"PROPN",
"PUNCT",
"SCONJ",
"SYM",
"VERB",
"X",
]
| 0 |
'''simple docstring'''
import importlib
import inspect
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_config_docstrings.py
_lowercase : Tuple = """src/transformers"""
# This is to make sure the transformers module imported is the one in the repo.
_lowercase : str = importlib.util.spec_from_file_location(
"""transformers""",
os.path.join(PATH_TO_TRANSFORMERS, """__init__.py"""),
submodule_search_locations=[PATH_TO_TRANSFORMERS],
)
_lowercase : Optional[Any] = spec.loader.load_module()
_lowercase : List[Any] = transformers.models.auto.configuration_auto.CONFIG_MAPPING
# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
_lowercase : List[Any] = re.compile("""\[(.+?)\]\((https://huggingface\.co/.+?)\)""")
_lowercase : List[str] = {
"""CLIPConfigMixin""",
"""DecisionTransformerConfigMixin""",
"""EncoderDecoderConfigMixin""",
"""RagConfigMixin""",
"""SpeechEncoderDecoderConfigMixin""",
"""VisionEncoderDecoderConfigMixin""",
"""VisionTextDualEncoderConfigMixin""",
}
def lowerCamelCase__ ( ):
'''simple docstring'''
UpperCAmelCase = []
for config_class in list(CONFIG_MAPPING.values() ):
UpperCAmelCase = False
# source code of `config_class`
UpperCAmelCase = inspect.getsource(A )
UpperCAmelCase = _re_checkpoint.findall(A )
for checkpoint in checkpoints:
# Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
# For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
UpperCAmelCase , UpperCAmelCase = checkpoint
# verify the checkpoint name corresponds to the checkpoint link
UpperCAmelCase = f"""https://huggingface.co/{ckpt_name}"""
if ckpt_link == ckpt_link_from_name:
UpperCAmelCase = True
break
UpperCAmelCase = config_class.__name__
if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
configs_without_checkpoint.append(A )
if len(A ) > 0:
UpperCAmelCase = '''\n'''.join(sorted(A ) )
raise ValueError(f"""The following configurations don't contain any valid checkpoint:\n{message}""" )
if __name__ == "__main__":
check_config_docstrings_have_checkpoints()
| 210 | 0 |
import argparse
import os
import torch
from transformers.utils import WEIGHTS_NAME
_a : int = ["""small""", """medium""", """large"""]
_a : Dict = """lm_head.decoder.weight"""
_a : List[str] = """lm_head.weight"""
def snake_case__ ( UpperCAmelCase : List[str] , UpperCAmelCase : str ):
lowerCAmelCase__ :List[Any] = torch.load(__SCREAMING_SNAKE_CASE )
lowerCAmelCase__ :List[Any] = d.pop(__SCREAMING_SNAKE_CASE )
os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE )
torch.save(__SCREAMING_SNAKE_CASE , os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) )
if __name__ == "__main__":
_a : Any = argparse.ArgumentParser()
parser.add_argument("""--dialogpt_path""", default=""".""", type=str)
_a : int = parser.parse_args()
for MODEL in DIALOGPT_MODELS:
_a : Union[str, Any] = os.path.join(args.dialogpt_path, f"""{MODEL}_ft.pkl""")
_a : Optional[Any] = f"""./DialoGPT-{MODEL}"""
convert_dialogpt_checkpoint(
checkpoint_path,
pytorch_dump_folder_path,
)
| 704 |
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 : Tuple = logging.get_logger(__name__)
_a : Optional[int] = {
"""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 _UpperCAmelCase ( _A ):
"""simple docstring"""
A = '''levit'''
def __init__( self , _lowerCAmelCase=224 , _lowerCAmelCase=3 , _lowerCAmelCase=3 , _lowerCAmelCase=2 , _lowerCAmelCase=1 , _lowerCAmelCase=16 , _lowerCAmelCase=[128, 256, 384] , _lowerCAmelCase=[4, 8, 12] , _lowerCAmelCase=[4, 4, 4] , _lowerCAmelCase=[16, 16, 16] , _lowerCAmelCase=0 , _lowerCAmelCase=[2, 2, 2] , _lowerCAmelCase=[2, 2, 2] , _lowerCAmelCase=0.02 , **_lowerCAmelCase , ):
'''simple docstring'''
super().__init__(**_lowerCAmelCase )
lowerCAmelCase__ :List[str] = image_size
lowerCAmelCase__ :Dict = num_channels
lowerCAmelCase__ :List[Any] = kernel_size
lowerCAmelCase__ :List[Any] = stride
lowerCAmelCase__ :Tuple = padding
lowerCAmelCase__ :str = hidden_sizes
lowerCAmelCase__ :Union[str, Any] = num_attention_heads
lowerCAmelCase__ :Optional[int] = depths
lowerCAmelCase__ :Union[str, Any] = key_dim
lowerCAmelCase__ :str = drop_path_rate
lowerCAmelCase__ :int = patch_size
lowerCAmelCase__ :Dict = attention_ratio
lowerCAmelCase__ :Dict = mlp_ratio
lowerCAmelCase__ :Optional[int] = initializer_range
lowerCAmelCase__ :Tuple = [
["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 _UpperCAmelCase ( _A ):
"""simple docstring"""
A = version.parse('''1.11''' )
@property
def snake_case_ ( self ):
'''simple docstring'''
return OrderedDict(
[
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
] )
@property
def snake_case_ ( self ):
'''simple docstring'''
return 1e-4
| 111 | 0 |
'''simple docstring'''
import unittest
from transformers.testing_utils import require_bsa
from transformers.utils import is_bsa_available
from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin
if is_bsa_available():
from transformers import MarkupLMFeatureExtractor
class __SCREAMING_SNAKE_CASE ( unittest.TestCase ):
def __init__( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] ):
'''simple docstring'''
lowercase : List[str] =parent
def lowerCamelCase_ ( self : List[Any] ):
'''simple docstring'''
return {}
def _lowerCAmelCase ( ) -> List[str]:
lowercase : int ='''<HTML>
<HEAD>
<TITLE>sample document</TITLE>
</HEAD>
<BODY BGCOLOR="FFFFFF">
<HR>
<a href="http://google.com">Goog</a>
<H1>This is one header</H1>
<H2>This is a another Header</H2>
<P>Travel from
<P>
<B>SFO to JFK</B>
<BR>
<B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B>
<HR>
<div style="color:#0000FF">
<h3>Traveler <b> name </b> is
<p> John Doe </p>
</div>'''
lowercase : Dict ='''
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
'''
return [html_string_a, html_string_a]
@require_bsa
class __SCREAMING_SNAKE_CASE ( lowercase__ , unittest.TestCase ):
lowerCamelCase_ = MarkupLMFeatureExtractor if is_bsa_available() else None
def lowerCamelCase_ ( self : List[Any] ):
'''simple docstring'''
lowercase : Tuple =MarkupLMFeatureExtractionTester(self )
@property
def lowerCamelCase_ ( self : int ):
'''simple docstring'''
return self.feature_extract_tester.prepare_feat_extract_dict()
def lowerCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
# Initialize feature_extractor
lowercase : Dict =self.feature_extraction_class()
# Test not batched input
lowercase : List[str] =get_html_strings()[0]
lowercase : str =feature_extractor(UpperCAmelCase__ )
# fmt: off
lowercase : Dict =[['''sample document''', '''Goog''', '''This is one header''', '''This is a another Header''', '''Travel from''', '''SFO to JFK''', '''on May 2, 2015 at 2:00 pm. For details go to confirm.com''', '''Traveler''', '''name''', '''is''', '''John Doe''']]
lowercase : Any =[['''/html/head/title''', '''/html/body/a''', '''/html/body/h1''', '''/html/body/h2''', '''/html/body/p''', '''/html/body/p/p/b[1]''', '''/html/body/p/p/b[2]/i''', '''/html/body/p/p/div/h3''', '''/html/body/p/p/div/h3/b''', '''/html/body/p/p/div/h3''', '''/html/body/p/p/div/h3/p''']]
# fmt: on
self.assertEqual(encoding.nodes , UpperCAmelCase__ )
self.assertEqual(encoding.xpaths , UpperCAmelCase__ )
# Test batched
lowercase : int =get_html_strings()
lowercase : Union[str, Any] =feature_extractor(UpperCAmelCase__ )
# fmt: off
lowercase : Dict =expected_nodes + [['''My First Heading''', '''My first paragraph.''']]
lowercase : List[str] =expected_xpaths + [['''/html/body/h1''', '''/html/body/p''']]
self.assertEqual(len(encoding.nodes ) , 2 )
self.assertEqual(len(encoding.xpaths ) , 2 )
self.assertEqual(encoding.nodes , UpperCAmelCase__ )
self.assertEqual(encoding.xpaths , UpperCAmelCase__ )
| 92 |
"""simple docstring"""
def lowercase (_snake_case ) -> int:
'''simple docstring'''
__UpperCamelCase = len(_snake_case )
__UpperCamelCase = len(matrix[0] )
__UpperCamelCase = min(_snake_case ,_snake_case )
for row in range(_snake_case ):
# Check if diagonal element is not zero
if matrix[row][row] != 0:
# Eliminate all the elements below the diagonal
for col in range(row + 1 ,_snake_case ):
__UpperCamelCase = matrix[col][row] / matrix[row][row]
for i in range(_snake_case ,_snake_case ):
matrix[col][i] -= multiplier * matrix[row][i]
else:
# Find a non-zero diagonal element to swap rows
__UpperCamelCase = True
for i in range(row + 1 ,_snake_case ):
if matrix[i][row] != 0:
__UpperCamelCase , __UpperCamelCase = matrix[i], matrix[row]
__UpperCamelCase = False
break
if reduce:
rank -= 1
for i in range(_snake_case ):
__UpperCamelCase = matrix[i][rank]
# Reduce the row pointer by one to stay on the same row
row -= 1
return rank
if __name__ == "__main__":
import doctest
doctest.testmod() | 505 | 0 |
from arguments import InitializationArguments
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
# Configuration
UpperCamelCase_ = HfArgumentParser(InitializationArguments)
UpperCamelCase_ = parser.parse_args()
# Load codeparrot tokenizer trained for Python code tokenization
UpperCamelCase_ = AutoTokenizer.from_pretrained(args.tokenizer_name)
# Config: "scale_attn_by_layer_idx" and "reorder_and_upcast_attn" are Mistral stability tweaks
UpperCamelCase_ = {
"vocab_size": len(tokenizer),
"scale_attn_by_inverse_layer_idx": True,
"reorder_and_upcast_attn": True,
}
# Load model config (GPT-2 large in this case)
UpperCamelCase_ = AutoConfig.from_pretrained(args.config_name, **config_kwargs)
# Initialize new model with config
UpperCamelCase_ = AutoModelForCausalLM.from_config(config)
# Save model to the hub
model.save_pretrained(args.model_name, push_to_hub=args.push_to_hub)
| 721 |
import warnings
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
UpperCamelCase_ = logging.get_logger(__name__)
UpperCamelCase_ = {
"nvidia/segformer-b0-finetuned-ade-512-512": (
"https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json"
),
# See all SegFormer models at https://huggingface.co/models?filter=segformer
}
class a ( __UpperCAmelCase ):
lowercase_ : Union[str, Any] = 'segformer'
def __init__( self : List[str] , snake_case__ : Any=3 , snake_case__ : int=4 , snake_case__ : Tuple=[2, 2, 2, 2] , snake_case__ : Optional[int]=[8, 4, 2, 1] , snake_case__ : Union[str, Any]=[32, 64, 160, 256] , snake_case__ : str=[7, 3, 3, 3] , snake_case__ : List[Any]=[4, 2, 2, 2] , snake_case__ : Tuple=[1, 2, 5, 8] , snake_case__ : List[str]=[4, 4, 4, 4] , snake_case__ : Optional[Any]="gelu" , snake_case__ : Optional[Any]=0.0 , snake_case__ : Any=0.0 , snake_case__ : str=0.1 , snake_case__ : List[Any]=0.0_2 , snake_case__ : Any=0.1 , snake_case__ : List[Any]=1E-6 , snake_case__ : Any=256 , snake_case__ : Optional[Any]=255 , **snake_case__ : Union[str, Any] , ):
"""simple docstring"""
super().__init__(**snake_case__ )
if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
warnings.warn(
"Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be"
" removed, as the behaviour will default to that of reshape_last_stage = True." , snake_case__ , )
__lowerCAmelCase = num_channels
__lowerCAmelCase = num_encoder_blocks
__lowerCAmelCase = depths
__lowerCAmelCase = sr_ratios
__lowerCAmelCase = hidden_sizes
__lowerCAmelCase = patch_sizes
__lowerCAmelCase = strides
__lowerCAmelCase = mlp_ratios
__lowerCAmelCase = num_attention_heads
__lowerCAmelCase = hidden_act
__lowerCAmelCase = hidden_dropout_prob
__lowerCAmelCase = attention_probs_dropout_prob
__lowerCAmelCase = classifier_dropout_prob
__lowerCAmelCase = initializer_range
__lowerCAmelCase = drop_path_rate
__lowerCAmelCase = layer_norm_eps
__lowerCAmelCase = decoder_hidden_size
__lowerCAmelCase = kwargs.get("reshape_last_stage" , snake_case__ )
__lowerCAmelCase = semantic_loss_ignore_index
class a ( __UpperCAmelCase ):
lowercase_ : List[str] = version.parse('1.11' )
@property
def UpperCAmelCase__ ( self : Any ):
"""simple docstring"""
return OrderedDict(
[
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
] )
@property
def UpperCAmelCase__ ( self : Union[str, Any] ):
"""simple docstring"""
return 1E-4
@property
def UpperCAmelCase__ ( self : Optional[Any] ):
"""simple docstring"""
return 12
| 376 | 0 |
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 DeformableDetrImageProcessor
class _snake_case ( unittest.TestCase ):
def __init__( self , a , a=7 , a=3 , a=30 , a=400 , a=True , a=None , a=True , a=[0.5, 0.5, 0.5] , a=[0.5, 0.5, 0.5] , a=True , a=1 / 255 , a=True , ) -> Dict:
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
SCREAMING_SNAKE_CASE = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333}
SCREAMING_SNAKE_CASE = parent
SCREAMING_SNAKE_CASE = batch_size
SCREAMING_SNAKE_CASE = num_channels
SCREAMING_SNAKE_CASE = min_resolution
SCREAMING_SNAKE_CASE = max_resolution
SCREAMING_SNAKE_CASE = do_resize
SCREAMING_SNAKE_CASE = size
SCREAMING_SNAKE_CASE = do_normalize
SCREAMING_SNAKE_CASE = image_mean
SCREAMING_SNAKE_CASE = image_std
SCREAMING_SNAKE_CASE = do_rescale
SCREAMING_SNAKE_CASE = rescale_factor
SCREAMING_SNAKE_CASE = do_pad
def SCREAMING_SNAKE_CASE__ ( self) -> Dict:
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) -> List[Any]:
if not batched:
SCREAMING_SNAKE_CASE = image_inputs[0]
if isinstance(a , Image.Image):
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image.size
else:
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image.shape[1], image.shape[2]
if w < h:
SCREAMING_SNAKE_CASE = int(self.size['shortest_edge'] * h / w)
SCREAMING_SNAKE_CASE = self.size['shortest_edge']
elif w > h:
SCREAMING_SNAKE_CASE = self.size['shortest_edge']
SCREAMING_SNAKE_CASE = int(self.size['shortest_edge'] * w / h)
else:
SCREAMING_SNAKE_CASE = self.size['shortest_edge']
SCREAMING_SNAKE_CASE = self.size['shortest_edge']
else:
SCREAMING_SNAKE_CASE = []
for image in image_inputs:
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.get_expected_values([image])
expected_values.append((expected_height, expected_width))
SCREAMING_SNAKE_CASE = max(a , key=lambda a: item[0])[0]
SCREAMING_SNAKE_CASE = max(a , key=lambda a: item[1])[1]
return expected_height, expected_width
@require_torch
@require_vision
class _snake_case ( A__ , unittest.TestCase ):
_lowercase : int = DeformableDetrImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]:
SCREAMING_SNAKE_CASE = DeformableDetrImageProcessingTester(self)
@property
def SCREAMING_SNAKE_CASE__ ( self) -> Tuple:
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE__ ( self) -> Tuple:
SCREAMING_SNAKE_CASE = 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) -> List[str]:
SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333})
self.assertEqual(image_processor.do_pad , a)
SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(
self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=a)
self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84})
self.assertEqual(image_processor.do_pad , a)
def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]:
pass
def SCREAMING_SNAKE_CASE__ ( self) -> Tuple:
# Initialize image_processing
SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=a)
for image in image_inputs:
self.assertIsInstance(a , Image.Image)
# Test not batched input
SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 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
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a , batched=a)
SCREAMING_SNAKE_CASE = 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) -> Any:
# Initialize image_processing
SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
SCREAMING_SNAKE_CASE = 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
SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 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
SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt').pixel_values
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 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]:
# Initialize image_processing
SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
SCREAMING_SNAKE_CASE = 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
SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors='pt').pixel_values
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 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
SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt').pixel_values
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 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) -> Any:
# prepare image and target
SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r') as f:
SCREAMING_SNAKE_CASE = json.loads(f.read())
SCREAMING_SNAKE_CASE = {'image_id': 3_9769, 'annotations': target}
# encode them
SCREAMING_SNAKE_CASE = DeformableDetrImageProcessor()
SCREAMING_SNAKE_CASE = image_processing(images=a , annotations=a , return_tensors='pt')
# verify pixel values
SCREAMING_SNAKE_CASE = torch.Size([1, 3, 800, 1066])
self.assertEqual(encoding['pixel_values'].shape , a)
SCREAMING_SNAKE_CASE = torch.tensor([0.27_96, 0.31_38, 0.34_81])
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , a , atol=1E-4))
# verify area
SCREAMING_SNAKE_CASE = torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38])
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , a))
# verify boxes
SCREAMING_SNAKE_CASE = torch.Size([6, 4])
self.assertEqual(encoding['labels'][0]['boxes'].shape , a)
SCREAMING_SNAKE_CASE = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15])
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , a , atol=1E-3))
# verify image_id
SCREAMING_SNAKE_CASE = torch.tensor([3_9769])
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , a))
# verify is_crowd
SCREAMING_SNAKE_CASE = torch.tensor([0, 0, 0, 0, 0, 0])
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , a))
# verify class_labels
SCREAMING_SNAKE_CASE = torch.tensor([75, 75, 63, 65, 17, 17])
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , a))
# verify orig_size
SCREAMING_SNAKE_CASE = torch.tensor([480, 640])
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , a))
# verify size
SCREAMING_SNAKE_CASE = torch.tensor([800, 1066])
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , a))
@slow
def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]:
# prepare image, target and masks_path
SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r') as f:
SCREAMING_SNAKE_CASE = json.loads(f.read())
SCREAMING_SNAKE_CASE = {'file_name': '000000039769.png', 'image_id': 3_9769, 'segments_info': target}
SCREAMING_SNAKE_CASE = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic')
# encode them
SCREAMING_SNAKE_CASE = DeformableDetrImageProcessor(format='coco_panoptic')
SCREAMING_SNAKE_CASE = image_processing(images=a , annotations=a , masks_path=a , return_tensors='pt')
# verify pixel values
SCREAMING_SNAKE_CASE = torch.Size([1, 3, 800, 1066])
self.assertEqual(encoding['pixel_values'].shape , a)
SCREAMING_SNAKE_CASE = torch.tensor([0.27_96, 0.31_38, 0.34_81])
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , a , atol=1E-4))
# verify area
SCREAMING_SNAKE_CASE = torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47])
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , a))
# verify boxes
SCREAMING_SNAKE_CASE = torch.Size([6, 4])
self.assertEqual(encoding['labels'][0]['boxes'].shape , a)
SCREAMING_SNAKE_CASE = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25])
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , a , atol=1E-3))
# verify image_id
SCREAMING_SNAKE_CASE = torch.tensor([3_9769])
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , a))
# verify is_crowd
SCREAMING_SNAKE_CASE = torch.tensor([0, 0, 0, 0, 0, 0])
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , a))
# verify class_labels
SCREAMING_SNAKE_CASE = torch.tensor([17, 17, 63, 75, 75, 93])
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , a))
# verify masks
SCREAMING_SNAKE_CASE = 82_2873
self.assertEqual(encoding['labels'][0]['masks'].sum().item() , a)
# verify orig_size
SCREAMING_SNAKE_CASE = torch.tensor([480, 640])
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , a))
# verify size
SCREAMING_SNAKE_CASE = torch.tensor([800, 1066])
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , a))
| 73 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available
__A : Optional[int] = {
"configuration_longt5": ["LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "LongT5Config", "LongT5OnnxConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : Optional[Any] = [
"LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST",
"LongT5EncoderModel",
"LongT5ForConditionalGeneration",
"LongT5Model",
"LongT5PreTrainedModel",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : Optional[Any] = [
"FlaxLongT5ForConditionalGeneration",
"FlaxLongT5Model",
"FlaxLongT5PreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_longta import (
LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST,
LongTaEncoderModel,
LongTaForConditionalGeneration,
LongTaModel,
LongTaPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_longta import (
FlaxLongTaForConditionalGeneration,
FlaxLongTaModel,
FlaxLongTaPreTrainedModel,
)
else:
import sys
__A : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 602 | 0 |
import gc
import unittest
import numpy as np
import torch
from diffusers import StableDiffusionKDiffusionPipeline
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
enable_full_determinism()
@slow
@require_torch_gpu
class a ( unittest.TestCase ):
def UpperCAmelCase__ ( self : Tuple ):
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase__ ( self : Dict ):
"""simple docstring"""
__lowerCAmelCase = StableDiffusionKDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4" )
__lowerCAmelCase = sd_pipe.to(snake_case__ )
sd_pipe.set_progress_bar_config(disable=snake_case__ )
sd_pipe.set_scheduler("sample_euler" )
__lowerCAmelCase = "A painting of a squirrel eating a burger"
__lowerCAmelCase = torch.manual_seed(0 )
__lowerCAmelCase = sd_pipe([prompt] , generator=snake_case__ , guidance_scale=9.0 , num_inference_steps=20 , output_type="np" )
__lowerCAmelCase = output.images
__lowerCAmelCase = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
__lowerCAmelCase = np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase__ ( self : Dict ):
"""simple docstring"""
__lowerCAmelCase = StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" )
__lowerCAmelCase = sd_pipe.to(snake_case__ )
sd_pipe.set_progress_bar_config(disable=snake_case__ )
sd_pipe.set_scheduler("sample_euler" )
__lowerCAmelCase = "A painting of a squirrel eating a burger"
__lowerCAmelCase = torch.manual_seed(0 )
__lowerCAmelCase = sd_pipe([prompt] , generator=snake_case__ , guidance_scale=9.0 , num_inference_steps=20 , output_type="np" )
__lowerCAmelCase = output.images
__lowerCAmelCase = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
__lowerCAmelCase = np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1
def UpperCAmelCase__ ( self : str ):
"""simple docstring"""
__lowerCAmelCase = StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" )
__lowerCAmelCase = sd_pipe.to(snake_case__ )
sd_pipe.set_progress_bar_config(disable=snake_case__ )
sd_pipe.set_scheduler("sample_dpmpp_2m" )
__lowerCAmelCase = "A painting of a squirrel eating a burger"
__lowerCAmelCase = torch.manual_seed(0 )
__lowerCAmelCase = sd_pipe(
[prompt] , generator=snake_case__ , guidance_scale=7.5 , num_inference_steps=15 , output_type="np" , use_karras_sigmas=snake_case__ , )
__lowerCAmelCase = output.images
__lowerCAmelCase = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
__lowerCAmelCase = np.array(
[0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
| 376 |
import unittest
from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
UpperCamelCase_ = get_tests_dir("fixtures/spiece.model")
@require_sentencepiece
@require_tokenizers
class a ( __UpperCAmelCase , unittest.TestCase ):
lowercase_ : Union[str, Any] = DebertaVaTokenizer
lowercase_ : List[str] = DebertaVaTokenizerFast
lowercase_ : str = True
lowercase_ : List[Any] = True
def UpperCAmelCase__ ( self : Optional[Any] ):
"""simple docstring"""
super().setUp()
# We have a SentencePiece fixture for testing
__lowerCAmelCase = DebertaVaTokenizer(snake_case__ , unk_token="<unk>" )
tokenizer.save_pretrained(self.tmpdirname )
def UpperCAmelCase__ ( self : str , snake_case__ : Dict ):
"""simple docstring"""
__lowerCAmelCase = "this is a test"
__lowerCAmelCase = "this is a test"
return input_text, output_text
def UpperCAmelCase__ ( self : int ):
"""simple docstring"""
__lowerCAmelCase = "<pad>"
__lowerCAmelCase = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(snake_case__ ) , snake_case__ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(snake_case__ ) , snake_case__ )
def UpperCAmelCase__ ( self : Any ):
"""simple docstring"""
__lowerCAmelCase = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<pad>" )
self.assertEqual(vocab_keys[1] , "<unk>" )
self.assertEqual(vocab_keys[-1] , "[PAD]" )
self.assertEqual(len(snake_case__ ) , 30_001 )
def UpperCAmelCase__ ( self : Tuple ):
"""simple docstring"""
self.assertEqual(self.get_tokenizer().vocab_size , 30_000 )
def UpperCAmelCase__ ( self : List[str] ):
"""simple docstring"""
__lowerCAmelCase = " \tHeLLo!how \n Are yoU? "
__lowerCAmelCase = ["▁hello", "!", "how", "▁are", "▁you", "?"]
# fmt: on
__lowerCAmelCase = DebertaVaTokenizer(snake_case__ , do_lower_case=snake_case__ )
__lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = DebertaVaTokenizerFast(snake_case__ , do_lower_case=snake_case__ )
__lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
self.assertListEqual(snake_case__ , snake_case__ )
@unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." )
def UpperCAmelCase__ ( self : Union[str, Any] ):
"""simple docstring"""
pass
@unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." )
def UpperCAmelCase__ ( self : List[str] ):
"""simple docstring"""
pass
def UpperCAmelCase__ ( self : Any ):
"""simple docstring"""
__lowerCAmelCase = "I was born in 92000, and this is falsé."
__lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ]
# fmt: on
__lowerCAmelCase = DebertaVaTokenizer(snake_case__ , split_by_punct=snake_case__ )
__lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = DebertaVaTokenizerFast(snake_case__ , split_by_punct=snake_case__ )
__lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
self.assertListEqual(snake_case__ , snake_case__ )
def UpperCAmelCase__ ( self : Tuple ):
"""simple docstring"""
__lowerCAmelCase = "I was born in 92000, and this is falsé."
__lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ]
# fmt: on
__lowerCAmelCase = DebertaVaTokenizer(snake_case__ , do_lower_case=snake_case__ , split_by_punct=snake_case__ )
__lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = DebertaVaTokenizerFast(snake_case__ , do_lower_case=snake_case__ , split_by_punct=snake_case__ )
__lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
self.assertListEqual(snake_case__ , snake_case__ )
def UpperCAmelCase__ ( self : Optional[int] ):
"""simple docstring"""
__lowerCAmelCase = "I was born in 92000, and this is falsé."
__lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ]
# fmt: on
__lowerCAmelCase = DebertaVaTokenizer(snake_case__ , do_lower_case=snake_case__ , split_by_punct=snake_case__ )
__lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = DebertaVaTokenizerFast(snake_case__ , do_lower_case=snake_case__ , split_by_punct=snake_case__ )
__lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
self.assertListEqual(snake_case__ , snake_case__ )
def UpperCAmelCase__ ( self : int ):
"""simple docstring"""
__lowerCAmelCase = "I was born in 92000, and this is falsé."
__lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ]
# fmt: on
__lowerCAmelCase = DebertaVaTokenizer(snake_case__ , do_lower_case=snake_case__ , split_by_punct=snake_case__ )
__lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = DebertaVaTokenizerFast(snake_case__ , do_lower_case=snake_case__ , split_by_punct=snake_case__ )
__lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
self.assertListEqual(snake_case__ , snake_case__ )
def UpperCAmelCase__ ( self : Tuple ):
"""simple docstring"""
__lowerCAmelCase = " \tHeLLo!how \n Are yoU? "
__lowerCAmelCase = ["▁", "<unk>", "e", "<unk>", "o", "!", "how", "▁", "<unk>", "re", "▁yo", "<unk>", "?"]
# fmt: on
__lowerCAmelCase = DebertaVaTokenizer(snake_case__ , do_lower_case=snake_case__ , split_by_punct=snake_case__ )
__lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = DebertaVaTokenizerFast(snake_case__ , do_lower_case=snake_case__ , split_by_punct=snake_case__ )
__lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
self.assertListEqual(snake_case__ , snake_case__ )
def UpperCAmelCase__ ( self : Optional[int] ):
"""simple docstring"""
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = self.get_rust_tokenizer()
__lowerCAmelCase = "I was born in 92000, and this is falsé."
__lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
__lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ )
__lowerCAmelCase = rust_tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = self.get_rust_tokenizer()
__lowerCAmelCase = tokenizer.encode(snake_case__ )
__lowerCAmelCase = rust_tokenizer.encode(snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
def UpperCAmelCase__ ( self : Optional[int] ):
"""simple docstring"""
__lowerCAmelCase = "This is a test"
__lowerCAmelCase = [13, 1, 4_398, 25, 21, 1_289]
__lowerCAmelCase = ["▁", "T", "his", "▁is", "▁a", "▁test"]
__lowerCAmelCase = ["▁", "<unk>", "his", "▁is", "▁a", "▁test"]
__lowerCAmelCase = DebertaVaTokenizer(snake_case__ , keep_accents=snake_case__ )
__lowerCAmelCase = DebertaVaTokenizerFast(snake_case__ , keep_accents=snake_case__ )
__lowerCAmelCase = tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = tokenizer.tokenize(snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = tokenizer.convert_ids_to_tokens(snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = rust_tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = rust_tokenizer.tokenize(snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
# fmt: off
__lowerCAmelCase = "I was born in 92000, and this is falsé."
__lowerCAmelCase = [13, 1, 23, 386, 19, 561, 3_050, 15, 17, 48, 25, 8_256, 18, 1, 9]
__lowerCAmelCase = ["▁", "I", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", ".", ]
__lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ]
# fmt: on
__lowerCAmelCase = tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = tokenizer.tokenize(snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = tokenizer.convert_ids_to_tokens(snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = rust_tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = rust_tokenizer.tokenize(snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
def UpperCAmelCase__ ( self : Any ):
"""simple docstring"""
__lowerCAmelCase = DebertaVaTokenizer(snake_case__ )
__lowerCAmelCase = tokenizer.encode("sequence builders" )
__lowerCAmelCase = tokenizer.encode("multi-sequence build" )
__lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(snake_case__ )
__lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(snake_case__ , snake_case__ )
self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , snake_case__ )
self.assertEqual(
[tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , snake_case__ , )
@slow
def UpperCAmelCase__ ( self : Optional[int] ):
"""simple docstring"""
__lowerCAmelCase = {"input_ids": [[1, 39_867, 36, 19_390, 486, 27, 35_052, 81_436, 18, 60_685, 1_225, 7, 35_052, 81_436, 18, 9_367, 16_899, 18, 15_937, 53, 594, 773, 18, 16_287, 30_465, 36, 15_937, 6, 41_139, 38, 36_979, 60_763, 191, 6, 34_132, 99, 6, 50_538, 390, 43_230, 6, 34_132, 2_779, 20_850, 14, 699, 1_072, 1_194, 36, 382, 10_901, 53, 7, 699, 1_072, 2_084, 36, 20_422, 630, 53, 19, 105, 3_049, 1_896, 1_053, 16_899, 1_506, 11, 37_978, 4_243, 7, 1_237, 31_869, 200, 16_566, 654, 6, 35_052, 81_436, 7, 55_630, 13_593, 4, 2], [1, 26, 15_011, 13, 667, 8, 1_053, 18, 23_611, 1_237, 72_356, 12_820, 34, 104_134, 1_209, 35, 13_313, 6_627, 21, 202, 347, 7, 164, 2_399, 11, 46, 4_485, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 1_232, 2_864, 15_785, 14_951, 105, 5, 8_581, 1_250, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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]], "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=snake_case__ , model_name="microsoft/deberta-v2-xlarge" , revision="ad6e42c1532ddf3a15c39246b63f5559d558b670" , )
| 376 | 1 |
from ... import PretrainedConfig
_A : Any = {
"""sijunhe/nezha-cn-base""": """https://huggingface.co/sijunhe/nezha-cn-base/resolve/main/config.json""",
}
class __snake_case ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowerCamelCase__ : str = NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP
lowerCamelCase__ : Optional[Any] = """nezha"""
def __init__( self , A_=2_11_28 , A_=7_68 , A_=12 , A_=12 , A_=30_72 , A_="gelu" , A_=0.1 , A_=0.1 , A_=5_12 , A_=64 , A_=2 , A_=0.02 , A_=1E-12 , A_=0.1 , A_=0 , A_=2 , A_=3 , A_=True , **A_ , ):
'''simple docstring'''
super().__init__(pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , **A_ )
SCREAMING_SNAKE_CASE__ = vocab_size
SCREAMING_SNAKE_CASE__ = hidden_size
SCREAMING_SNAKE_CASE__ = num_hidden_layers
SCREAMING_SNAKE_CASE__ = num_attention_heads
SCREAMING_SNAKE_CASE__ = hidden_act
SCREAMING_SNAKE_CASE__ = intermediate_size
SCREAMING_SNAKE_CASE__ = hidden_dropout_prob
SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE__ = max_position_embeddings
SCREAMING_SNAKE_CASE__ = max_relative_position
SCREAMING_SNAKE_CASE__ = type_vocab_size
SCREAMING_SNAKE_CASE__ = initializer_range
SCREAMING_SNAKE_CASE__ = layer_norm_eps
SCREAMING_SNAKE_CASE__ = classifier_dropout
SCREAMING_SNAKE_CASE__ = use_cache
| 100 |
from abc import ABC, abstractmethod
from argparse import ArgumentParser
class __magic_name__ ( _a):
@staticmethod
@abstractmethod
def _UpperCAmelCase ( __SCREAMING_SNAKE_CASE : ArgumentParser ):
raise NotImplementedError()
@abstractmethod
def _UpperCAmelCase ( self : List[Any] ):
raise NotImplementedError()
| 333 | 0 |
def lowerCamelCase__ ( __lowerCAmelCase : str ):
"""simple docstring"""
lowerCAmelCase_ = [int(SCREAMING_SNAKE_CASE_ ) for i in ip_va_address.split("." ) if i.isdigit()]
return len(SCREAMING_SNAKE_CASE_ ) == 4 and all(0 <= int(SCREAMING_SNAKE_CASE_ ) <= 254 for octet in octets )
if __name__ == "__main__":
_A : List[Any] = input().strip()
_A : Union[str, Any] = "valid" if is_ip_va_address_valid(ip) else "invalid"
print(f"""{ip} is a {valid_or_invalid} IP v4 address.""")
| 700 |
from collections.abc import Iterable
from typing import Any
class _lowerCAmelCase :
def __init__( self , _UpperCamelCase = None ) -> str:
lowerCAmelCase_ = value
lowerCAmelCase_ = None # Added in order to delete a node easier
lowerCAmelCase_ = None
lowerCAmelCase_ = None
def __repr__( self ) -> str:
from pprint import pformat
if self.left is None and self.right is None:
return str(self.value )
return pformat({f"""{self.value}""": (self.left, self.right)} , indent=1 )
class _lowerCAmelCase :
def __init__( self , _UpperCamelCase = None ) -> Union[str, Any]:
lowerCAmelCase_ = root
def __str__( self ) -> str:
return str(self.root )
def __a ( self , _UpperCamelCase , _UpperCamelCase ) -> None:
if new_children is not None: # reset its kids
lowerCAmelCase_ = node.parent
if node.parent is not None: # reset its parent
if self.is_right(_UpperCamelCase ): # If it is the right children
lowerCAmelCase_ = new_children
else:
lowerCAmelCase_ = new_children
else:
lowerCAmelCase_ = new_children
def __a ( self , _UpperCamelCase ) -> bool:
if node.parent and node.parent.right:
return node == node.parent.right
return False
def __a ( self ) -> bool:
return self.root is None
def __a ( self , _UpperCamelCase ) -> None:
lowerCAmelCase_ = Node(_UpperCamelCase ) # create a new Node
if self.empty(): # if Tree is empty
lowerCAmelCase_ = new_node # set its root
else: # Tree is not empty
lowerCAmelCase_ = self.root # from root
if parent_node is None:
return
while True: # While we don't get to a leaf
if value < parent_node.value: # We go left
if parent_node.left is None:
lowerCAmelCase_ = new_node # We insert the new node in a leaf
break
else:
lowerCAmelCase_ = parent_node.left
else:
if parent_node.right is None:
lowerCAmelCase_ = new_node
break
else:
lowerCAmelCase_ = parent_node.right
lowerCAmelCase_ = parent_node
def __a ( self , *_UpperCamelCase ) -> None:
for value in values:
self.__insert(_UpperCamelCase )
def __a ( self , _UpperCamelCase ) -> Node | None:
if self.empty():
raise IndexError("Warning: Tree is empty! please use another." )
else:
lowerCAmelCase_ = self.root
# use lazy evaluation here to avoid NoneType Attribute error
while node is not None and node.value is not value:
lowerCAmelCase_ = node.left if value < node.value else node.right
return node
def __a ( self , _UpperCamelCase = None ) -> Node | None:
if node is None:
if self.root is None:
return None
lowerCAmelCase_ = self.root
if not self.empty():
while node.right is not None:
lowerCAmelCase_ = node.right
return node
def __a ( self , _UpperCamelCase = None ) -> Node | None:
if node is None:
lowerCAmelCase_ = self.root
if self.root is None:
return None
if not self.empty():
lowerCAmelCase_ = self.root
while node.left is not None:
lowerCAmelCase_ = node.left
return node
def __a ( self , _UpperCamelCase ) -> None:
lowerCAmelCase_ = self.search(_UpperCamelCase ) # Look for the node with that label
if node is not None:
if node.left is None and node.right is None: # If it has no children
self.__reassign_nodes(_UpperCamelCase , _UpperCamelCase )
elif node.left is None: # Has only right children
self.__reassign_nodes(_UpperCamelCase , node.right )
elif node.right is None: # Has only left children
self.__reassign_nodes(_UpperCamelCase , node.left )
else:
lowerCAmelCase_ = self.get_max(
node.left ) # Gets the max value of the left branch
self.remove(tmp_node.value ) # type: ignore
lowerCAmelCase_ = (
tmp_node.value # type: ignore
) # Assigns the value to the node to delete and keep tree structure
def __a ( self , _UpperCamelCase ) -> Iterable:
if node is not None:
yield node # Preorder Traversal
yield from self.preorder_traverse(node.left )
yield from self.preorder_traverse(node.right )
def __a ( self , _UpperCamelCase=None ) -> Any:
if traversal_function is None:
return self.preorder_traverse(self.root )
else:
return traversal_function(self.root )
def __a ( self , _UpperCamelCase , _UpperCamelCase ) -> None:
if node:
self.inorder(_UpperCamelCase , node.left )
arr.append(node.value )
self.inorder(_UpperCamelCase , node.right )
def __a ( self , _UpperCamelCase , _UpperCamelCase ) -> int:
lowerCAmelCase_ = []
self.inorder(_UpperCamelCase , _UpperCamelCase ) # append all values to list using inorder traversal
return arr[k - 1]
def lowerCamelCase__ ( __lowerCAmelCase : Node | None ):
"""simple docstring"""
lowerCAmelCase_ = []
if curr_node is not None:
lowerCAmelCase_ = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node]
return node_list
def lowerCamelCase__ ( ):
"""simple docstring"""
lowerCAmelCase_ = (8, 3, 6, 1, 10, 14, 13, 4, 7)
lowerCAmelCase_ = BinarySearchTree()
for i in testlist:
t.insert(__lowerCAmelCase )
# Prints all the elements of the list in order traversal
print(__lowerCAmelCase )
if t.search(6 ) is not None:
print("The value 6 exists" )
else:
print("The value 6 doesn't exist" )
if t.search(-1 ) is not None:
print("The value -1 exists" )
else:
print("The value -1 doesn't exist" )
if not t.empty():
print("Max Value: " , t.get_max().value ) # type: ignore
print("Min Value: " , t.get_min().value ) # type: ignore
for i in testlist:
t.remove(__lowerCAmelCase )
print(__lowerCAmelCase )
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
| 279 | 0 |
def UpperCamelCase_( _A :list[list] )-> list[list]:
UpperCamelCase__ = current_set.copy()
for row_index, row in enumerate(_A ):
UpperCamelCase__ = row[0]
for column_index, column in enumerate(_A ):
if magnitude == 0:
UpperCamelCase__ = column
continue
UpperCamelCase__ = column / magnitude
# Subtract to cancel term
UpperCamelCase__ = current_set[0]
UpperCamelCase__ = [first_row]
UpperCamelCase__ = current_set[1::]
for row in current_set:
UpperCamelCase__ = []
# If first term is 0, it is already in form we want, so we preserve it
if row[0] == 0:
final_set.append(_A )
continue
for column_index in range(len(_A ) ):
temp_row.append(first_row[column_index] - row[column_index] )
final_set.append(_A )
# Create next recursion iteration set
if len(final_set[0] ) != 3:
UpperCamelCase__ = final_set[0]
UpperCamelCase__ = []
UpperCamelCase__ = []
for row in final_set[1::]:
current_first_column.append(row[0] )
next_iteration.append(row[1::] )
UpperCamelCase__ = simplify(_A )
for i in range(len(_A ) ):
resultant[i].insert(0 , current_first_column[i] )
resultant.insert(0 , _A )
UpperCamelCase__ = resultant
return final_set
def UpperCamelCase_( _A :list[list] )-> list:
if len(_A ) == 0:
raise IndexError("solve_simultaneous() requires n lists of length n+1" )
UpperCamelCase__ = len(_A ) + 1
if any(len(_A ) != _length for item in equations ):
raise IndexError("solve_simultaneous() requires n lists of length n+1" )
for row in equations:
if any(not isinstance(_A , (int, float) ) for column in row ):
raise ValueError("solve_simultaneous() requires lists of integers" )
if len(_A ) == 1:
return [equations[0][-1] / equations[0][0]]
UpperCamelCase__ = equations.copy()
if any(0 in row for row in data_set ):
UpperCamelCase__ = data_set.copy()
UpperCamelCase__ = []
for row_index, row in enumerate(_A ):
if 0 not in row:
UpperCamelCase__ = data_set.pop(_A )
break
if not full_row:
raise ValueError("solve_simultaneous() requires at least 1 full equation" )
data_set.insert(0 , _A )
UpperCamelCase__ = data_set.copy()
UpperCamelCase__ = simplify(_A )
UpperCamelCase__ = simplified[::-1]
UpperCamelCase__ = []
for row in simplified:
UpperCamelCase__ = row[-1]
if not solutions:
if row[-2] == 0:
solutions.append(0 )
continue
solutions.append(current_solution / row[-2] )
continue
UpperCamelCase__ = row.copy()[: len(_A ) - 1 :]
while temp_row[0] == 0:
temp_row.pop(0 )
if len(_A ) == 0:
solutions.append(0 )
continue
UpperCamelCase__ = temp_row[1::]
UpperCamelCase__ = temp_row[::-1]
for column_index, column in enumerate(_A ):
current_solution -= column * solutions[column_index]
solutions.append(_A )
UpperCamelCase__ = []
for item in solutions:
final.append(float(round(_A , 5 ) ) )
return final[::-1]
if __name__ == "__main__":
import doctest
doctest.testmod()
__UpperCamelCase = [
[2, 1, 1, 1, 1, 4],
[1, 2, 1, 1, 1, 5],
[1, 1, 2, 1, 1, 6],
[1, 1, 1, 2, 1, 7],
[1, 1, 1, 1, 2, 8],
]
print(solve_simultaneous(eq))
print(solve_simultaneous([[4, 2]]))
| 551 |
from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline
else:
from .pipeline_kandinsky import KandinskyPipeline
from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline
from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline
from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput
from .text_encoder import MultilingualCLIP
| 551 | 1 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
__lowerCAmelCase = {
'''configuration_owlvit''': [
'''OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''OwlViTConfig''',
'''OwlViTOnnxConfig''',
'''OwlViTTextConfig''',
'''OwlViTVisionConfig''',
],
'''processing_owlvit''': ['''OwlViTProcessor'''],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase = ['''OwlViTFeatureExtractor''']
__lowerCAmelCase = ['''OwlViTImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase = [
'''OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''OwlViTModel''',
'''OwlViTPreTrainedModel''',
'''OwlViTTextModel''',
'''OwlViTVisionModel''',
'''OwlViTForObjectDetection''',
]
if TYPE_CHECKING:
from .configuration_owlvit import (
OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP,
OwlViTConfig,
OwlViTOnnxConfig,
OwlViTTextConfig,
OwlViTVisionConfig,
)
from .processing_owlvit import OwlViTProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_owlvit import OwlViTFeatureExtractor
from .image_processing_owlvit import OwlViTImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_owlvit import (
OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
OwlViTForObjectDetection,
OwlViTModel,
OwlViTPreTrainedModel,
OwlViTTextModel,
OwlViTVisionModel,
)
else:
import sys
__lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 335 |
import os
import re
import shutil
from argparse import ArgumentParser, Namespace
from datasets.commands import BaseDatasetsCLICommand
from datasets.utils.logging import get_logger
__lowerCAmelCase = '''<<<<<<< This should probably be modified because it mentions: '''
__lowerCAmelCase = '''=======
>>>>>>>
'''
__lowerCAmelCase = [
'''TextEncoderConfig''',
'''ByteTextEncoder''',
'''SubwordTextEncoder''',
'''encoder_config''',
'''maybe_build_from_corpus''',
'''manual_dir''',
]
__lowerCAmelCase = [
# (pattern, replacement)
# Order is important here for some replacements
(r'''tfds\.core''', r'''datasets'''),
(r'''tf\.io\.gfile\.GFile''', r'''open'''),
(r'''tf\.([\w\d]+)''', r'''datasets.Value(\'\1\')'''),
(r'''tfds\.features\.Text\(\)''', r'''datasets.Value(\'string\')'''),
(r'''tfds\.features\.Text\(''', r'''datasets.Value(\'string\'),'''),
(r'''features\s*=\s*tfds.features.FeaturesDict\(''', r'''features=datasets.Features('''),
(r'''tfds\.features\.FeaturesDict\(''', r'''dict('''),
(r'''The TensorFlow Datasets Authors''', r'''The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'''),
(r'''tfds\.''', r'''datasets.'''),
(r'''dl_manager\.manual_dir''', r'''self.config.data_dir'''),
(r'''self\.builder_config''', r'''self.config'''),
]
def snake_case_ ( snake_case ) -> Union[str, Any]:
return ConvertCommand(args.tfds_path , args.datasets_directory )
class __a ( __UpperCamelCase ):
@staticmethod
def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase__ ) -> Optional[int]:
'''simple docstring'''
lowercase__: List[str] = parser.add_parser(
'convert' , help='Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.' , )
train_parser.add_argument(
'--tfds_path' , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.' , )
train_parser.add_argument(
'--datasets_directory' , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='Path to the HuggingFace Datasets folder.' )
train_parser.set_defaults(func=lowerCAmelCase__ )
def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , *lowerCAmelCase__ ) -> Any:
'''simple docstring'''
lowercase__: Tuple = get_logger('datasets-cli/converting' )
lowercase__: Any = tfds_path
lowercase__: str = datasets_directory
def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]:
'''simple docstring'''
if os.path.isdir(self._tfds_path ):
lowercase__: int = os.path.abspath(self._tfds_path )
elif os.path.isfile(self._tfds_path ):
lowercase__: Optional[int] = os.path.dirname(self._tfds_path )
else:
raise ValueError('--tfds_path is neither a directory nor a file. Please check path.' )
lowercase__: str = os.path.abspath(self._datasets_directory )
self._logger.info(F'Converting datasets from {abs_tfds_path} to {abs_datasets_path}' )
lowercase__: Union[str, Any] = []
lowercase__: List[str] = []
lowercase__: str = {}
if os.path.isdir(self._tfds_path ):
lowercase__: List[Any] = os.listdir(lowerCAmelCase__ )
else:
lowercase__: Optional[Any] = [os.path.basename(self._tfds_path )]
for f_name in file_names:
self._logger.info(F'Looking at file {f_name}' )
lowercase__: List[str] = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ )
lowercase__: int = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ )
if not os.path.isfile(lowerCAmelCase__ ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name:
self._logger.info('Skipping file' )
continue
with open(lowerCAmelCase__ , encoding='utf-8' ) as f:
lowercase__: Any = f.readlines()
lowercase__: List[str] = []
lowercase__: List[Any] = False
lowercase__: Any = False
lowercase__: Dict = []
for line in lines:
lowercase__: Tuple = line
# Convert imports
if "import tensorflow.compat.v2 as tf" in out_line:
continue
elif "@tfds.core" in out_line:
continue
elif "builder=self" in out_line:
continue
elif "import tensorflow_datasets.public_api as tfds" in out_line:
lowercase__: List[Any] = 'import datasets\n'
elif "import tensorflow" in out_line:
# order is important here
lowercase__: Optional[Any] = ''
continue
elif "from absl import logging" in out_line:
lowercase__: str = 'from datasets import logging\n'
elif "getLogger" in out_line:
lowercase__: Dict = out_line.replace('getLogger' , 'get_logger' )
elif any(expression in out_line for expression in TO_HIGHLIGHT ):
lowercase__: Tuple = True
lowercase__: int = list(filter(lambda lowerCAmelCase__ : e in out_line , lowerCAmelCase__ ) )
out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(lowerCAmelCase__ ) + '\n' )
out_lines.append(lowerCAmelCase__ )
out_lines.append(lowerCAmelCase__ )
continue
else:
for pattern, replacement in TO_CONVERT:
lowercase__: Any = re.sub(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
# Take care of saving utilities (to later move them together with main script)
if "tensorflow_datasets" in out_line:
lowercase__: Tuple = re.match(R'from\stensorflow_datasets.*import\s([^\.\r\n]+)' , lowerCAmelCase__ )
tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(',' ) )
lowercase__: Dict = 'from . import ' + match.group(1 )
# Check we have not forget anything
if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line:
raise ValueError(F'Error converting {out_line.strip()}' )
if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line:
lowercase__: List[str] = True
out_lines.append(lowerCAmelCase__ )
if is_builder or "wmt" in f_name:
# We create a new directory for each dataset
lowercase__: Dict = f_name.replace('.py' , '' )
lowercase__: Optional[Any] = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ )
lowercase__: Any = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ )
os.makedirs(lowerCAmelCase__ , exist_ok=lowerCAmelCase__ )
self._logger.info(F'Adding directory {output_dir}' )
imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} )
else:
# Utilities will be moved at the end
utils_files.append(lowerCAmelCase__ )
if needs_manual_update:
with_manual_update.append(lowerCAmelCase__ )
with open(lowerCAmelCase__ , 'w' , encoding='utf-8' ) as f:
f.writelines(lowerCAmelCase__ )
self._logger.info(F'Converted in {output_file}' )
for utils_file in utils_files:
try:
lowercase__: str = os.path.basename(lowerCAmelCase__ )
lowercase__: int = imports_to_builder_map[f_name.replace('.py' , '' )]
self._logger.info(F'Moving {dest_folder} to {utils_file}' )
shutil.copy(lowerCAmelCase__ , lowerCAmelCase__ )
except KeyError:
self._logger.error(F'Cannot find destination folder for {utils_file}. Please copy manually.' )
if with_manual_update:
for file_path in with_manual_update:
self._logger.warning(
F'You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.' )
| 335 | 1 |
UpperCAmelCase_ = """Alexander Joslin"""
import operator as op
from .stack import Stack
def SCREAMING_SNAKE_CASE_ ( _snake_case :str ) -> int:
_A = {'''*''': op.mul, '''/''': op.truediv, '''+''': op.add, '''-''': op.sub}
_A = Stack()
_A = Stack()
for i in equation:
if i.isdigit():
# RULE 1
operand_stack.push(int(_snake_case ) )
elif i in operators:
# RULE 2
operator_stack.push(_snake_case )
elif i == ")":
# RULE 4
_A = operator_stack.peek()
operator_stack.pop()
_A = operand_stack.peek()
operand_stack.pop()
_A = operand_stack.peek()
operand_stack.pop()
_A = operators[opr](_snake_case , _snake_case )
operand_stack.push(_snake_case )
# RULE 5
return operand_stack.peek()
if __name__ == "__main__":
UpperCAmelCase_ = """(5 + ((4 * 2) * (2 + 3)))"""
# answer = 45
print(f'{equation} = {dijkstras_two_stack_algorithm(equation)}')
| 2 |
import importlib.metadata
import warnings
from copy import deepcopy
from packaging import version
from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available
if is_bitsandbytes_available():
import bitsandbytes as bnb
import torch
import torch.nn as nn
from ..pytorch_utils import ConvaD
if is_accelerate_available():
from accelerate import init_empty_weights
from accelerate.utils import find_tied_parameters
_lowerCamelCase : Union[str, Any] = logging.get_logger(__name__)
def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None ) -> Dict:
"""simple docstring"""
if "." in tensor_name:
A__ = tensor_name.split('''.''' )
for split in splits[:-1]:
A__ = getattr(lowercase_ , lowercase_ )
if new_module is None:
raise ValueError(f"""{module} has no attribute {split}.""" )
A__ = new_module
A__ = splits[-1]
if tensor_name not in module._parameters and tensor_name not in module._buffers:
raise ValueError(f"""{module} does not have a parameter or a buffer named {tensor_name}.""" )
A__ = tensor_name in module._buffers
A__ = getattr(lowercase_ , lowercase_ )
if old_value.device == torch.device('''meta''' ) and device not in ["meta", torch.device('''meta''' )] and value is None:
raise ValueError(f"""{tensor_name} is on the meta device, we need a `value` to put in on {device}.""" )
A__ = False
A__ = False
if is_buffer or not is_bitsandbytes_available():
A__ = False
A__ = False
else:
A__ = hasattr(bnb.nn , '''Params4bit''' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit )
A__ = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams )
if is_abit or is_abit:
A__ = module._parameters[tensor_name]
if param.device.type != "cuda":
if value is None:
A__ = old_value.to(lowercase_ )
elif isinstance(lowercase_ , torch.Tensor ):
A__ = value.to('''cpu''' )
if value.dtype == torch.inta:
A__ = version.parse(importlib.metadata.version('''bitsandbytes''' ) ) > version.parse(
'''0.37.2''' )
if not is_abit_serializable:
raise ValueError(
'''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. '''
'''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.''' )
else:
A__ = torch.tensor(lowercase_ , device='''cpu''' )
# Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
# Since weights are saved in the correct "orientation", we skip transposing when loading.
if issubclass(module.source_cls , lowercase_ ) and fpaa_statistics is None:
A__ = new_value.T
A__ = old_value.__dict__
if is_abit:
A__ = bnb.nn.IntaParams(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ )
elif is_abit:
A__ = bnb.nn.Paramsabit(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ )
A__ = new_value
if fpaa_statistics is not None:
setattr(module.weight , '''SCB''' , fpaa_statistics.to(lowercase_ ) )
else:
if value is None:
A__ = old_value.to(lowercase_ )
elif isinstance(lowercase_ , torch.Tensor ):
A__ = value.to(lowercase_ )
else:
A__ = torch.tensor(lowercase_ , device=lowercase_ )
if is_buffer:
A__ = new_value
else:
A__ = nn.Parameter(lowercase_ , requires_grad=old_value.requires_grad )
A__ = new_value
def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=False ) -> Dict:
"""simple docstring"""
for name, module in model.named_children():
if current_key_name is None:
A__ = []
current_key_name.append(lowercase_ )
if (isinstance(lowercase_ , nn.Linear ) or isinstance(lowercase_ , lowercase_ )) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
if not any(key in '''.'''.join(lowercase_ ) for key in modules_to_not_convert ):
with init_empty_weights():
if isinstance(lowercase_ , lowercase_ ):
A__ , A__ = module.weight.shape
else:
A__ = module.in_features
A__ = module.out_features
if quantization_config.quantization_method() == "llm_int8":
A__ = bnb.nn.LinearabitLt(
lowercase_ , lowercase_ , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , )
A__ = True
else:
if (
quantization_config.llm_inta_skip_modules is not None
and name in quantization_config.llm_inta_skip_modules
):
pass
else:
A__ = bnb.nn.Linearabit(
lowercase_ , lowercase_ , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , )
A__ = True
# Store the module class in case we need to transpose the weight later
A__ = type(lowercase_ )
# Force requires grad to False to avoid unexpected errors
model._modules[name].requires_grad_(lowercase_ )
if len(list(module.children() ) ) > 0:
A__ , A__ = _replace_with_bnb_linear(
lowercase_ , lowercase_ , lowercase_ , lowercase_ , has_been_replaced=lowercase_ , )
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None ) -> Tuple:
"""simple docstring"""
A__ = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
A__ , A__ = _replace_with_bnb_linear(
lowercase_ , lowercase_ , lowercase_ , lowercase_ )
if not has_been_replaced:
logger.warning(
'''You are loading your model in 8bit or 4bit but no linear modules were found in your model.'''
''' Please double check your model architecture, or submit an issue on github if you think this is'''
''' a bug.''' )
return model
def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Dict:
"""simple docstring"""
warnings.warn(
'''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' , lowercase_ , )
return replace_with_bnb_linear(*lowercase_ , **lowercase_ )
def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Optional[Any]:
"""simple docstring"""
warnings.warn(
'''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' , lowercase_ , )
return set_module_quantized_tensor_to_device(*lowercase_ , **lowercase_ )
def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[str]:
"""simple docstring"""
A__ = deepcopy(lowercase_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
tied_model.tie_weights()
A__ = find_tied_parameters(lowercase_ )
# For compatibility with Accelerate < 0.18
if isinstance(lowercase_ , lowercase_ ):
A__ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
A__ = sum(lowercase_ , [] )
A__ = len(lowercase_ ) > 0
# Check if it is a base model
A__ = not hasattr(lowercase_ , model.base_model_prefix )
# Ignore this for base models (BertModel, GPT2Model, etc.)
if (not has_tied_params) and is_base_model:
return []
# otherwise they have an attached head
A__ = list(model.named_children() )
A__ = [list_modules[-1][0]]
# add last module together with tied weights
A__ = set(lowercase_ ) - set(lowercase_ )
A__ = list(set(lowercase_ ) ) + list(lowercase_ )
# remove ".weight" from the keys
A__ = ['''.weight''', '''.bias''']
A__ = []
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
A__ = name.replace(lowercase_ , '''''' )
filtered_module_names.append(lowercase_ )
return filtered_module_names
| 87 | 0 |
def lowerCamelCase__ ( UpperCamelCase__ : int ) -> int:
'''simple docstring'''
if a < 0:
raise ValueError('Input value must be a positive integer' )
elif isinstance(UpperCamelCase__ , UpperCamelCase__ ):
raise TypeError('Input value must be a \'int\' type' )
return bin(UpperCamelCase__ ).count('1' )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 541 |
from cva import destroyAllWindows, imread, imshow, waitKey
def lowerCamelCase__ ( UpperCamelCase__ : Optional[int] ) -> Optional[int]:
'''simple docstring'''
_snake_case , _snake_case = img.shape[0], img.shape[1]
# converting each pixel's color to its negative
for i in range(UpperCamelCase__ ):
for j in range(UpperCamelCase__ ):
_snake_case = [255, 255, 255] - img[i][j]
return img
if __name__ == "__main__":
# read original image
UpperCAmelCase_ = imread("""image_data/lena.jpg""", 1)
# convert to its negative
UpperCAmelCase_ = convert_to_negative(img)
# show result image
imshow("""negative of original image""", img)
waitKey(0)
destroyAllWindows()
| 541 | 1 |
import inspect
import unittest
from datasets import load_dataset
from packaging import version
from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import (
MODEL_MAPPING,
BeitForImageClassification,
BeitForMaskedImageModeling,
BeitForSemanticSegmentation,
BeitModel,
)
from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
import PIL
from PIL import Image
from transformers import BeitImageProcessor
class snake_case :
def __init__( self : Optional[int] , a_ : Any , a_ : List[str]=100 , a_ : Dict=13 , a_ : str=30 , a_ : str=2 , a_ : Any=3 , a_ : int=True , a_ : str=True , a_ : Tuple=32 , a_ : Optional[Any]=4 , a_ : Optional[int]=4 , a_ : List[Any]=37 , a_ : str="gelu" , a_ : str=0.1 , a_ : Dict=0.1 , a_ : Union[str, Any]=10 , a_ : int=0.02 , a_ : Optional[Any]=3 , a_ : Tuple=None , a_ : Optional[int]=[0, 1, 2, 3] , )-> List[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : int = parent
SCREAMING_SNAKE_CASE__ : int = 100
SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_size
SCREAMING_SNAKE_CASE__ : Any = image_size
SCREAMING_SNAKE_CASE__ : Optional[int] = patch_size
SCREAMING_SNAKE_CASE__ : str = num_channels
SCREAMING_SNAKE_CASE__ : List[Any] = is_training
SCREAMING_SNAKE_CASE__ : Tuple = use_labels
SCREAMING_SNAKE_CASE__ : Any = hidden_size
SCREAMING_SNAKE_CASE__ : int = num_hidden_layers
SCREAMING_SNAKE_CASE__ : Any = num_attention_heads
SCREAMING_SNAKE_CASE__ : str = intermediate_size
SCREAMING_SNAKE_CASE__ : str = hidden_act
SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob
SCREAMING_SNAKE_CASE__ : Tuple = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE__ : Dict = type_sequence_label_size
SCREAMING_SNAKE_CASE__ : List[str] = initializer_range
SCREAMING_SNAKE_CASE__ : str = scope
SCREAMING_SNAKE_CASE__ : List[Any] = out_indices
SCREAMING_SNAKE_CASE__ : Optional[int] = num_labels
# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
SCREAMING_SNAKE_CASE__ : Optional[Any] = (image_size // patch_size) ** 2
SCREAMING_SNAKE_CASE__ : Any = num_patches + 1
def __lowercase( self : List[str] )-> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
SCREAMING_SNAKE_CASE__ : Any = None
SCREAMING_SNAKE_CASE__ : int = None
if self.use_labels:
SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size )
SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
SCREAMING_SNAKE_CASE__ : int = self.get_config()
return config, pixel_values, labels, pixel_labels
def __lowercase( self : List[Any] )-> Union[str, Any]:
"""simple docstring"""
return BeitConfig(
vocab_size=self.vocab_size , 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 , out_indices=self.out_indices , )
def __lowercase( self : List[str] , a_ : str , a_ : Any , a_ : Tuple , a_ : Tuple )-> List[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : List[str] = BeitModel(config=a_ )
model.to(a_ )
model.eval()
SCREAMING_SNAKE_CASE__ : List[str] = model(a_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __lowercase( self : List[str] , a_ : List[str] , a_ : List[Any] , a_ : int , a_ : Optional[Any] )-> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : List[str] = BeitForMaskedImageModeling(config=a_ )
model.to(a_ )
model.eval()
SCREAMING_SNAKE_CASE__ : Dict = model(a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) )
def __lowercase( self : Any , a_ : Any , a_ : Optional[int] , a_ : str , a_ : Any )-> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : List[Any] = self.type_sequence_label_size
SCREAMING_SNAKE_CASE__ : Optional[Any] = BeitForImageClassification(a_ )
model.to(a_ )
model.eval()
SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
SCREAMING_SNAKE_CASE__ : Any = 1
SCREAMING_SNAKE_CASE__ : Optional[Any] = BeitForImageClassification(a_ )
model.to(a_ )
model.eval()
SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
SCREAMING_SNAKE_CASE__ : Dict = model(a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def __lowercase( self : Dict , a_ : Dict , a_ : Optional[int] , a_ : int , a_ : Optional[int] )-> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Optional[Any] = self.num_labels
SCREAMING_SNAKE_CASE__ : Any = BeitForSemanticSegmentation(a_ )
model.to(a_ )
model.eval()
SCREAMING_SNAKE_CASE__ : List[str] = model(a_ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) )
SCREAMING_SNAKE_CASE__ : int = model(a_ , labels=a_ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) )
def __lowercase( self : Optional[int] )-> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = config_and_inputs
SCREAMING_SNAKE_CASE__ : int = {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ):
lowercase_ = (
(BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
if is_torch_available()
else ()
)
lowercase_ = (
{
'feature-extraction': BeitModel,
'image-classification': BeitForImageClassification,
'image-segmentation': BeitForSemanticSegmentation,
}
if is_torch_available()
else {}
)
lowercase_ = False
lowercase_ = False
lowercase_ = False
def __lowercase( self : str )-> List[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Any = BeitModelTester(self )
SCREAMING_SNAKE_CASE__ : str = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 )
def __lowercase( self : Any )-> Dict:
"""simple docstring"""
self.config_tester.run_common_tests()
@unittest.skip(reason='BEiT does not use inputs_embeds' )
def __lowercase( self : Optional[Any] )-> Union[str, Any]:
"""simple docstring"""
pass
@require_torch_multi_gpu
@unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' )
def __lowercase( self : int )-> Optional[Any]:
"""simple docstring"""
pass
def __lowercase( self : int )-> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(a_ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
SCREAMING_SNAKE_CASE__ : Tuple = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(a_ , nn.Linear ) )
def __lowercase( self : int )-> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE__ : List[Any] = model_class(a_ )
SCREAMING_SNAKE_CASE__ : List[Any] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
SCREAMING_SNAKE_CASE__ : Optional[Any] = [*signature.parameters.keys()]
SCREAMING_SNAKE_CASE__ : Union[str, Any] = ['pixel_values']
self.assertListEqual(arg_names[:1] , a_ )
def __lowercase( self : str )-> List[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a_ )
def __lowercase( self : Optional[Any] )-> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*a_ )
def __lowercase( self : int )-> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*a_ )
def __lowercase( self : Optional[int] )-> Tuple:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*a_ )
def __lowercase( self : int )-> str:
"""simple docstring"""
if not self.model_tester.is_training:
return
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
SCREAMING_SNAKE_CASE__ : str = True
for model_class in self.all_model_classes:
# we don't test BeitForMaskedImageModeling
if model_class in [*get_values(a_ ), BeitForMaskedImageModeling]:
continue
SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(a_ )
model.to(a_ )
model.train()
SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ )
SCREAMING_SNAKE_CASE__ : Dict = model(**a_ ).loss
loss.backward()
def __lowercase( self : Optional[Any] )-> Tuple:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
if not self.model_tester.is_training:
return
SCREAMING_SNAKE_CASE__ : str = False
SCREAMING_SNAKE_CASE__ : Tuple = True
for model_class in self.all_model_classes:
# we don't test BeitForMaskedImageModeling
if (
model_class in [*get_values(a_ ), BeitForMaskedImageModeling]
or not model_class.supports_gradient_checkpointing
):
continue
SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ )
model.gradient_checkpointing_enable()
model.to(a_ )
model.train()
SCREAMING_SNAKE_CASE__ : Any = self._prepare_for_class(a_ , a_ , return_labels=a_ )
SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss
loss.backward()
def __lowercase( self : List[Any] )-> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common()
SCREAMING_SNAKE_CASE__ : List[str] = _config_zero_init(a_ )
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE__ : Any = model_class(config=a_ )
for name, param in model.named_parameters():
# we skip lambda parameters as these require special initial values
# determined by config.layer_scale_init_value
if "lambda" in name:
continue
if param.requires_grad:
self.assertIn(
((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , )
@slow
def __lowercase( self : Any )-> str:
"""simple docstring"""
for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE__ : List[str] = BeitModel.from_pretrained(a_ )
self.assertIsNotNone(a_ )
def _a ( ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_torch
@require_vision
class snake_case ( unittest.TestCase ):
@cached_property
def __lowercase( self : str )-> List[Any]:
"""simple docstring"""
return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None
@slow
def __lowercase( self : Optional[int] )-> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Union[str, Any] = BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ).to(a_ )
SCREAMING_SNAKE_CASE__ : int = self.default_image_processor
SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img()
SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ).pixel_values.to(a_ )
# prepare bool_masked_pos
SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.ones((1, 196) , dtype=torch.bool ).to(a_ )
# forward pass
with torch.no_grad():
SCREAMING_SNAKE_CASE__ : str = model(pixel_values=a_ , bool_masked_pos=a_ )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits
# verify the logits
SCREAMING_SNAKE_CASE__ : Tuple = torch.Size((1, 196, 8192) )
self.assertEqual(logits.shape , a_ )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor(
[[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]] ).to(a_ )
self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] , a_ , atol=1e-2 ) )
@slow
def __lowercase( self : List[Any] )-> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Union[str, Any] = BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ).to(a_ )
SCREAMING_SNAKE_CASE__ : List[str] = self.default_image_processor
SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img()
SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_processor(images=a_ , return_tensors='pt' ).to(a_ )
# forward pass
with torch.no_grad():
SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ )
SCREAMING_SNAKE_CASE__ : List[str] = outputs.logits
# verify the logits
SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Size((1, 1000) )
self.assertEqual(logits.shape , a_ )
SCREAMING_SNAKE_CASE__ : int = torch.tensor([-1.2385, -1.0987, -1.0108] ).to(a_ )
self.assertTrue(torch.allclose(logits[0, :3] , a_ , atol=1e-4 ) )
SCREAMING_SNAKE_CASE__ : Optional[Any] = 281
self.assertEqual(logits.argmax(-1 ).item() , a_ )
@slow
def __lowercase( self : List[str] )-> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Any = BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ).to(
a_ )
SCREAMING_SNAKE_CASE__ : Tuple = self.default_image_processor
SCREAMING_SNAKE_CASE__ : Dict = prepare_img()
SCREAMING_SNAKE_CASE__ : Tuple = image_processor(images=a_ , return_tensors='pt' ).to(a_ )
# forward pass
with torch.no_grad():
SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**a_ )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits
# verify the logits
SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 2_1841) )
self.assertEqual(logits.shape , a_ )
SCREAMING_SNAKE_CASE__ : str = torch.tensor([1.6881, -0.2787, 0.5901] ).to(a_ )
self.assertTrue(torch.allclose(logits[0, :3] , a_ , atol=1e-4 ) )
SCREAMING_SNAKE_CASE__ : List[Any] = 2396
self.assertEqual(logits.argmax(-1 ).item() , a_ )
@slow
def __lowercase( self : Tuple )-> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Any = BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.to(a_ )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = BeitImageProcessor(do_resize=a_ , size=640 , do_center_crop=a_ )
SCREAMING_SNAKE_CASE__ : List[str] = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
SCREAMING_SNAKE_CASE__ : Optional[int] = Image.open(ds[0]['file'] )
SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(images=a_ , return_tensors='pt' ).to(a_ )
# forward pass
with torch.no_grad():
SCREAMING_SNAKE_CASE__ : str = model(**a_ )
SCREAMING_SNAKE_CASE__ : Optional[Any] = outputs.logits
# verify the logits
SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 150, 160, 160) )
self.assertEqual(logits.shape , a_ )
SCREAMING_SNAKE_CASE__ : str = version.parse(PIL.__version__ ) < version.parse('9.0.0' )
if is_pillow_less_than_a:
SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor(
[
[[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]],
[[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]],
[[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]],
] , device=a_ , )
else:
SCREAMING_SNAKE_CASE__ : Any = torch.tensor(
[
[[-4.8960, -2.3688, -3.0355], [-2.8478, -0.9836, -1.7418], [-2.9449, -1.3332, -2.1456]],
[[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]],
[[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]],
] , device=a_ , )
self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , a_ , atol=1e-4 ) )
@slow
def __lowercase( self : Union[str, Any] )-> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : str = BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.to(a_ )
SCREAMING_SNAKE_CASE__ : Optional[int] = BeitImageProcessor(do_resize=a_ , size=640 , do_center_crop=a_ )
SCREAMING_SNAKE_CASE__ : str = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
SCREAMING_SNAKE_CASE__ : Dict = Image.open(ds[0]['file'] )
SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(images=a_ , return_tensors='pt' ).to(a_ )
# forward pass
with torch.no_grad():
SCREAMING_SNAKE_CASE__ : Dict = model(**a_ )
SCREAMING_SNAKE_CASE__ : List[str] = outputs.logits.detach().cpu()
SCREAMING_SNAKE_CASE__ : int = image_processor.post_process_semantic_segmentation(outputs=a_ , target_sizes=[(500, 300)] )
SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size((500, 300) )
self.assertEqual(segmentation[0].shape , a_ )
SCREAMING_SNAKE_CASE__ : Dict = image_processor.post_process_semantic_segmentation(outputs=a_ )
SCREAMING_SNAKE_CASE__ : List[Any] = torch.Size((160, 160) )
self.assertEqual(segmentation[0].shape , a_ )
| 85 |
'''simple docstring'''
def UpperCAmelCase_ ( lowerCAmelCase_ , lowerCAmelCase_ ):
"""simple docstring"""
return [sentence[i : i + ngram_size] for i in range(len(lowerCAmelCase_ ) - ngram_size + 1 )]
if __name__ == "__main__":
from doctest import testmod
testmod()
| 310 | 0 |
'''simple docstring'''
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_snake_case : Tuple = logging.get_logger(__name__)
class _UpperCAmelCase ( _UpperCamelCase ):
"""simple docstring"""
a_ = """encoder-decoder"""
a_ = True
def __init__( self : Tuple , **lowerCAmelCase_ : Optional[Any] ) -> Optional[Any]:
super().__init__(**__UpperCamelCase )
assert (
"encoder" in kwargs and "decoder" in kwargs
), "Config has to be initialized with encoder and decoder config"
__lowerCAmelCase = kwargs.pop('encoder' )
__lowerCAmelCase = encoder_config.pop('model_type' )
__lowerCAmelCase = kwargs.pop('decoder' )
__lowerCAmelCase = decoder_config.pop('model_type' )
from ..auto.configuration_auto import AutoConfig
__lowerCAmelCase = AutoConfig.for_model(__UpperCamelCase , **__UpperCamelCase )
__lowerCAmelCase = AutoConfig.for_model(__UpperCamelCase , **__UpperCamelCase )
__lowerCAmelCase = True
@classmethod
def lowercase ( cls : Optional[int] , lowerCAmelCase_ : PretrainedConfig , lowerCAmelCase_ : PretrainedConfig , **lowerCAmelCase_ : str ) -> PretrainedConfig:
logger.info('Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config' )
__lowerCAmelCase = True
__lowerCAmelCase = True
return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__UpperCamelCase )
def lowercase ( self : Dict ) -> Any:
__lowerCAmelCase = copy.deepcopy(self.__dict__ )
__lowerCAmelCase = self.encoder.to_dict()
__lowerCAmelCase = self.decoder.to_dict()
__lowerCAmelCase = self.__class__.model_type
return output
| 707 |
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 _UpperCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : Dict , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Union[str, Any]=1_3 , lowerCAmelCase_ : List[str]=7 , lowerCAmelCase_ : Union[str, Any]=True , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : Union[str, Any]=True , lowerCAmelCase_ : List[Any]=9_9 , lowerCAmelCase_ : Tuple=3_2 , lowerCAmelCase_ : Any=5 , lowerCAmelCase_ : Any=4 , lowerCAmelCase_ : Dict=3_7 , lowerCAmelCase_ : Tuple="gelu" , lowerCAmelCase_ : List[Any]=0.1 , lowerCAmelCase_ : str=0.1 , lowerCAmelCase_ : str=5_1_2 , lowerCAmelCase_ : Dict=1_6 , lowerCAmelCase_ : Tuple=2 , lowerCAmelCase_ : Optional[int]=0.02 , lowerCAmelCase_ : Optional[int]=4 , ) -> List[Any]:
__lowerCAmelCase = parent
__lowerCAmelCase = batch_size
__lowerCAmelCase = seq_length
__lowerCAmelCase = is_training
__lowerCAmelCase = use_attention_mask
__lowerCAmelCase = use_token_type_ids
__lowerCAmelCase = use_labels
__lowerCAmelCase = vocab_size
__lowerCAmelCase = hidden_size
__lowerCAmelCase = num_hidden_layers
__lowerCAmelCase = num_attention_heads
__lowerCAmelCase = intermediate_size
__lowerCAmelCase = hidden_act
__lowerCAmelCase = hidden_dropout_prob
__lowerCAmelCase = attention_probs_dropout_prob
__lowerCAmelCase = max_position_embeddings
__lowerCAmelCase = type_vocab_size
__lowerCAmelCase = type_sequence_label_size
__lowerCAmelCase = initializer_range
__lowerCAmelCase = num_choices
def lowercase ( self : List[str] ) -> Optional[int]:
__lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__lowerCAmelCase = None
if self.use_attention_mask:
__lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] )
__lowerCAmelCase = None
if self.use_token_type_ids:
__lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
__lowerCAmelCase = 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=lowerCAmelCase_ , initializer_range=self.initializer_range , )
return config, input_ids, token_type_ids, attention_mask
def lowercase ( self : Dict ) -> Dict:
__lowerCAmelCase = self.prepare_config_and_inputs()
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = config_and_inputs
__lowerCAmelCase = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask}
return config, inputs_dict
def lowercase ( self : Tuple ) -> int:
__lowerCAmelCase = self.prepare_config_and_inputs()
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = config_and_inputs
__lowerCAmelCase = True
__lowerCAmelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
__lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 )
return (
config,
input_ids,
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 _UpperCAmelCase ( _UpperCamelCase , unittest.TestCase ):
"""simple docstring"""
a_ = True
a_ = (
(
FlaxRobertaPreLayerNormModel,
FlaxRobertaPreLayerNormForCausalLM,
FlaxRobertaPreLayerNormForMaskedLM,
FlaxRobertaPreLayerNormForSequenceClassification,
FlaxRobertaPreLayerNormForTokenClassification,
FlaxRobertaPreLayerNormForMultipleChoice,
FlaxRobertaPreLayerNormForQuestionAnswering,
)
if is_flax_available()
else ()
)
def lowercase ( self : Any ) -> Dict:
__lowerCAmelCase = FlaxRobertaPreLayerNormModelTester(self )
@slow
def lowercase ( self : Tuple ) -> List[str]:
for model_class_name in self.all_model_classes:
__lowerCAmelCase = model_class_name.from_pretrained('andreasmadsen/efficient_mlm_m0.40' , from_pt=lowerCAmelCase_ )
__lowerCAmelCase = model(np.ones((1, 1) ) )
self.assertIsNotNone(lowerCAmelCase_ )
@require_flax
class _UpperCAmelCase ( unittest.TestCase ):
"""simple docstring"""
@slow
def lowercase ( self : int ) -> int:
__lowerCAmelCase = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('andreasmadsen/efficient_mlm_m0.40' , from_pt=lowerCAmelCase_ )
__lowerCAmelCase = 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 )
__lowerCAmelCase = model(lowerCAmelCase_ )[0]
__lowerCAmelCase = [1, 1_1, 5_0_2_6_5]
self.assertEqual(list(output.shape ) , lowerCAmelCase_ )
# compare the actual values for a slice.
__lowerCAmelCase = np.array(
[[[40.48_80, 18.01_99, -5.23_67], [-1.88_77, -4.08_85, 10.70_85], [-2.26_13, -5.61_10, 7.26_65]]] , dtype=np.floataa )
self.assertTrue(np.allclose(output[:, :3, :3] , lowerCAmelCase_ , atol=1e-4 ) )
@slow
def lowercase ( self : Union[str, Any] ) -> Tuple:
__lowerCAmelCase = FlaxRobertaPreLayerNormModel.from_pretrained('andreasmadsen/efficient_mlm_m0.40' , from_pt=lowerCAmelCase_ )
__lowerCAmelCase = 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 )
__lowerCAmelCase = model(lowerCAmelCase_ )[0]
# compare the actual values for a slice.
__lowerCAmelCase = np.array(
[[[0.02_08, -0.03_56, 0.02_37], [-0.15_69, -0.04_11, -0.26_26], [0.18_79, 0.01_25, -0.00_89]]] , dtype=np.floataa )
self.assertTrue(np.allclose(output[:, :3, :3] , lowerCAmelCase_ , atol=1e-4 ) )
| 421 | 0 |
'''simple docstring'''
def _lowerCAmelCase (_lowercase ):
"""simple docstring"""
a__ = ""
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 _lowerCAmelCase (_lowercase ):
"""simple docstring"""
a__ = [chr(i + 65 ) for i in range(26 )]
# Remove duplicate characters from key
a__ = remove_duplicates(key.upper() )
a__ = len(_lowercase )
# First fill cipher with key characters
a__ = {alphabet[i]: char for i, char in enumerate(_lowercase )}
# Then map remaining characters in alphabet to
# the alphabet from the beginning
for i in range(len(_lowercase ) , 26 ):
a__ = alphabet[i - offset]
# Ensure we are not mapping letters to letters previously mapped
while char in key:
offset -= 1
a__ = alphabet[i - offset]
a__ = char
return cipher_alphabet
def _lowerCAmelCase (_lowercase , _lowercase ):
"""simple docstring"""
return "".join(cipher_map.get(_lowercase , _lowercase ) for ch in message.upper() )
def _lowerCAmelCase (_lowercase , _lowercase ):
"""simple docstring"""
a__ = {v: k for k, v in cipher_map.items()}
return "".join(rev_cipher_map.get(_lowercase , _lowercase ) for ch in message.upper() )
def _lowerCAmelCase ():
"""simple docstring"""
a__ = input("Enter message to encode or decode: " ).strip()
a__ = input("Enter keyword: " ).strip()
a__ = input("Encipher or decipher? E/D:" ).strip()[0].lower()
try:
a__ = {"e": encipher, "d": decipher}[option]
except KeyError:
raise KeyError("invalid input option" )
a__ = create_cipher_map(_lowercase )
print(func(_lowercase , _lowercase ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 331 |
'''simple docstring'''
from __future__ import annotations
import numpy as np
def _lowerCAmelCase (_lowercase ):
"""simple docstring"""
return np.maximum(0 , _lowercase )
if __name__ == "__main__":
print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
| 331 | 1 |
import shutil
import tempfile
import unittest
from unittest.mock import patch
from transformers import (
DefaultFlowCallback,
IntervalStrategy,
PrinterCallback,
ProgressCallback,
Trainer,
TrainerCallback,
TrainingArguments,
is_torch_available,
)
from transformers.testing_utils import require_torch
if is_torch_available():
from transformers.trainer import DEFAULT_CALLBACKS
from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel
class lowerCamelCase ( A_ ):
def __init__(self : int ) -> str:
snake_case = []
def UpperCAmelCase(self : Any , _A : int , _A : Optional[int] , _A : Dict , **_A : List[str] ) -> int:
self.events.append("on_init_end" )
def UpperCAmelCase(self : List[str] , _A : List[Any] , _A : List[Any] , _A : List[Any] , **_A : Optional[int] ) -> Tuple:
self.events.append("on_train_begin" )
def UpperCAmelCase(self : Union[str, Any] , _A : Any , _A : Tuple , _A : Dict , **_A : str ) -> Any:
self.events.append("on_train_end" )
def UpperCAmelCase(self : Dict , _A : Tuple , _A : Dict , _A : List[Any] , **_A : Tuple ) -> List[Any]:
self.events.append("on_epoch_begin" )
def UpperCAmelCase(self : Dict , _A : Dict , _A : Dict , _A : Optional[int] , **_A : Optional[int] ) -> Optional[int]:
self.events.append("on_epoch_end" )
def UpperCAmelCase(self : str , _A : Any , _A : Optional[int] , _A : List[Any] , **_A : List[Any] ) -> Optional[Any]:
self.events.append("on_step_begin" )
def UpperCAmelCase(self : int , _A : List[str] , _A : Union[str, Any] , _A : Optional[Any] , **_A : List[str] ) -> str:
self.events.append("on_step_end" )
def UpperCAmelCase(self : Optional[Any] , _A : Tuple , _A : Dict , _A : List[str] , **_A : List[Any] ) -> Dict:
self.events.append("on_evaluate" )
def UpperCAmelCase(self : Optional[int] , _A : Union[str, Any] , _A : Any , _A : str , **_A : str ) -> Dict:
self.events.append("on_predict" )
def UpperCAmelCase(self : int , _A : List[Any] , _A : Dict , _A : Optional[int] , **_A : Dict ) -> int:
self.events.append("on_save" )
def UpperCAmelCase(self : int , _A : str , _A : Union[str, Any] , _A : Tuple , **_A : Tuple ) -> int:
self.events.append("on_log" )
def UpperCAmelCase(self : List[Any] , _A : Tuple , _A : List[Any] , _A : int , **_A : Dict ) -> Tuple:
self.events.append("on_prediction_step" )
@require_torch
class lowerCamelCase ( unittest.TestCase ):
def UpperCAmelCase(self : List[str] ) -> Optional[Any]:
snake_case = tempfile.mkdtemp()
def UpperCAmelCase(self : int ) -> List[Any]:
shutil.rmtree(self.output_dir )
def UpperCAmelCase(self : Union[str, Any] , _A : List[str]=0 , _A : Any=0 , _A : Optional[int]=6_4 , _A : List[str]=6_4 , _A : int=None , _A : Union[str, Any]=False , **_A : Tuple ) -> List[Any]:
# disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure
# its set to False since the tests later on depend on its value.
snake_case = RegressionDataset(length=_A )
snake_case = RegressionDataset(length=_A )
snake_case = RegressionModelConfig(a=_A , b=_A )
snake_case = RegressionPreTrainedModel(_A )
snake_case = TrainingArguments(self.output_dir , disable_tqdm=_A , report_to=[] , **_A )
return Trainer(
_A , _A , train_dataset=_A , eval_dataset=_A , callbacks=_A , )
def UpperCAmelCase(self : Tuple , _A : Optional[Any] , _A : List[str] ) -> str:
self.assertEqual(len(_A ) , len(_A ) )
# Order doesn't matter
snake_case = sorted(_A , key=lambda _A : cb.__name__ if isinstance(_A , _A ) else cb.__class__.__name__ )
snake_case = sorted(_A , key=lambda _A : cb.__name__ if isinstance(_A , _A ) else cb.__class__.__name__ )
for cba, cba in zip(_A , _A ):
if isinstance(_A , _A ) and isinstance(_A , _A ):
self.assertEqual(_A , _A )
elif isinstance(_A , _A ) and not isinstance(_A , _A ):
self.assertEqual(_A , cba.__class__ )
elif not isinstance(_A , _A ) and isinstance(_A , _A ):
self.assertEqual(cba.__class__ , _A )
else:
self.assertEqual(_A , _A )
def UpperCAmelCase(self : Tuple , _A : str ) -> List[Any]:
snake_case = ["on_init_end", "on_train_begin"]
snake_case = 0
snake_case = len(trainer.get_eval_dataloader() )
snake_case = ["on_prediction_step"] * len(trainer.get_eval_dataloader() ) + ["on_log", "on_evaluate"]
for _ in range(trainer.state.num_train_epochs ):
expected_events.append("on_epoch_begin" )
for _ in range(_A ):
step += 1
expected_events += ["on_step_begin", "on_step_end"]
if step % trainer.args.logging_steps == 0:
expected_events.append("on_log" )
if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0:
expected_events += evaluation_events.copy()
if step % trainer.args.save_steps == 0:
expected_events.append("on_save" )
expected_events.append("on_epoch_end" )
if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH:
expected_events += evaluation_events.copy()
expected_events += ["on_log", "on_train_end"]
return expected_events
def UpperCAmelCase(self : Optional[Any] ) -> Optional[Any]:
snake_case = self.get_trainer()
snake_case = DEFAULT_CALLBACKS.copy() + [ProgressCallback]
self.check_callbacks_equality(trainer.callback_handler.callbacks , _A )
# Callbacks passed at init are added to the default callbacks
snake_case = self.get_trainer(callbacks=[MyTestTrainerCallback] )
expected_callbacks.append(_A )
self.check_callbacks_equality(trainer.callback_handler.callbacks , _A )
# TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
snake_case = self.get_trainer(disable_tqdm=_A )
snake_case = DEFAULT_CALLBACKS.copy() + [PrinterCallback]
self.check_callbacks_equality(trainer.callback_handler.callbacks , _A )
def UpperCAmelCase(self : Optional[int] ) -> Union[str, Any]:
snake_case = DEFAULT_CALLBACKS.copy() + [ProgressCallback]
snake_case = self.get_trainer()
# We can add, pop, or remove by class name
trainer.remove_callback(_A )
expected_callbacks.remove(_A )
self.check_callbacks_equality(trainer.callback_handler.callbacks , _A )
snake_case = self.get_trainer()
snake_case = trainer.pop_callback(_A )
self.assertEqual(cb.__class__ , _A )
self.check_callbacks_equality(trainer.callback_handler.callbacks , _A )
trainer.add_callback(_A )
expected_callbacks.insert(0 , _A )
self.check_callbacks_equality(trainer.callback_handler.callbacks , _A )
# We can also add, pop, or remove by instance
snake_case = self.get_trainer()
snake_case = trainer.callback_handler.callbacks[0]
trainer.remove_callback(_A )
expected_callbacks.remove(_A )
self.check_callbacks_equality(trainer.callback_handler.callbacks , _A )
snake_case = self.get_trainer()
snake_case = trainer.callback_handler.callbacks[0]
snake_case = trainer.pop_callback(_A )
self.assertEqual(_A , _A )
self.check_callbacks_equality(trainer.callback_handler.callbacks , _A )
trainer.add_callback(_A )
expected_callbacks.insert(0 , _A )
self.check_callbacks_equality(trainer.callback_handler.callbacks , _A )
def UpperCAmelCase(self : Tuple ) -> List[Any]:
import warnings
# XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested
warnings.simplefilter(action="ignore" , category=_A )
snake_case = self.get_trainer(callbacks=[MyTestTrainerCallback] )
trainer.train()
snake_case = trainer.callback_handler.callbacks[-2].events
self.assertEqual(_A , self.get_expected_events(_A ) )
# Independent log/save/eval
snake_case = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 )
trainer.train()
snake_case = trainer.callback_handler.callbacks[-2].events
self.assertEqual(_A , self.get_expected_events(_A ) )
snake_case = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 )
trainer.train()
snake_case = trainer.callback_handler.callbacks[-2].events
self.assertEqual(_A , self.get_expected_events(_A ) )
snake_case = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy="steps" )
trainer.train()
snake_case = trainer.callback_handler.callbacks[-2].events
self.assertEqual(_A , self.get_expected_events(_A ) )
snake_case = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy="epoch" )
trainer.train()
snake_case = trainer.callback_handler.callbacks[-2].events
self.assertEqual(_A , self.get_expected_events(_A ) )
# A bit of everything
snake_case = self.get_trainer(
callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=1_0 , eval_steps=5 , evaluation_strategy="steps" , )
trainer.train()
snake_case = trainer.callback_handler.callbacks[-2].events
self.assertEqual(_A , self.get_expected_events(_A ) )
# warning should be emitted for duplicated callbacks
with patch("transformers.trainer_callback.logger.warning" ) as warn_mock:
snake_case = self.get_trainer(
callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , )
assert str(_A ) in warn_mock.call_args[0][0]
| 721 |
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 lowerCamelCase ( A_ ):
UpperCAmelCase__ : Dict = "canine"
def __init__(self : List[Any] , _A : Union[str, Any]=7_6_8 , _A : Any=1_2 , _A : List[Any]=1_2 , _A : List[Any]=3_0_7_2 , _A : Dict="gelu" , _A : Optional[Any]=0.1 , _A : Tuple=0.1 , _A : str=1_6_3_8_4 , _A : Union[str, Any]=1_6 , _A : Any=0.02 , _A : List[str]=1E-12 , _A : Union[str, Any]=0 , _A : Dict=0Xe0_00 , _A : List[Any]=0Xe0_01 , _A : int=4 , _A : str=4 , _A : Optional[int]=8 , _A : Optional[Any]=1_6_3_8_4 , _A : Optional[Any]=1_2_8 , **_A : Union[str, Any] , ) -> Union[str, Any]:
super().__init__(pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , **_A )
snake_case = max_position_embeddings
snake_case = hidden_size
snake_case = num_hidden_layers
snake_case = num_attention_heads
snake_case = intermediate_size
snake_case = hidden_act
snake_case = hidden_dropout_prob
snake_case = attention_probs_dropout_prob
snake_case = initializer_range
snake_case = type_vocab_size
snake_case = layer_norm_eps
# Character config:
snake_case = downsampling_rate
snake_case = upsampling_kernel_size
snake_case = num_hash_functions
snake_case = num_hash_buckets
snake_case = local_transformer_stride
| 294 | 0 |
'''simple docstring'''
def a_ ( _lowerCAmelCase = 1000 ) -> int:
return sum(2 * a * ((a - 1) // 2) for a in range(3 ,n + 1 ) )
if __name__ == "__main__":
print(solution())
| 459 |
class A__ :
'''simple docstring'''
def __init__( self : Optional[int] , _SCREAMING_SNAKE_CASE : str = "" , _SCREAMING_SNAKE_CASE : bool = False ):
"""simple docstring"""
UpperCamelCase = {}
# A node will be a leaf if the tree contains its word
UpperCamelCase = is_leaf
UpperCamelCase = prefix
def _SCREAMING_SNAKE_CASE ( self : Optional[int] , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
UpperCamelCase = 0
for q, w in zip(self.prefix , _SCREAMING_SNAKE_CASE ):
if q != w:
break
x += 1
return self.prefix[:x], self.prefix[x:], word[x:]
def _SCREAMING_SNAKE_CASE ( self : Any , _SCREAMING_SNAKE_CASE : list[str] ):
"""simple docstring"""
for word in words:
self.insert(_SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
if self.prefix == word:
UpperCamelCase = True
# Case 2: The node has no edges that have a prefix to the word
# Solution: We create an edge from the current node to a new one
# containing the word
elif word[0] not in self.nodes:
UpperCamelCase = RadixNode(prefix=_SCREAMING_SNAKE_CASE , is_leaf=_SCREAMING_SNAKE_CASE )
else:
UpperCamelCase = self.nodes[word[0]]
UpperCamelCase , UpperCamelCase , UpperCamelCase = incoming_node.match(
_SCREAMING_SNAKE_CASE )
# Case 3: The node prefix is equal to the matching
# Solution: We insert remaining word on the next node
if remaining_prefix == "":
self.nodes[matching_string[0]].insert(_SCREAMING_SNAKE_CASE )
# Case 4: The word is greater equal to the matching
# Solution: Create a node in between both nodes, change
# prefixes and add the new node for the remaining word
else:
UpperCamelCase = remaining_prefix
UpperCamelCase = self.nodes[matching_string[0]]
UpperCamelCase = RadixNode(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
UpperCamelCase = aux_node
if remaining_word == "":
UpperCamelCase = True
else:
self.nodes[matching_string[0]].insert(_SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : Any , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
UpperCamelCase = self.nodes.get(word[0] , _SCREAMING_SNAKE_CASE )
if not incoming_node:
return False
else:
UpperCamelCase , UpperCamelCase , UpperCamelCase = incoming_node.match(
_SCREAMING_SNAKE_CASE )
# If there is remaining prefix, the word can't be on the tree
if remaining_prefix != "":
return False
# This applies when the word and the prefix are equal
elif remaining_word == "":
return incoming_node.is_leaf
# We have word remaining so we check the next node
else:
return incoming_node.find(_SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : List[Any] , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
UpperCamelCase = self.nodes.get(word[0] , _SCREAMING_SNAKE_CASE )
if not incoming_node:
return False
else:
UpperCamelCase , UpperCamelCase , UpperCamelCase = incoming_node.match(
_SCREAMING_SNAKE_CASE )
# If there is remaining prefix, the word can't be on the tree
if remaining_prefix != "":
return False
# We have word remaining so we check the next node
elif remaining_word != "":
return incoming_node.delete(_SCREAMING_SNAKE_CASE )
else:
# If it is not a leaf, we don't have to delete
if not incoming_node.is_leaf:
return False
else:
# We delete the nodes if no edges go from it
if len(incoming_node.nodes ) == 0:
del self.nodes[word[0]]
# We merge the current node with its only child
if len(self.nodes ) == 1 and not self.is_leaf:
UpperCamelCase = list(self.nodes.values() )[0]
UpperCamelCase = merging_node.is_leaf
self.prefix += merging_node.prefix
UpperCamelCase = merging_node.nodes
# If there is more than 1 edge, we just mark it as non-leaf
elif len(incoming_node.nodes ) > 1:
UpperCamelCase = False
# If there is 1 edge, we merge it with its child
else:
UpperCamelCase = list(incoming_node.nodes.values() )[0]
UpperCamelCase = merging_node.is_leaf
incoming_node.prefix += merging_node.prefix
UpperCamelCase = merging_node.nodes
return True
def _SCREAMING_SNAKE_CASE ( self : Tuple , _SCREAMING_SNAKE_CASE : int = 0 ):
"""simple docstring"""
if self.prefix != "":
print('-' * height , self.prefix , ' (leaf)' if self.is_leaf else '' )
for value in self.nodes.values():
value.print_tree(height + 1 )
def lowercase__ ( ) -> bool:
"""simple docstring"""
UpperCamelCase = 'banana bananas bandana band apple all beast'.split()
UpperCamelCase = RadixNode()
root.insert_many(_UpperCamelCase)
assert all(root.find(_UpperCamelCase) for word in words)
assert not root.find('bandanas')
assert not root.find('apps')
root.delete('all')
assert not root.find('all')
root.delete('banana')
assert not root.find('banana')
assert root.find('bananas')
return True
def lowercase__ ( ) -> None:
"""simple docstring"""
assert test_trie()
def lowercase__ ( ) -> None:
"""simple docstring"""
UpperCamelCase = RadixNode()
UpperCamelCase = 'banana bananas bandanas bandana band apple all beast'.split()
root.insert_many(_UpperCamelCase)
print('Words:' , _UpperCamelCase)
print('Tree:')
root.print_tree()
if __name__ == "__main__":
main()
| 280 | 0 |
import json
import os
import unittest
from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast
from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class lowerCamelCase_ ( lowercase , unittest.TestCase ):
__lowercase : Optional[Any] = GPTaTokenizer
__lowercase : Optional[Any] = GPTaTokenizerFast
__lowercase : Optional[int] = True
__lowercase : Optional[int] = {"add_prefix_space": True}
__lowercase : Union[str, Any] = False
def lowercase ( self ) -> Union[str, Any]:
"""simple docstring"""
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
_UpperCamelCase = [
"l",
"o",
"w",
"e",
"r",
"s",
"t",
"i",
"d",
"n",
"\u0120",
"\u0120l",
"\u0120n",
"\u0120lo",
"\u0120low",
"er",
"\u0120lowest",
"\u0120newer",
"\u0120wider",
"<unk>",
"<|endoftext|>",
]
_UpperCamelCase = dict(zip(lowerCamelCase_ , range(len(lowerCamelCase_ ) ) ) )
_UpperCamelCase = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
_UpperCamelCase = {"unk_token": "<unk>"}
_UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
_UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as fp:
fp.write(json.dumps(lowerCamelCase_ ) + "\n" )
with open(self.merges_file , "w" , encoding="utf-8" ) as fp:
fp.write("\n".join(lowerCamelCase_ ) )
def lowercase ( self , **lowerCamelCase_ ) -> Dict:
"""simple docstring"""
kwargs.update(self.special_tokens_map )
return GPTaTokenizer.from_pretrained(self.tmpdirname , **lowerCamelCase_ )
def lowercase ( self , **lowerCamelCase_ ) -> Tuple:
"""simple docstring"""
kwargs.update(self.special_tokens_map )
return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **lowerCamelCase_ )
def lowercase ( self , lowerCamelCase_ ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = "lower newer"
_UpperCamelCase = "lower newer"
return input_text, output_text
def lowercase ( self ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
_UpperCamelCase = "lower newer"
_UpperCamelCase = ["\u0120low", "er", "\u0120", "n", "e", "w", "er"]
_UpperCamelCase = tokenizer.tokenize(lowerCamelCase_ , add_prefix_space=lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ )
_UpperCamelCase = tokens + [tokenizer.unk_token]
_UpperCamelCase = [14, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) , lowerCamelCase_ )
def lowercase ( self ) -> int:
"""simple docstring"""
if not self.test_rust_tokenizer:
return
_UpperCamelCase = self.get_tokenizer()
_UpperCamelCase = self.get_rust_tokenizer(add_prefix_space=lowerCamelCase_ )
_UpperCamelCase = "lower newer"
# Testing tokenization
_UpperCamelCase = tokenizer.tokenize(lowerCamelCase_ , add_prefix_space=lowerCamelCase_ )
_UpperCamelCase = rust_tokenizer.tokenize(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ )
# Testing conversion to ids without special tokens
_UpperCamelCase = tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , add_prefix_space=lowerCamelCase_ )
_UpperCamelCase = rust_tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ )
# Testing conversion to ids with special tokens
_UpperCamelCase = self.get_rust_tokenizer(add_prefix_space=lowerCamelCase_ )
_UpperCamelCase = tokenizer.encode(lowerCamelCase_ , add_prefix_space=lowerCamelCase_ )
_UpperCamelCase = rust_tokenizer.encode(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ )
# Testing the unknown token
_UpperCamelCase = tokens + [rust_tokenizer.unk_token]
_UpperCamelCase = [14, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) , lowerCamelCase_ )
def lowercase ( self , *lowerCamelCase_ , **lowerCamelCase_ ) -> str:
"""simple docstring"""
pass
def lowercase ( self , lowerCamelCase_=15 ) -> str:
"""simple docstring"""
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
_UpperCamelCase = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ )
# Simple input
_UpperCamelCase = "This is a simple input"
_UpperCamelCase = ["This is a simple input 1", "This is a simple input 2"]
_UpperCamelCase = ("This is a simple input", "This is a pair")
_UpperCamelCase = [
("This is a simple input 1", "This is a simple input 2"),
("This is a simple pair 1", "This is a simple pair 2"),
]
# Simple input tests
self.assertRaises(lowerCamelCase_ , tokenizer_r.encode , lowerCamelCase_ , max_length=lowerCamelCase_ , padding="max_length" )
# Simple input
self.assertRaises(lowerCamelCase_ , tokenizer_r.encode_plus , lowerCamelCase_ , max_length=lowerCamelCase_ , padding="max_length" )
# Simple input
self.assertRaises(
lowerCamelCase_ , tokenizer_r.batch_encode_plus , lowerCamelCase_ , max_length=lowerCamelCase_ , padding="max_length" , )
# Pair input
self.assertRaises(lowerCamelCase_ , tokenizer_r.encode , lowerCamelCase_ , max_length=lowerCamelCase_ , padding="max_length" )
# Pair input
self.assertRaises(lowerCamelCase_ , tokenizer_r.encode_plus , lowerCamelCase_ , max_length=lowerCamelCase_ , padding="max_length" )
# Pair input
self.assertRaises(
lowerCamelCase_ , tokenizer_r.batch_encode_plus , lowerCamelCase_ , max_length=lowerCamelCase_ , padding="max_length" , )
def lowercase ( self ) -> List[Any]:
"""simple docstring"""
_UpperCamelCase = GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token="<pad>" )
# Simple input
_UpperCamelCase = "This is a simple input"
_UpperCamelCase = ["This is a simple input looooooooong", "This is a simple input"]
_UpperCamelCase = ("This is a simple input", "This is a pair")
_UpperCamelCase = [
("This is a simple input loooooong", "This is a simple input"),
("This is a simple pair loooooong", "This is a simple pair"),
]
_UpperCamelCase = tokenizer.pad_token_id
_UpperCamelCase = tokenizer(lowerCamelCase_ , padding="max_length" , max_length=30 , return_tensors="np" )
_UpperCamelCase = tokenizer(lowerCamelCase_ , padding=lowerCamelCase_ , truncate=lowerCamelCase_ , return_tensors="np" )
_UpperCamelCase = tokenizer(*lowerCamelCase_ , padding="max_length" , max_length=60 , return_tensors="np" )
_UpperCamelCase = tokenizer(lowerCamelCase_ , padding=lowerCamelCase_ , truncate=lowerCamelCase_ , return_tensors="np" )
# s
# test single string max_length padding
self.assertEqual(out_s["input_ids"].shape[-1] , 30 )
self.assertTrue(pad_token_id in out_s["input_ids"] )
self.assertTrue(0 in out_s["attention_mask"] )
# s2
# test automatic padding
self.assertEqual(out_sa["input_ids"].shape[-1] , 33 )
# long slice doesn't have padding
self.assertFalse(pad_token_id in out_sa["input_ids"][0] )
self.assertFalse(0 in out_sa["attention_mask"][0] )
# short slice does have padding
self.assertTrue(pad_token_id in out_sa["input_ids"][1] )
self.assertTrue(0 in out_sa["attention_mask"][1] )
# p
# test single pair max_length padding
self.assertEqual(out_p["input_ids"].shape[-1] , 60 )
self.assertTrue(pad_token_id in out_p["input_ids"] )
self.assertTrue(0 in out_p["attention_mask"] )
# p2
# test automatic padding pair
self.assertEqual(out_pa["input_ids"].shape[-1] , 52 )
# long slice pair doesn't have padding
self.assertFalse(pad_token_id in out_pa["input_ids"][0] )
self.assertFalse(0 in out_pa["attention_mask"][0] )
# short slice pair does have padding
self.assertTrue(pad_token_id in out_pa["input_ids"][1] )
self.assertTrue(0 in out_pa["attention_mask"][1] )
def lowercase ( self ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = "$$$"
_UpperCamelCase = GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=lowerCamelCase_ , add_bos_token=lowerCamelCase_ )
_UpperCamelCase = "This is a simple input"
_UpperCamelCase = ["This is a simple input 1", "This is a simple input 2"]
_UpperCamelCase = tokenizer.bos_token_id
_UpperCamelCase = tokenizer(lowerCamelCase_ )
_UpperCamelCase = tokenizer(lowerCamelCase_ )
self.assertEqual(out_s.input_ids[0] , lowerCamelCase_ )
self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) )
_UpperCamelCase = tokenizer.decode(out_s.input_ids )
_UpperCamelCase = tokenizer.batch_decode(out_sa.input_ids )
self.assertEqual(decode_s.split()[0] , lowerCamelCase_ )
self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) )
def lowercase ( self ) -> Union[str, Any]:
"""simple docstring"""
pass
def lowercase ( self ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = [self.get_tokenizer(do_lower_case=lowerCamelCase_ , add_bos_token=lowerCamelCase_ )]
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
_UpperCamelCase = "Encode this."
_UpperCamelCase = "This one too please."
_UpperCamelCase = tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ )
encoded_sequence += tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ )
_UpperCamelCase = tokenizer.encode_plus(
lowerCamelCase_ , lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , return_special_tokens_mask=lowerCamelCase_ , )
_UpperCamelCase = encoded_sequence_dict["input_ids"]
_UpperCamelCase = encoded_sequence_dict["special_tokens_mask"]
self.assertEqual(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) )
_UpperCamelCase = [
(x if not special_tokens_mask[i] else None) for i, x in enumerate(lowerCamelCase_ )
]
_UpperCamelCase = [x for x in filtered_sequence if x is not None]
self.assertEqual(lowerCamelCase_ , lowerCamelCase_ )
@require_tokenizers
class lowerCamelCase_ ( unittest.TestCase ):
def lowercase ( self ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = AutoTokenizer.from_pretrained("facebook/opt-350m" , from_slow=lowerCamelCase_ )
_UpperCamelCase = "A photo of a cat"
_UpperCamelCase = tokenizer.encode(
lowerCamelCase_ , )
self.assertEqual(lowerCamelCase_ , [2, 2_50, 13_45, 9, 10, 47_58] )
tokenizer.save_pretrained("test_opt" )
_UpperCamelCase = AutoTokenizer.from_pretrained("./test_opt" )
_UpperCamelCase = tokenizer.encode(
lowerCamelCase_ , )
self.assertEqual(lowerCamelCase_ , [2, 2_50, 13_45, 9, 10, 47_58] )
def lowercase ( self ) -> int:
"""simple docstring"""
_UpperCamelCase = AutoTokenizer.from_pretrained("facebook/opt-350m" , use_slow=lowerCamelCase_ )
_UpperCamelCase = "A photo of a cat"
_UpperCamelCase = tokenizer.encode(
lowerCamelCase_ , )
# Same as above
self.assertEqual(lowerCamelCase_ , [2, 2_50, 13_45, 9, 10, 47_58] )
@unittest.skip("This test is failing because of a bug in the fast tokenizer" )
def lowercase ( self ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = AutoTokenizer.from_pretrained("facebook/opt-350m" , from_slow=lowerCamelCase_ )
_UpperCamelCase = "bos"
_UpperCamelCase = tokenizer.get_vocab()["bos"]
_UpperCamelCase = "A photo of a cat"
_UpperCamelCase = tokenizer.encode(
lowerCamelCase_ , )
# We changed the bos token
self.assertEqual(lowerCamelCase_ , [3_19_57, 2_50, 13_45, 9, 10, 47_58] )
tokenizer.save_pretrained("./tok" )
_UpperCamelCase = AutoTokenizer.from_pretrained("./tok" )
self.assertTrue(tokenizer.is_fast )
_UpperCamelCase = tokenizer.encode(
lowerCamelCase_ , )
self.assertEqual(lowerCamelCase_ , [3_19_57, 2_50, 13_45, 9, 10, 47_58] )
| 589 |
import unittest
from transformers import SqueezeBertConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
SqueezeBertForMaskedLM,
SqueezeBertForMultipleChoice,
SqueezeBertForQuestionAnswering,
SqueezeBertForSequenceClassification,
SqueezeBertForTokenClassification,
SqueezeBertModel,
)
class lowerCamelCase_ ( lowercase ):
def __init__( self , lowerCamelCase_ , lowerCamelCase_=13 , lowerCamelCase_=7 , lowerCamelCase_=True , lowerCamelCase_=True , lowerCamelCase_=False , lowerCamelCase_=True , lowerCamelCase_=99 , lowerCamelCase_=32 , lowerCamelCase_=5 , lowerCamelCase_=4 , lowerCamelCase_=64 , lowerCamelCase_="gelu" , lowerCamelCase_=0.1 , lowerCamelCase_=0.1 , lowerCamelCase_=5_12 , lowerCamelCase_=16 , lowerCamelCase_=2 , lowerCamelCase_=0.02 , lowerCamelCase_=3 , lowerCamelCase_=4 , lowerCamelCase_=None , lowerCamelCase_=2 , lowerCamelCase_=2 , lowerCamelCase_=2 , lowerCamelCase_=2 , lowerCamelCase_=4 , lowerCamelCase_=1 , ) -> Tuple:
"""simple docstring"""
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = is_training
_UpperCamelCase = use_input_mask
_UpperCamelCase = use_token_type_ids
_UpperCamelCase = use_labels
_UpperCamelCase = vocab_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_act
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = type_vocab_size
_UpperCamelCase = type_sequence_label_size
_UpperCamelCase = initializer_range
_UpperCamelCase = num_labels
_UpperCamelCase = num_choices
_UpperCamelCase = scope
_UpperCamelCase = q_groups
_UpperCamelCase = k_groups
_UpperCamelCase = v_groups
_UpperCamelCase = post_attention_groups
_UpperCamelCase = intermediate_groups
_UpperCamelCase = output_groups
def lowercase ( self ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_UpperCamelCase = None
if self.use_input_mask:
_UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] )
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
if self.use_labels:
_UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
_UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices )
_UpperCamelCase = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def lowercase ( self ) -> List[Any]:
"""simple docstring"""
return SqueezeBertConfig(
embedding_size=self.hidden_size , vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , )
def lowercase ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = SqueezeBertModel(config=lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
_UpperCamelCase = model(lowerCamelCase_ , lowerCamelCase_ )
_UpperCamelCase = model(lowerCamelCase_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def lowercase ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> str:
"""simple docstring"""
_UpperCamelCase = SqueezeBertForMaskedLM(config=lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
_UpperCamelCase = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , labels=lowerCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def lowercase ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = SqueezeBertForQuestionAnswering(config=lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
_UpperCamelCase = model(
lowerCamelCase_ , attention_mask=lowerCamelCase_ , start_positions=lowerCamelCase_ , end_positions=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 lowercase ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = self.num_labels
_UpperCamelCase = SqueezeBertForSequenceClassification(lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
_UpperCamelCase = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , labels=lowerCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def lowercase ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Any:
"""simple docstring"""
_UpperCamelCase = self.num_labels
_UpperCamelCase = SqueezeBertForTokenClassification(config=lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
_UpperCamelCase = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , labels=lowerCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def lowercase ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> int:
"""simple docstring"""
_UpperCamelCase = self.num_choices
_UpperCamelCase = SqueezeBertForMultipleChoice(config=lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
_UpperCamelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_UpperCamelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_UpperCamelCase = model(
lowerCamelCase_ , attention_mask=lowerCamelCase_ , labels=lowerCamelCase_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def lowercase ( self ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = self.prepare_config_and_inputs()
((_UpperCamelCase) , (_UpperCamelCase) , (_UpperCamelCase) , (_UpperCamelCase) , (_UpperCamelCase) , (_UpperCamelCase)) = config_and_inputs
_UpperCamelCase = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class lowerCamelCase_ ( lowercase , lowercase , unittest.TestCase ):
__lowercase : Any = (
(
SqueezeBertModel,
SqueezeBertForMaskedLM,
SqueezeBertForMultipleChoice,
SqueezeBertForQuestionAnswering,
SqueezeBertForSequenceClassification,
SqueezeBertForTokenClassification,
)
if is_torch_available()
else None
)
__lowercase : Dict = (
{
"feature-extraction": SqueezeBertModel,
"fill-mask": SqueezeBertForMaskedLM,
"question-answering": SqueezeBertForQuestionAnswering,
"text-classification": SqueezeBertForSequenceClassification,
"token-classification": SqueezeBertForTokenClassification,
"zero-shot": SqueezeBertForSequenceClassification,
}
if is_torch_available()
else {}
)
__lowercase : Tuple = False
__lowercase : List[str] = True
__lowercase : Any = False
def lowercase ( self ) -> Any:
"""simple docstring"""
_UpperCamelCase = SqueezeBertModelTester(self )
_UpperCamelCase = ConfigTester(self , config_class=lowerCamelCase_ , dim=37 )
def lowercase ( self ) -> Optional[int]:
"""simple docstring"""
self.config_tester.run_common_tests()
def lowercase ( self ) -> List[str]:
"""simple docstring"""
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_squeezebert_model(*lowerCamelCase_ )
def lowercase ( self ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_squeezebert_for_masked_lm(*lowerCamelCase_ )
def lowercase ( self ) -> int:
"""simple docstring"""
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_squeezebert_for_question_answering(*lowerCamelCase_ )
def lowercase ( self ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_squeezebert_for_sequence_classification(*lowerCamelCase_ )
def lowercase ( self ) -> Any:
"""simple docstring"""
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_squeezebert_for_token_classification(*lowerCamelCase_ )
def lowercase ( self ) -> Tuple:
"""simple docstring"""
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_squeezebert_for_multiple_choice(*lowerCamelCase_ )
@slow
def lowercase ( self ) -> Any:
"""simple docstring"""
for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase = SqueezeBertModel.from_pretrained(lowerCamelCase_ )
self.assertIsNotNone(lowerCamelCase_ )
@require_sentencepiece
@require_tokenizers
@require_torch
class lowerCamelCase_ ( unittest.TestCase ):
@slow
def lowercase ( self ) -> Any:
"""simple docstring"""
_UpperCamelCase = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli" )
_UpperCamelCase = torch.tensor([[1, 2_94_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 13, 15_88, 2]] )
_UpperCamelCase = model(lowerCamelCase_ )[0]
_UpperCamelCase = torch.Size((1, 3) )
self.assertEqual(output.shape , lowerCamelCase_ )
_UpperCamelCase = torch.tensor([[0.64_01, -0.03_49, -0.60_41]] )
self.assertTrue(torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1E-4 ) )
| 589 | 1 |
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__)
| 221 | from argparse import ArgumentParser
from datasets.commands.convert import ConvertCommand
from datasets.commands.dummy_data import DummyDataCommand
from datasets.commands.env import EnvironmentCommand
from datasets.commands.run_beam import RunBeamCommand
from datasets.commands.test import TestCommand
from datasets.utils.logging import set_verbosity_info
def __lowerCAmelCase ( A_ : Optional[int] ) -> Optional[int]:
return {key.lstrip("-" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )}
def __lowerCAmelCase ( ) -> Dict:
__UpperCAmelCase = ArgumentParser(
"HuggingFace Datasets CLI tool" , usage="datasets-cli <command> [<args>]" , allow_abbrev=A_ )
__UpperCAmelCase = parser.add_subparsers(help="datasets-cli command helpers" )
set_verbosity_info()
# Register commands
ConvertCommand.register_subcommand(A_ )
EnvironmentCommand.register_subcommand(A_ )
TestCommand.register_subcommand(A_ )
RunBeamCommand.register_subcommand(A_ )
DummyDataCommand.register_subcommand(A_ )
# Parse args
__UpperCAmelCase , __UpperCAmelCase = parser.parse_known_args()
if not hasattr(A_ , "func" ):
parser.print_help()
exit(1 )
__UpperCAmelCase = parse_unknown_args(A_ )
# Run
__UpperCAmelCase = args.func(A_ , **A_ )
service.run()
if __name__ == "__main__":
main()
| 221 | 1 |
import json
import os
import shutil
import warnings
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import List
from ..utils import logging
from . import BaseTransformersCLICommand
try:
from cookiecutter.main import cookiecutter
snake_case__ = True
except ImportError:
snake_case__ = False
snake_case__ = logging.get_logger(__name__) # pylint: disable=invalid-name
def __magic_name__( __UpperCAmelCase ) -> Union[str, Any]:
'''simple docstring'''
return AddNewModelCommand(args.testing , args.testing_file , path=args.path )
class UpperCamelCase ( __lowercase ):
'''simple docstring'''
@staticmethod
def UpperCamelCase_ ( A_ ) -> Tuple:
"""simple docstring"""
_lowerCamelCase = parser.add_parser('''add-new-model''' )
add_new_model_parser.add_argument('''--testing''' , action='''store_true''' , help='''If in testing mode.''' )
add_new_model_parser.add_argument('''--testing_file''' , type=A_ , help='''Configuration file on which to run.''' )
add_new_model_parser.add_argument(
'''--path''' , type=A_ , help='''Path to cookiecutter. Should only be used for testing purposes.''' )
add_new_model_parser.set_defaults(func=A_ )
def __init__( self , A_ , A_ , A_=None , *A_ ) -> int:
"""simple docstring"""
_lowerCamelCase = testing
_lowerCamelCase = testing_file
_lowerCamelCase = path
def UpperCamelCase_ ( self ) -> str:
"""simple docstring"""
warnings.warn(
'''The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. '''
'''It is not actively maintained anymore, so might give a result that won\'t pass all tests and quality '''
'''checks, you should use `transformers-cli add-new-model-like` instead.''' )
if not _has_cookiecutter:
raise ImportError(
'''Model creation dependencies are required to use the `add_new_model` command. Install them by running '''
'''the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n''' )
# Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory
_lowerCamelCase = [directory for directory in os.listdir() if '''cookiecutter-template-''' == directory[:22]]
if len(A_ ) > 0:
raise ValueError(
'''Several directories starting with `cookiecutter-template-` in current working directory. '''
'''Please clean your directory by removing all folders starting with `cookiecutter-template-` or '''
'''change your working directory.''' )
_lowerCamelCase = (
Path(A_ ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent
)
_lowerCamelCase = path_to_transformer_root / '''templates''' / '''adding_a_new_model'''
# Execute cookiecutter
if not self._testing:
cookiecutter(str(A_ ) )
else:
with open(self._testing_file , '''r''' ) as configuration_file:
_lowerCamelCase = json.load(A_ )
cookiecutter(
str(path_to_cookiecutter if self._path is None else self._path ) , no_input=A_ , extra_context=A_ , )
_lowerCamelCase = [directory for directory in os.listdir() if '''cookiecutter-template-''' in directory[:22]][0]
# Retrieve configuration
with open(directory + '''/configuration.json''' , '''r''' ) as configuration_file:
_lowerCamelCase = json.load(A_ )
_lowerCamelCase = configuration['''lowercase_modelname''']
_lowerCamelCase = configuration['''generate_tensorflow_pytorch_and_flax''']
os.remove(F'{directory}/configuration.json' )
_lowerCamelCase = '''PyTorch''' in generate_tensorflow_pytorch_and_flax
_lowerCamelCase = '''TensorFlow''' in generate_tensorflow_pytorch_and_flax
_lowerCamelCase = '''Flax''' in generate_tensorflow_pytorch_and_flax
_lowerCamelCase = F'{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}'
os.makedirs(A_ , exist_ok=A_ )
os.makedirs(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}' , exist_ok=A_ )
# Tests require submodules as they have parent imports
with open(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py' , '''w''' ):
pass
shutil.move(
F'{directory}/__init__.py' , F'{model_dir}/__init__.py' , )
shutil.move(
F'{directory}/configuration_{lowercase_model_name}.py' , F'{model_dir}/configuration_{lowercase_model_name}.py' , )
def remove_copy_lines(A_ ):
with open(A_ , '''r''' ) as f:
_lowerCamelCase = f.readlines()
with open(A_ , '''w''' ) as f:
for line in lines:
if "# Copied from transformers." not in line:
f.write(A_ )
if output_pytorch:
if not self._testing:
remove_copy_lines(F'{directory}/modeling_{lowercase_model_name}.py' )
shutil.move(
F'{directory}/modeling_{lowercase_model_name}.py' , F'{model_dir}/modeling_{lowercase_model_name}.py' , )
shutil.move(
F'{directory}/test_modeling_{lowercase_model_name}.py' , F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py' , )
else:
os.remove(F'{directory}/modeling_{lowercase_model_name}.py' )
os.remove(F'{directory}/test_modeling_{lowercase_model_name}.py' )
if output_tensorflow:
if not self._testing:
remove_copy_lines(F'{directory}/modeling_tf_{lowercase_model_name}.py' )
shutil.move(
F'{directory}/modeling_tf_{lowercase_model_name}.py' , F'{model_dir}/modeling_tf_{lowercase_model_name}.py' , )
shutil.move(
F'{directory}/test_modeling_tf_{lowercase_model_name}.py' , F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py' , )
else:
os.remove(F'{directory}/modeling_tf_{lowercase_model_name}.py' )
os.remove(F'{directory}/test_modeling_tf_{lowercase_model_name}.py' )
if output_flax:
if not self._testing:
remove_copy_lines(F'{directory}/modeling_flax_{lowercase_model_name}.py' )
shutil.move(
F'{directory}/modeling_flax_{lowercase_model_name}.py' , F'{model_dir}/modeling_flax_{lowercase_model_name}.py' , )
shutil.move(
F'{directory}/test_modeling_flax_{lowercase_model_name}.py' , F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py' , )
else:
os.remove(F'{directory}/modeling_flax_{lowercase_model_name}.py' )
os.remove(F'{directory}/test_modeling_flax_{lowercase_model_name}.py' )
shutil.move(
F'{directory}/{lowercase_model_name}.md' , F'{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md' , )
shutil.move(
F'{directory}/tokenization_{lowercase_model_name}.py' , F'{model_dir}/tokenization_{lowercase_model_name}.py' , )
shutil.move(
F'{directory}/tokenization_fast_{lowercase_model_name}.py' , F'{model_dir}/tokenization_{lowercase_model_name}_fast.py' , )
from os import fdopen, remove
from shutil import copymode, move
from tempfile import mkstemp
def replace(A_ , A_ , A_ ):
# Create temp file
_lowerCamelCase , _lowerCamelCase = mkstemp()
_lowerCamelCase = False
with fdopen(A_ , '''w''' ) as new_file:
with open(A_ ) as old_file:
for line in old_file:
new_file.write(A_ )
if line_to_copy_below in line:
_lowerCamelCase = True
for line_to_copy in lines_to_copy:
new_file.write(A_ )
if not line_found:
raise ValueError(F'Line {line_to_copy_below} was not found in file.' )
# Copy the file permissions from the old file to the new file
copymode(A_ , A_ )
# Remove original file
remove(A_ )
# Move new file
move(A_ , A_ )
def skip_units(A_ ):
return (
("generating PyTorch" in line and not output_pytorch)
or ("generating TensorFlow" in line and not output_tensorflow)
or ("generating Flax" in line and not output_flax)
)
def replace_in_files(A_ ):
with open(A_ ) as datafile:
_lowerCamelCase = []
_lowerCamelCase = False
_lowerCamelCase = False
for line in datafile:
if "# To replace in: " in line and "##" not in line:
_lowerCamelCase = line.split('''"''' )[1]
_lowerCamelCase = skip_units(A_ )
elif "# Below: " in line and "##" not in line:
_lowerCamelCase = line.split('''"''' )[1]
_lowerCamelCase = skip_units(A_ )
elif "# End." in line and "##" not in line:
if not skip_file and not skip_snippet:
replace(A_ , A_ , A_ )
_lowerCamelCase = []
elif "# Replace with" in line and "##" not in line:
_lowerCamelCase = []
elif "##" not in line:
lines_to_copy.append(A_ )
remove(A_ )
replace_in_files(F'{directory}/to_replace_{lowercase_model_name}.py' )
os.rmdir(A_ ) | 713 | import os
from glob import glob
import imageio
import torch
import torchvision
import wandb
from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan
from loaders import load_vqgan
from PIL import Image
from torch import nn
from transformers import CLIPModel, CLIPTokenizerFast
from utils import get_device, get_timestamp, show_pil
class UpperCamelCase :
'''simple docstring'''
def __init__( self , A_ = "cpu" , A_ = "openai/clip-vit-large-patch14" ) -> None:
"""simple docstring"""
_lowerCamelCase = device
_lowerCamelCase = CLIPTokenizerFast.from_pretrained(A_ )
_lowerCamelCase = [0.48145466, 0.4578275, 0.40821073]
_lowerCamelCase = [0.26862954, 0.26130258, 0.27577711]
_lowerCamelCase = torchvision.transforms.Normalize(self.image_mean , self.image_std )
_lowerCamelCase = torchvision.transforms.Resize(2_24 )
_lowerCamelCase = torchvision.transforms.CenterCrop(2_24 )
def UpperCamelCase_ ( self , A_ ) -> int:
"""simple docstring"""
_lowerCamelCase = self.resize(A_ )
_lowerCamelCase = self.center_crop(A_ )
_lowerCamelCase = self.normalize(A_ )
return images
def __call__( self , A_=None , A_=None , **A_ ) -> Optional[Any]:
"""simple docstring"""
_lowerCamelCase = self.tokenizer(text=A_ , **A_ )
_lowerCamelCase = self.preprocess_img(A_ )
_lowerCamelCase = {key: value.to(self.device ) for (key, value) in encoding.items()}
return encoding
class UpperCamelCase ( nn.Module ):
'''simple docstring'''
def __init__( self , A_=10 , A_=0.01 , A_=None , A_=None , A_=None , A_=None , A_=None , A_=None , A_=False , A_=True , A_="image" , A_=True , A_=False , A_=False , A_=False , ) -> None:
"""simple docstring"""
super().__init__()
_lowerCamelCase = None
_lowerCamelCase = device if device else get_device()
if vqgan:
_lowerCamelCase = vqgan
else:
_lowerCamelCase = load_vqgan(self.device , conf_path=A_ , ckpt_path=A_ )
self.vqgan.eval()
if clip:
_lowerCamelCase = clip
else:
_lowerCamelCase = CLIPModel.from_pretrained('''openai/clip-vit-base-patch32''' )
self.clip.to(self.device )
_lowerCamelCase = ProcessorGradientFlow(device=self.device )
_lowerCamelCase = iterations
_lowerCamelCase = lr
_lowerCamelCase = log
_lowerCamelCase = make_grid
_lowerCamelCase = return_val
_lowerCamelCase = quantize
_lowerCamelCase = self.vqgan.decoder.z_shape
def UpperCamelCase_ ( self , A_=None , A_=None , A_=5 , A_=True ) -> Any:
"""simple docstring"""
_lowerCamelCase = []
if output_path is None:
_lowerCamelCase = '''./animation.gif'''
if input_path is None:
_lowerCamelCase = self.save_path
_lowerCamelCase = sorted(glob(input_path + '''/*''' ) )
if not len(A_ ):
raise ValueError(
'''No images found in save path, aborting (did you pass save_intermediate=True to the generate'''
''' function?)''' )
if len(A_ ) == 1:
print('''Only one image found in save path, (did you pass save_intermediate=True to the generate function?)''' )
_lowerCamelCase = total_duration / len(A_ )
_lowerCamelCase = [frame_duration] * len(A_ )
if extend_frames:
_lowerCamelCase = 1.5
_lowerCamelCase = 3
for file_name in paths:
if file_name.endswith('''.png''' ):
images.append(imageio.imread(A_ ) )
imageio.mimsave(A_ , A_ , duration=A_ )
print(F'gif saved to {output_path}' )
def UpperCamelCase_ ( self , A_=None , A_=None ) -> Union[str, Any]:
"""simple docstring"""
if not (path or img):
raise ValueError('''Input either path or tensor''' )
if img is not None:
raise NotImplementedError
_lowerCamelCase = preprocess(Image.open(A_ ) , target_image_size=2_56 ).to(self.device )
_lowerCamelCase = preprocess_vqgan(A_ )
_lowerCamelCase , *_lowerCamelCase = self.vqgan.encode(A_ )
return z
def UpperCamelCase_ ( self , A_ ) -> Optional[int]:
"""simple docstring"""
_lowerCamelCase = self.latent.detach().requires_grad_()
_lowerCamelCase = base_latent + transform_vector
if self.quantize:
_lowerCamelCase , *_lowerCamelCase = self.vqgan.quantize(A_ )
else:
_lowerCamelCase = trans_latent
return self.vqgan.decode(A_ )
def UpperCamelCase_ ( self , A_ , A_ , A_=None ) -> Any:
"""simple docstring"""
_lowerCamelCase = self.clip_preprocessor(text=A_ , images=A_ , return_tensors='''pt''' , padding=A_ )
_lowerCamelCase = self.clip(**A_ )
_lowerCamelCase = clip_outputs.logits_per_image
if weights is not None:
_lowerCamelCase = similarity_logits * weights
return similarity_logits.sum()
def UpperCamelCase_ ( self , A_ , A_ , A_ ) -> Dict:
"""simple docstring"""
_lowerCamelCase = self._get_clip_similarity(pos_prompts['''prompts'''] , A_ , weights=(1 / pos_prompts['''weights''']) )
if neg_prompts:
_lowerCamelCase = self._get_clip_similarity(neg_prompts['''prompts'''] , A_ , weights=neg_prompts['''weights'''] )
else:
_lowerCamelCase = torch.tensor([1] , device=self.device )
_lowerCamelCase = -torch.log(A_ ) + torch.log(A_ )
return loss
def UpperCamelCase_ ( self , A_ , A_ , A_ ) -> str:
"""simple docstring"""
_lowerCamelCase = torch.randn_like(self.latent , requires_grad=A_ , device=self.device )
_lowerCamelCase = torch.optim.Adam([vector] , lr=self.lr )
for i in range(self.iterations ):
optim.zero_grad()
_lowerCamelCase = self._add_vector(A_ )
_lowerCamelCase = loop_post_process(A_ )
_lowerCamelCase = self._get_CLIP_loss(A_ , A_ , A_ )
print('''CLIP loss''' , A_ )
if self.log:
wandb.log({'''CLIP Loss''': clip_loss} )
clip_loss.backward(retain_graph=A_ )
optim.step()
if self.return_val == "image":
yield custom_to_pil(transformed_img[0] )
else:
yield vector
def UpperCamelCase_ ( self , A_ , A_ , A_ ) -> Any:
"""simple docstring"""
wandb.init(reinit=A_ , project='''face-editor''' )
wandb.config.update({'''Positive Prompts''': positive_prompts} )
wandb.config.update({'''Negative Prompts''': negative_prompts} )
wandb.config.update({'''lr''': self.lr, '''iterations''': self.iterations} )
if image_path:
_lowerCamelCase = Image.open(A_ )
_lowerCamelCase = image.resize((2_56, 2_56) )
wandb.log('''Original Image''' , wandb.Image(A_ ) )
def UpperCamelCase_ ( self , A_ ) -> int:
"""simple docstring"""
if not prompts:
return []
_lowerCamelCase = []
_lowerCamelCase = []
if isinstance(A_ , A_ ):
_lowerCamelCase = [prompt.strip() for prompt in prompts.split('''|''' )]
for prompt in prompts:
if isinstance(A_ , (tuple, list) ):
_lowerCamelCase = prompt[0]
_lowerCamelCase = float(prompt[1] )
elif ":" in prompt:
_lowerCamelCase , _lowerCamelCase = prompt.split(''':''' )
_lowerCamelCase = float(A_ )
else:
_lowerCamelCase = prompt
_lowerCamelCase = 1.0
processed_prompts.append(A_ )
weights.append(A_ )
return {
"prompts": processed_prompts,
"weights": torch.tensor(A_ , device=self.device ),
}
def UpperCamelCase_ ( self , A_ , A_=None , A_=None , A_=True , A_=False , A_=True , A_=True , A_=None , ) -> str:
"""simple docstring"""
if image_path:
_lowerCamelCase = self._get_latent(A_ )
else:
_lowerCamelCase = torch.randn(self.latent_dim , device=self.device )
if self.log:
self._init_logging(A_ , A_ , A_ )
assert pos_prompts, "You must provide at least one positive prompt."
_lowerCamelCase = self.process_prompts(A_ )
_lowerCamelCase = self.process_prompts(A_ )
if save_final and save_path is None:
_lowerCamelCase = os.path.join('''./outputs/''' , '''_'''.join(pos_prompts['''prompts'''] ) )
if not os.path.exists(A_ ):
os.makedirs(A_ )
else:
_lowerCamelCase = save_path + '''_''' + get_timestamp()
os.makedirs(A_ )
_lowerCamelCase = save_path
_lowerCamelCase = self.vqgan.decode(self.latent )[0]
if show_intermediate:
print('''Original Image''' )
show_pil(custom_to_pil(A_ ) )
_lowerCamelCase = loop_post_process(A_ )
for iter, transformed_img in enumerate(self._optimize_CLIP(A_ , A_ , A_ ) ):
if show_intermediate:
show_pil(A_ )
if save_intermediate:
transformed_img.save(os.path.join(self.save_path , F'iter_{iter:03d}.png' ) )
if self.log:
wandb.log({'''Image''': wandb.Image(A_ )} )
if show_final:
show_pil(A_ )
if save_final:
transformed_img.save(os.path.join(self.save_path , F'iter_{iter:03d}_final.png' ) ) | 638 | 0 |
"""simple docstring"""
import itertools
import random
import unittest
import numpy as np
from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available
from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin
lowerCAmelCase__ = random.Random()
if is_torch_available():
import torch
def snake_case_ ( A_ : Tuple, A_ : List[Any]=1.0, A_ : Optional[Any]=None, A_ : Optional[int]=None ):
'''simple docstring'''
if rng is None:
_lowerCamelCase : Dict = global_rng
_lowerCamelCase : Any = []
for batch_idx in range(shape[0] ):
values.append([] )
for _ in range(shape[1] ):
values[-1].append(rng.random() * scale )
return values
class __snake_case ( unittest.TestCase):
def __init__( self : int , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[Any]=7 , __lowerCAmelCase : int=4_0_0 , __lowerCAmelCase : List[str]=2_0_0_0 , __lowerCAmelCase : str=1 , __lowerCAmelCase : Tuple=0.0 , __lowerCAmelCase : Dict=1_6_0_0_0 , __lowerCAmelCase : Dict=True , __lowerCAmelCase : Any=True , ):
"""simple docstring"""
_lowerCamelCase : int = parent
_lowerCamelCase : Optional[Any] = batch_size
_lowerCamelCase : int = min_seq_length
_lowerCamelCase : Any = max_seq_length
_lowerCamelCase : int = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
_lowerCamelCase : Dict = feature_size
_lowerCamelCase : int = padding_value
_lowerCamelCase : Tuple = sampling_rate
_lowerCamelCase : Optional[int] = return_attention_mask
_lowerCamelCase : List[str] = do_normalize
def SCREAMING_SNAKE_CASE ( self : Optional[int] ):
"""simple docstring"""
return {
"feature_size": self.feature_size,
"padding_value": self.padding_value,
"sampling_rate": self.sampling_rate,
"return_attention_mask": self.return_attention_mask,
"do_normalize": self.do_normalize,
}
def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : Any=False , __lowerCAmelCase : int=False ):
"""simple docstring"""
def _flatten(__lowerCAmelCase : int ):
return list(itertools.chain(*__lowerCAmelCase ) )
if equal_length:
_lowerCamelCase : str = floats_list((self.batch_size, self.max_seq_length) )
else:
# make sure that inputs increase in size
_lowerCamelCase : Optional[Any] = [
_flatten(floats_list((x, self.feature_size) ) )
for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff )
]
if numpify:
_lowerCamelCase : Dict = [np.asarray(__lowerCAmelCase ) for x in speech_inputs]
return speech_inputs
@require_torch
@require_torchaudio
class __snake_case ( _lowercase , unittest.TestCase):
snake_case__ : List[str] = ASTFeatureExtractor
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ):
"""simple docstring"""
_lowerCamelCase : Union[str, Any] = ASTFeatureExtractionTester(self )
def SCREAMING_SNAKE_CASE ( self : Dict ):
"""simple docstring"""
_lowerCamelCase : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
# create three inputs of length 800, 1000, and 1200
_lowerCamelCase : List[str] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
_lowerCamelCase : Tuple = [np.asarray(__lowerCAmelCase ) for speech_input in speech_inputs]
# Test not batched input
_lowerCamelCase : Optional[Any] = feat_extract(speech_inputs[0] , return_tensors='''np''' ).input_values
_lowerCamelCase : Optional[int] = feat_extract(np_speech_inputs[0] , return_tensors='''np''' ).input_values
self.assertTrue(np.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) )
# Test batched
_lowerCamelCase : Optional[Any] = feat_extract(__lowerCAmelCase , padding=__lowerCAmelCase , return_tensors='''np''' ).input_values
_lowerCamelCase : Optional[Any] = feat_extract(__lowerCAmelCase , padding=__lowerCAmelCase , return_tensors='''np''' ).input_values
for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase , __lowerCAmelCase ):
self.assertTrue(np.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) )
# Test 2-D numpy arrays are batched.
_lowerCamelCase : str = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
_lowerCamelCase : Any = np.asarray(__lowerCAmelCase )
_lowerCamelCase : Dict = feat_extract(__lowerCAmelCase , return_tensors='''np''' ).input_values
_lowerCamelCase : List[Any] = feat_extract(__lowerCAmelCase , return_tensors='''np''' ).input_values
for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase , __lowerCAmelCase ):
self.assertTrue(np.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) )
@require_torch
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ):
"""simple docstring"""
import torch
_lowerCamelCase : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
_lowerCamelCase : Any = np.random.rand(1_0_0 ).astype(np.floataa )
_lowerCamelCase : int = np_speech_inputs.tolist()
for inputs in [py_speech_inputs, np_speech_inputs]:
_lowerCamelCase : Union[str, Any] = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''np''' )
self.assertTrue(np_processed.input_values.dtype == np.floataa )
_lowerCamelCase : Tuple = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''pt''' )
self.assertTrue(pt_processed.input_values.dtype == torch.floataa )
def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : List[str] ):
"""simple docstring"""
from datasets import load_dataset
_lowerCamelCase : str = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' )
# automatic decoding with librispeech
_lowerCamelCase : int = ds.sort('''id''' ).select(range(__lowerCAmelCase ) )[:num_samples]['''audio''']
return [x["array"] for x in speech_samples]
@require_torch
def SCREAMING_SNAKE_CASE ( self : Optional[int] ):
"""simple docstring"""
_lowerCamelCase : Optional[int] = torch.tensor(
[-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76,
-1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33,
-1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36,
-0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] )
# fmt: on
_lowerCamelCase : Optional[Any] = self._load_datasamples(1 )
_lowerCamelCase : int = ASTFeatureExtractor()
_lowerCamelCase : Tuple = feature_extractor(__lowerCAmelCase , return_tensors='''pt''' ).input_values
self.assertEquals(input_values.shape , (1, 1_0_2_4, 1_2_8) )
self.assertTrue(torch.allclose(input_values[0, 0, :3_0] , __lowerCAmelCase , atol=1E-4 ) )
| 83 |
A : Any = '\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n'
A : Optional[int] = [{'type': 'code', 'content': INSTALL_CONTENT}]
A : Optional[int] = {
'{processor_class}': 'FakeProcessorClass',
'{model_class}': 'FakeModelClass',
'{object_class}': 'FakeObjectClass',
}
| 371 | 0 |
import argparse
import json
import os
from collections import OrderedDict
import numpy as np
import tensorflow as tf
import torch
def __lowerCAmelCase ( UpperCamelCase ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase__ : List[Any] = os.path.join(args.tf_model_dir , '''parameters.json''' )
lowerCAmelCase__ : Any = json.loads(open(lowerCAmelCase__ ).read() )
if not params:
raise ValueError(
F"""It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.""" )
if not args.output.endswith('''.pt''' ):
lowerCAmelCase__ : Dict = args.output + '''.pt'''
lowerCAmelCase__ : Tuple = OrderedDict()
with tf.device('''/CPU:0''' ):
lowerCAmelCase__ : List[str] = tf.train.load_checkpoint(args.tf_model_dir )
lowerCAmelCase__ : Dict = reader.get_variable_to_shape_map()
for key_name in shapes.keys():
lowerCAmelCase__ : int = reader.get_tensor(lowerCAmelCase__ ).astype(np.floataa )
if key_name.endswith('''/adam_m''' ) or key_name.endswith('''/adam_v''' ):
continue
if key_name.startswith('''pasts/''' ):
if key_name.startswith('''pasts/mlp''' ):
lowerCAmelCase__ : List[Any] = int(key_name[9] )
elif key_name.startswith('''pasts/out''' ):
lowerCAmelCase__ : Dict = 8
lowerCAmelCase__ : int = '''model.sqout.%d.weight''' % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time
lowerCAmelCase__ : List[Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
lowerCAmelCase__ : Any = torch.tensor(lowerCAmelCase__ )
elif key_name.startswith('''model/moe''' ):
lowerCAmelCase__ : Optional[int] = int(key_name[9:].split('''/''' )[0] )
if key_name.endswith('''/switch_gating/kernel''' ):
lowerCAmelCase__ : Any = '''model.blocks.%d.feed_forward.mlp.router.classifier.weight''' % player
lowerCAmelCase__ : List[Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
lowerCAmelCase__ : Any = torch.tensor(lowerCAmelCase__ )
elif key_name.endswith('''/softmlp/kernel''' ):
lowerCAmelCase__ : Union[str, Any] = '''model.blocks.%d.feed_forward.soft_bypass_mlp.weight''' % player
lowerCAmelCase__ : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
lowerCAmelCase__ : Dict = torch.tensor(lowerCAmelCase__ )
elif key_name.endswith('''/wo/kernel''' ) or key_name.endswith('''/wi/kernel''' ):
lowerCAmelCase__ : Any = key_name[-9:-7]
for i in range(16 ):
lowerCAmelCase__ : Any = '''model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight''' % (player, i, nlayer)
lowerCAmelCase__ : Tuple = (
vnp[i].transpose([1, 0] ).copy()
) # In Mesh-Tensorflow, it is one array, so it is divided
lowerCAmelCase__ : List[Any] = torch.tensor(lowerCAmelCase__ )
elif key_name.startswith('''model/mlp''' ):
lowerCAmelCase__ : Union[str, Any] = int(key_name[9:].split('''/''' )[0] )
if key_name.endswith('''/p1/kernel''' ):
lowerCAmelCase__ : Optional[Any] = '''model.blocks.%d.feed_forward.mlp.wi.weight''' % player
lowerCAmelCase__ : Dict = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
lowerCAmelCase__ : Any = torch.tensor(lowerCAmelCase__ )
elif key_name.endswith('''/p1/bias''' ):
lowerCAmelCase__ : Optional[int] = '''model.blocks.%d.feed_forward.mlp.wi.bias''' % player
lowerCAmelCase__ : List[Any] = vnp.copy() # same because it is one dimensional
lowerCAmelCase__ : Dict = torch.tensor(lowerCAmelCase__ )
elif key_name.endswith('''/p2/kernel''' ):
lowerCAmelCase__ : Optional[int] = '''model.blocks.%d.feed_forward.mlp.wo.weight''' % player
lowerCAmelCase__ : Union[str, Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
lowerCAmelCase__ : Optional[int] = torch.tensor(lowerCAmelCase__ )
elif key_name.endswith('''/p2/bias''' ):
lowerCAmelCase__ : List[Any] = '''model.blocks.%d.feed_forward.mlp.wo.bias''' % player
lowerCAmelCase__ : Tuple = vnp.copy() # same because it is one dimensional
lowerCAmelCase__ : List[Any] = torch.tensor(lowerCAmelCase__ )
elif key_name.startswith('''model/ln''' ):
lowerCAmelCase__ : str = int(key_name[8:].split('''/''' )[0] )
if key_name.endswith('''/b''' ):
lowerCAmelCase__ : int = '''model.blocks.%d.feed_forward.norm.bias''' % player
lowerCAmelCase__ : Tuple = vnp.copy() # same because it is one dimensional
lowerCAmelCase__ : str = torch.tensor(lowerCAmelCase__ )
elif key_name.endswith('''/g''' ):
lowerCAmelCase__ : int = '''model.blocks.%d.feed_forward.norm.weight''' % player
lowerCAmelCase__ : List[Any] = vnp.copy() # same because it is one dimensional
lowerCAmelCase__ : List[str] = torch.tensor(lowerCAmelCase__ )
elif key_name.startswith('''model/att''' ):
lowerCAmelCase__ : List[Any] = int(key_name[9:].split('''/''' )[0] )
if key_name.endswith('''/qkv/kernel''' ):
lowerCAmelCase__ : Dict = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum
lowerCAmelCase__ : Tuple = state[:, 0, :, :]
lowerCAmelCase__ : Dict = state[:, 1, :, :]
lowerCAmelCase__ : int = state[:, 2, :, :]
lowerCAmelCase__ : Optional[int] = (
state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] )
.transpose([1, 0] )
.copy()
) # Mesh-Tensorflow is a diagonal matrix
lowerCAmelCase__ : Union[str, Any] = (
state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] )
.transpose([1, 0] )
.copy()
) # Mesh-Tensorflow is a diagonal matrix
lowerCAmelCase__ : Tuple = (
state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] )
.transpose([1, 0] )
.copy()
) # Mesh-Tensorflow is a diagonal matrix
lowerCAmelCase__ : int = '''model.blocks.%d.self_attn.self_attn.q_proj.weight''' % player
lowerCAmelCase__ : Optional[Any] = torch.tensor(lowerCAmelCase__ )
lowerCAmelCase__ : List[Any] = '''model.blocks.%d.self_attn.self_attn.k_proj.weight''' % player
lowerCAmelCase__ : Optional[Any] = torch.tensor(lowerCAmelCase__ )
lowerCAmelCase__ : Dict = '''model.blocks.%d.self_attn.self_attn.v_proj.weight''' % player
lowerCAmelCase__ : List[Any] = torch.tensor(lowerCAmelCase__ )
elif key_name.endswith('''/o/kernel''' ):
lowerCAmelCase__ : int = '''model.blocks.%d.self_attn.self_attn.out_proj.weight''' % player
lowerCAmelCase__ : str = (
vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy()
) # Mesh-Tensorflow is a diagonal matrix
lowerCAmelCase__ : Optional[int] = torch.tensor(lowerCAmelCase__ )
elif key_name.startswith('''model/an''' ):
lowerCAmelCase__ : Union[str, Any] = int(key_name[8:].split('''/''' )[0] )
if key_name.endswith('''/b''' ):
lowerCAmelCase__ : Union[str, Any] = '''model.blocks.%d.self_attn.norm.bias''' % player
lowerCAmelCase__ : int = vnp.copy() # same because it is one dimensional
lowerCAmelCase__ : Union[str, Any] = torch.tensor(lowerCAmelCase__ )
elif key_name.endswith('''/g''' ):
lowerCAmelCase__ : int = '''model.blocks.%d.self_attn.norm.weight''' % player
lowerCAmelCase__ : Any = vnp.copy() # same because it is one dimensional
lowerCAmelCase__ : List[Any] = torch.tensor(lowerCAmelCase__ )
elif (
key_name.startswith('''model/wte''' )
or key_name.startswith('''model/wpe''' )
or key_name.startswith('''model/ete''' )
):
lowerCAmelCase__ : int = {'''wte''': '''embed_tokens''', '''wpe''': '''position_embeddings''', '''ete''': '''extra_position_embeddings'''}[
key_name[-3:]
]
lowerCAmelCase__ : Any = '''model.%s.weight''' % nlayer
lowerCAmelCase__ : List[str] = vnp.copy() # same in embedded
lowerCAmelCase__ : List[Any] = torch.tensor(lowerCAmelCase__ )
if key_name.startswith('''model/wte''' ):
lowerCAmelCase__ : Union[str, Any] = '''lm_head.weight'''
lowerCAmelCase__ : Union[str, Any] = vnp.copy() # same in embedded
lowerCAmelCase__ : List[str] = torch.tensor(lowerCAmelCase__ )
elif key_name.startswith('''model/wob''' ):
lowerCAmelCase__ : Tuple = '''final_logits_bias'''
lowerCAmelCase__ : Any = vnp.copy() # same in embedded
lowerCAmelCase__ : Tuple = state.reshape((1, -1) )
lowerCAmelCase__ : Union[str, Any] = torch.tensor(lowerCAmelCase__ )
elif key_name == "model/dense/kernel":
lowerCAmelCase__ : Union[str, Any] = '''model.last_project.weight'''
lowerCAmelCase__ : Dict = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
lowerCAmelCase__ : Optional[Any] = torch.tensor(lowerCAmelCase__ )
elif key_name == "model/dense_1/bias":
lowerCAmelCase__ : Tuple = '''model.last_project.bias'''
lowerCAmelCase__ : List[str] = vnp.copy() # same because it is one dimensional
lowerCAmelCase__ : Union[str, Any] = torch.tensor(lowerCAmelCase__ )
torch.save(lowerCAmelCase__ , args.output )
if __name__ == "__main__":
lowerCAmelCase_ = argparse.ArgumentParser(
description="""model converter.""", formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument("""--tf_model_dir""", metavar="""PATH""", type=str, required=True, help="""import model""")
parser.add_argument("""--output""", metavar="""PATH""", type=str, required=True, help="""output model""")
lowerCAmelCase_ = parser.parse_args()
convert_tf_gptsan_to_pt(args)
| 714 |
from __future__ import annotations
import unittest
from transformers import is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
if is_tf_available():
import numpy as np
import tensorflow as tf
from transformers import TFCamembertModel
@require_tf
@require_sentencepiece
@require_tokenizers
class _lowerCAmelCase ( unittest.TestCase ):
@slow
def __magic_name__( self ):
lowerCAmelCase__ : Optional[Any] = TFCamembertModel.from_pretrained('''jplu/tf-camembert-base''' )
lowerCAmelCase__ : List[str] = tf.convert_to_tensor(
[[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !"
lowerCAmelCase__ : str = model(__UpperCAmelCase )['''last_hidden_state''']
lowerCAmelCase__ : List[Any] = tf.TensorShape((1, 10, 768) )
self.assertEqual(output.shape , __UpperCAmelCase )
# compare the actual values for a slice.
lowerCAmelCase__ : int = tf.convert_to_tensor(
[[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]] , dtype=tf.floataa , )
# camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0')
# camembert.eval()
# expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach()
self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
| 470 | 0 |
from __future__ import annotations
import copy
import inspect
import json
import math
import os
import tempfile
import unittest
from importlib import import_module
import numpy as np
from transformers import ViTMAEConfig
from transformers.file_utils import cached_property, is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, require_vision, slow
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 TFViTMAEForPreTraining, TFViTMAEModel
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class lowerCamelCase_ :
def __init__( self : str , __A : Tuple , __A : Union[str, Any]=13 , __A : Union[str, Any]=30 , __A : Optional[int]=2 , __A : Optional[Any]=3 , __A : Optional[Any]=True , __A : str=True , __A : Dict=32 , __A : List[Any]=2 , __A : Dict=4 , __A : str=37 , __A : Union[str, Any]="gelu" , __A : Optional[Any]=0.1 , __A : Dict=0.1 , __A : List[str]=10 , __A : Optional[Any]=0.0_2 , __A : Optional[int]=3 , __A : Tuple=0.6 , __A : Any=None , ):
__A : int = parent
__A : str = batch_size
__A : List[Any] = image_size
__A : Optional[int] = patch_size
__A : int = num_channels
__A : Tuple = is_training
__A : Optional[int] = use_labels
__A : Union[str, Any] = hidden_size
__A : Dict = num_hidden_layers
__A : Dict = num_attention_heads
__A : int = intermediate_size
__A : Union[str, Any] = hidden_act
__A : Dict = hidden_dropout_prob
__A : List[str] = attention_probs_dropout_prob
__A : Union[str, Any] = type_sequence_label_size
__A : str = initializer_range
__A : Any = mask_ratio
__A : int = scope
# in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
# (we add 1 for the [CLS] token)
__A : str = (image_size // patch_size) ** 2
__A : List[Any] = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) )
def lowerCAmelCase_ ( self : Optional[int] ):
__A : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__A : Union[str, Any] = None
if self.use_labels:
__A : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__A : Union[str, Any] = self.get_config()
return config, pixel_values, labels
def lowerCAmelCase_ ( self : Optional[Any] ):
return ViTMAEConfig(
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 , decoder_hidden_size=self.hidden_size , decoder_num_hidden_layers=self.num_hidden_layers , decoder_num_attention_heads=self.num_attention_heads , decoder_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 , mask_ratio=self.mask_ratio , )
def lowerCAmelCase_ ( self : List[Any] , __A : Tuple , __A : int , __A : Any ):
__A : int = TFViTMAEModel(config=__A )
__A : List[str] = model(__A , training=__A )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def lowerCAmelCase_ ( self : Dict , __A : str , __A : Union[str, Any] , __A : Union[str, Any] ):
__A : Optional[Any] = TFViTMAEForPreTraining(__A )
__A : Optional[Any] = model(__A , training=__A )
# expected sequence length = num_patches
__A : Any = (self.image_size // self.patch_size) ** 2
__A : str = self.patch_size**2 * self.num_channels
self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) )
# test greyscale images
__A : Tuple = 1
__A : Optional[int] = TFViTMAEForPreTraining(__A )
__A : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
__A : List[str] = model(__A , training=__A )
__A : List[str] = self.patch_size**2
self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) )
def lowerCAmelCase_ ( self : Union[str, Any] ):
__A : int = self.prepare_config_and_inputs()
((__A) , (__A) , (__A)) : int = config_and_inputs
__A : Optional[Any] = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_tf
class lowerCamelCase_ ( _lowercase , _lowercase , unittest.TestCase ):
_lowercase : Any = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else ()
_lowercase : Optional[Any] = {'''feature-extraction''': TFViTMAEModel} if is_tf_available() else {}
_lowercase : Optional[int] = False
_lowercase : Optional[int] = False
_lowercase : Tuple = False
_lowercase : List[str] = False
def lowerCAmelCase_ ( self : Tuple ):
__A : Optional[Any] = TFViTMAEModelTester(self )
__A : Optional[Any] = ConfigTester(self , config_class=__A , has_text_modality=__A , hidden_size=37 )
def lowerCAmelCase_ ( self : int ):
self.config_tester.run_common_tests()
@unittest.skip(reason="""ViTMAE does not use inputs_embeds""" )
def lowerCAmelCase_ ( self : List[str] ):
pass
def lowerCAmelCase_ ( self : str ):
__A , __A : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__A : Optional[int] = model_class(__A )
self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) )
__A : Dict = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__A , tf.keras.layers.Layer ) )
def lowerCAmelCase_ ( self : Any ):
__A , __A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__A : int = model_class(__A )
__A : Optional[Any] = inspect.signature(model.call )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__A : Any = [*signature.parameters.keys()]
__A : str = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] , __A )
def lowerCAmelCase_ ( self : str ):
__A : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__A )
def lowerCAmelCase_ ( self : Optional[int] ):
__A : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*__A )
def lowerCAmelCase_ ( self : Tuple ):
# make the mask reproducible
np.random.seed(2 )
__A , __A : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
__A : Union[str, Any] = int((config.image_size // config.patch_size) ** 2 )
__A : Dict = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
for model_class in self.all_model_classes:
__A : str = model_class(__A )
__A : int = self._prepare_for_class(__A , __A )
__A : str = model(__A , noise=__A )
__A : Optional[int] = copy.deepcopy(self._prepare_for_class(__A , __A ) )
__A : Optional[Any] = model(**__A , noise=__A )
__A : int = outputs_dict[0].numpy()
__A : Union[str, Any] = outputs_keywords[0].numpy()
self.assertLess(np.sum(np.abs(output_dict - output_keywords ) ) , 1e-6 )
def lowerCAmelCase_ ( self : int ):
# make the mask reproducible
np.random.seed(2 )
__A , __A : List[str] = self.model_tester.prepare_config_and_inputs_for_common()
__A : str = int((config.image_size // config.patch_size) ** 2 )
__A : Union[str, Any] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
def prepare_numpy_arrays(__A : Union[str, Any] ):
__A : Union[str, Any] = {}
for k, v in inputs_dict.items():
if tf.is_tensor(__A ):
__A : Dict = v.numpy()
else:
__A : str = np.array(__A )
return inputs_np_dict
for model_class in self.all_model_classes:
__A : Dict = model_class(__A )
__A : Optional[Any] = self._prepare_for_class(__A , __A )
__A : Union[str, Any] = prepare_numpy_arrays(__A )
__A : List[str] = model(__A , noise=__A )
__A : Union[str, Any] = model(**__A , noise=__A )
self.assert_outputs_same(__A , __A )
def lowerCAmelCase_ ( self : Dict , __A : Union[str, Any] , __A : Union[str, Any] , __A : Dict ):
# make masks reproducible
np.random.seed(2 )
__A : Tuple = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2 )
__A : List[str] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
__A : Optional[Any] = tf.constant(__A )
# Add `noise` argument.
# PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
__A : List[Any] = tf_noise
super().check_pt_tf_models(__A , __A , __A )
def lowerCAmelCase_ ( self : Dict ):
# make mask reproducible
np.random.seed(2 )
__A , __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
__A : Optional[int] = {
module_member
for model_class in self.all_model_classes
for module in (import_module(model_class.__module__ ),)
for module_member_name in dir(__A )
if module_member_name.endswith("""MainLayer""" )
# This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`.
and module_member_name[: -len("""MainLayer""" )] == model_class.__name__[: -len("""Model""" )]
for module_member in (getattr(__A , __A ),)
if isinstance(__A , __A )
and tf.keras.layers.Layer in module_member.__bases__
and getattr(__A , """_keras_serializable""" , __A )
}
__A : Optional[int] = int((config.image_size // config.patch_size) ** 2 )
__A : Optional[Any] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
__A : List[str] = tf.convert_to_tensor(__A )
inputs_dict.update({"""noise""": noise} )
for main_layer_class in tf_main_layer_classes:
__A : Union[str, Any] = main_layer_class(__A )
__A : Tuple = {
name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype ) for name, tensor in inputs_dict.items()
}
__A : List[str] = tf.keras.Model(__A , outputs=main_layer(__A ) )
__A : Union[str, Any] = model(__A )
with tempfile.TemporaryDirectory() as tmpdirname:
__A : List[str] = os.path.join(__A , """keras_model.h5""" )
model.save(__A )
__A : List[Any] = tf.keras.models.load_model(
__A , custom_objects={main_layer_class.__name__: main_layer_class} )
assert isinstance(__A , tf.keras.Model )
__A : str = model(__A )
self.assert_outputs_same(__A , __A )
@slow
def lowerCAmelCase_ ( self : Union[str, Any] ):
# make mask reproducible
np.random.seed(2 )
__A , __A : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
__A : List[str] = int((config.image_size // config.patch_size) ** 2 )
__A : Optional[int] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
for model_class in self.all_model_classes:
__A : Any = model_class(__A )
__A : Dict = self._prepare_for_class(__A , __A )
__A : Optional[Any] = model(__A , noise=__A )
if model_class.__name__ == "TFViTMAEModel":
__A : List[str] = outputs.last_hidden_state.numpy()
__A : Optional[Any] = 0
else:
__A : List[str] = outputs.logits.numpy()
__A : List[str] = 0
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(__A , saved_model=__A )
__A : List[str] = model_class.from_pretrained(__A )
__A : str = model(__A , noise=__A )
if model_class.__name__ == "TFViTMAEModel":
__A : Dict = after_outputs["""last_hidden_state"""].numpy()
__A : List[str] = 0
else:
__A : Optional[int] = after_outputs["""logits"""].numpy()
__A : Dict = 0
__A : Optional[int] = np.amax(np.abs(out_a - out_a ) )
self.assertLessEqual(__A , 1e-5 )
def lowerCAmelCase_ ( self : Union[str, Any] ):
# make mask reproducible
np.random.seed(2 )
__A , __A : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
__A : List[str] = int((config.image_size // config.patch_size) ** 2 )
__A : Tuple = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
for model_class in self.all_model_classes:
__A : Tuple = model_class(__A )
__A : Optional[int] = self._prepare_for_class(__A , __A )
__A : Tuple = model(__A , noise=__A )
__A : int = model.get_config()
# make sure that returned config is jsonifiable, which is required by keras
json.dumps(__A )
__A : Dict = model_class.from_config(model.get_config() )
# make sure it also accepts a normal config
__A : Tuple = model_class.from_config(model.config )
__A : Union[str, Any] = new_model(__A ) # Build model
new_model.set_weights(model.get_weights() )
__A : Optional[int] = new_model(__A , noise=__A )
self.assert_outputs_same(__A , __A )
@unittest.skip(
reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
to get deterministic results.""" )
def lowerCAmelCase_ ( self : Optional[int] ):
pass
@unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" )
def lowerCAmelCase_ ( self : int ):
pass
@slow
def lowerCAmelCase_ ( self : Optional[Any] ):
__A : Dict = TFViTMAEModel.from_pretrained("""google/vit-base-patch16-224""" )
self.assertIsNotNone(__A )
def __SCREAMING_SNAKE_CASE ( ) -> Optional[Any]:
__A : Any = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
return image
@require_tf
@require_vision
class lowerCamelCase_ ( unittest.TestCase ):
@cached_property
def lowerCAmelCase_ ( self : int ):
return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None
@slow
def lowerCAmelCase_ ( self : int ):
# make random mask reproducible across the PT and TF model
np.random.seed(2 )
__A : List[Any] = TFViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" )
__A : List[Any] = self.default_image_processor
__A : Union[str, Any] = prepare_img()
__A : Union[str, Any] = image_processor(images=__A , return_tensors="""tf""" )
# prepare a noise vector that will be also used for testing the TF model
# (this way we can ensure that the PT and TF models operate on the same inputs)
__A : Dict = ViTMAEConfig()
__A : List[str] = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 )
__A : List[Any] = np.random.uniform(size=(1, num_patches) )
# forward pass
__A : int = model(**__A , noise=__A )
# verify the logits
__A : Optional[Any] = tf.convert_to_tensor([1, 196, 768] )
self.assertEqual(outputs.logits.shape , __A )
__A : Optional[Any] = tf.convert_to_tensor(
[[-0.0_5_4_8, -1.7_0_2_3, -0.9_3_2_5], [0.3_7_2_1, -0.5_6_7_0, -0.2_2_3_3], [0.8_2_3_5, -1.3_8_7_8, -0.3_5_2_4]] )
tf.debugging.assert_near(outputs.logits[0, :3, :3] , __A , atol=1e-4 )
| 17 |
"""simple docstring"""
import qiskit
def __snake_case ( __A ,__A ) -> qiskit.result.counts.Counts:
lowercase : List[Any] = qiskit.Aer.get_backend("""aer_simulator""" )
lowercase : int = qiskit.QuantumCircuit(4 ,2 )
# encode inputs in qubits 0 and 1
if bita == 1:
qc_ha.x(0 )
if bita == 1:
qc_ha.x(1 )
qc_ha.barrier()
# use cnots to write XOR of the inputs on qubit2
qc_ha.cx(0 ,2 )
qc_ha.cx(1 ,2 )
# use ccx / toffoli gate to write AND of the inputs on qubit3
qc_ha.ccx(0 ,1 ,3 )
qc_ha.barrier()
# extract outputs
qc_ha.measure(2 ,0 ) # extract XOR value
qc_ha.measure(3 ,1 ) # extract AND value
# Execute the circuit on the qasm simulator
lowercase : Any = qiskit.execute(__A ,__A ,shots=1000 )
# Return the histogram data of the results of the experiment
return job.result().get_counts(__A )
if __name__ == "__main__":
lowerCAmelCase: Optional[Any] =half_adder(1, 1)
print(F'Half Adder Output Qubit Counts: {counts}')
| 607 | 0 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
snake_case_ = logging.get_logger(__name__)
snake_case_ = {
'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json',
'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json',
'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json',
'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json',
'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json',
'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json',
'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json',
'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json',
'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json',
}
class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ):
_A = "xmod"
def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ):
"""simple docstring"""
super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ )
SCREAMING_SNAKE_CASE_ : Tuple = vocab_size
SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size
SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers
SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads
SCREAMING_SNAKE_CASE_ : List[str] = hidden_act
SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size
SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings
SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size
SCREAMING_SNAKE_CASE_ : str = initializer_range
SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps
SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type
SCREAMING_SNAKE_CASE_ : str = use_cache
SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout
SCREAMING_SNAKE_CASE_ : int = pre_norm
SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor
SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm
SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm
SCREAMING_SNAKE_CASE_ : int = ln_before_adapter
SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ )
SCREAMING_SNAKE_CASE_ : Any = default_language
class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ):
@property
def __lowerCamelCase ( self ):
"""simple docstring"""
if self.task == "multiple-choice":
SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"}
else:
SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
] )
| 701 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
snake_case_ = logging.get_logger(__name__)
snake_case_ = {
'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json',
'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json',
'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json',
'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json',
'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json',
'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json',
'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json',
'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json',
'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json',
}
class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ):
_A = "xmod"
def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ):
"""simple docstring"""
super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ )
SCREAMING_SNAKE_CASE_ : Tuple = vocab_size
SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size
SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers
SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads
SCREAMING_SNAKE_CASE_ : List[str] = hidden_act
SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size
SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings
SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size
SCREAMING_SNAKE_CASE_ : str = initializer_range
SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps
SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type
SCREAMING_SNAKE_CASE_ : str = use_cache
SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout
SCREAMING_SNAKE_CASE_ : int = pre_norm
SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor
SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm
SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm
SCREAMING_SNAKE_CASE_ : int = ln_before_adapter
SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ )
SCREAMING_SNAKE_CASE_ : Any = default_language
class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ):
@property
def __lowerCamelCase ( self ):
"""simple docstring"""
if self.task == "multiple-choice":
SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"}
else:
SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
] )
| 68 | 0 |
import gc
import inspect
import unittest
import torch
from parameterized import parameterized
from diffusers import PriorTransformer
from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device
from diffusers.utils.testing_utils import enable_full_determinism
from .test_modeling_common import ModelTesterMixin
enable_full_determinism()
class __lowercase (__SCREAMING_SNAKE_CASE , unittest.TestCase ):
"""simple docstring"""
_UpperCAmelCase = PriorTransformer
_UpperCAmelCase = """hidden_states"""
@property
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Tuple = 4
SCREAMING_SNAKE_CASE_ : int = 8
SCREAMING_SNAKE_CASE_ : Optional[Any] = 7
SCREAMING_SNAKE_CASE_ : List[str] = floats_tensor((batch_size, embedding_dim) ).to(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Optional[int] = floats_tensor((batch_size, embedding_dim) ).to(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : str = floats_tensor((batch_size, num_embeddings, embedding_dim) ).to(lowerCAmelCase__ )
return {
"hidden_states": hidden_states,
"timestep": 2,
"proj_embedding": proj_embedding,
"encoder_hidden_states": encoder_hidden_states,
}
def UpperCamelCase__ ( self , lowerCAmelCase__=0 ):
"""simple docstring"""
torch.manual_seed(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4
SCREAMING_SNAKE_CASE_ : Tuple = 8
SCREAMING_SNAKE_CASE_ : List[str] = 7
SCREAMING_SNAKE_CASE_ : str = torch.randn((batch_size, embedding_dim) ).to(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Dict = torch.randn((batch_size, embedding_dim) ).to(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Optional[int] = torch.randn((batch_size, num_embeddings, embedding_dim) ).to(lowerCAmelCase__ )
return {
"hidden_states": hidden_states,
"timestep": 2,
"proj_embedding": proj_embedding,
"encoder_hidden_states": encoder_hidden_states,
}
@property
def UpperCamelCase__ ( self ):
"""simple docstring"""
return (4, 8)
@property
def UpperCamelCase__ ( self ):
"""simple docstring"""
return (4, 8)
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[int] = {
'num_attention_heads': 2,
'attention_head_dim': 4,
'num_layers': 2,
'embedding_dim': 8,
'num_embeddings': 7,
'additional_embeddings': 4,
}
SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.dummy_input
return init_dict, inputs_dict
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = PriorTransformer.from_pretrained(
'hf-internal-testing/prior-dummy' , output_loading_info=lowerCAmelCase__ )
self.assertIsNotNone(lowerCAmelCase__ )
self.assertEqual(len(loading_info['missing_keys'] ) , 0 )
model.to(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(**self.dummy_input )[0]
assert hidden_states is not None, "Make sure output is not None"
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = self.prepare_init_args_and_inputs_for_common()
SCREAMING_SNAKE_CASE_ : List[Any] = self.model_class(**lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Dict = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
SCREAMING_SNAKE_CASE_ : Any = [*signature.parameters.keys()]
SCREAMING_SNAKE_CASE_ : Optional[Any] = ['hidden_states', 'timestep']
self.assertListEqual(arg_names[:2] , lowerCAmelCase__ )
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str = PriorTransformer.from_pretrained('hf-internal-testing/prior-dummy' )
SCREAMING_SNAKE_CASE_ : Tuple = model.to(lowerCAmelCase__ )
if hasattr(lowerCAmelCase__ , 'set_default_attn_processor' ):
model.set_default_attn_processor()
SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_dummy_seed_input()
with torch.no_grad():
SCREAMING_SNAKE_CASE_ : List[str] = model(**lowerCAmelCase__ )[0]
SCREAMING_SNAKE_CASE_ : List[str] = output[0, :5].flatten().cpu()
print(lowerCAmelCase__ )
# Since the VAE Gaussian prior's generator is seeded on the appropriate device,
# the expected output slices are not the same for CPU and GPU.
SCREAMING_SNAKE_CASE_ : List[str] = torch.tensor([-1.3_436, -0.2_870, 0.7_538, 0.4_368, -0.0_239] )
self.assertTrue(torch_all_close(lowerCAmelCase__ , lowerCAmelCase__ , rtol=1E-2 ) )
@slow
class __lowercase (unittest.TestCase ):
"""simple docstring"""
def UpperCamelCase__ ( self , lowerCAmelCase__=1 , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=7_7 , lowerCAmelCase__=0 ):
"""simple docstring"""
torch.manual_seed(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : List[str] = batch_size
SCREAMING_SNAKE_CASE_ : List[str] = embedding_dim
SCREAMING_SNAKE_CASE_ : Dict = num_embeddings
SCREAMING_SNAKE_CASE_ : Tuple = torch.randn((batch_size, embedding_dim) ).to(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Any = torch.randn((batch_size, embedding_dim) ).to(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Optional[int] = torch.randn((batch_size, num_embeddings, embedding_dim) ).to(lowerCAmelCase__ )
return {
"hidden_states": hidden_states,
"timestep": 2,
"proj_embedding": proj_embedding,
"encoder_hidden_states": encoder_hidden_states,
}
def UpperCamelCase__ ( self ):
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@parameterized.expand(
[
# fmt: off
[1_3, [-0.5_861, 0.1_283, -0.0_931, 0.0_882, 0.4_476, 0.1_329, -0.0_498, 0.0_640]],
[3_7, [-0.4_913, 0.0_110, -0.0_483, 0.0_541, 0.4_954, -0.0_170, 0.0_354, 0.1_651]],
# fmt: on
] )
def UpperCamelCase__ ( self , lowerCAmelCase__ , lowerCAmelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : int = PriorTransformer.from_pretrained('kandinsky-community/kandinsky-2-1-prior' , subfolder='prior' )
model.to(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_dummy_seed_input(seed=lowerCAmelCase__ )
with torch.no_grad():
SCREAMING_SNAKE_CASE_ : str = model(**lowerCAmelCase__ )[0]
assert list(sample.shape ) == [1, 7_6_8]
SCREAMING_SNAKE_CASE_ : Optional[Any] = sample[0, :8].flatten().cpu()
print(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : List[Any] = torch.tensor(lowerCAmelCase__ )
assert torch_all_close(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 )
| 101 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowerCamelCase : Dict = logging.get_logger(__name__)
_lowerCamelCase : Union[str, Any] = {
"funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/config.json",
"funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json",
"funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/config.json",
"funnel-transformer/medium-base": "https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json",
"funnel-transformer/intermediate": (
"https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json"
),
"funnel-transformer/intermediate-base": (
"https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json"
),
"funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/config.json",
"funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json",
"funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json",
"funnel-transformer/xlarge-base": "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json",
}
class __snake_case (_a ):
lowerCAmelCase__ = "funnel"
lowerCAmelCase__ = {
"hidden_size": "d_model",
"num_attention_heads": "n_head",
}
def __init__( self : Tuple , _UpperCAmelCase : Dict=3_0522 , _UpperCAmelCase : List[str]=[4, 4, 4] , _UpperCAmelCase : Union[str, Any]=None , _UpperCAmelCase : Optional[Any]=2 , _UpperCAmelCase : Union[str, Any]=768 , _UpperCAmelCase : List[str]=12 , _UpperCAmelCase : List[Any]=64 , _UpperCAmelCase : List[str]=3072 , _UpperCAmelCase : List[str]="gelu_new" , _UpperCAmelCase : List[Any]=0.1 , _UpperCAmelCase : Any=0.1 , _UpperCAmelCase : Any=0.0 , _UpperCAmelCase : Optional[int]=0.1 , _UpperCAmelCase : Dict=None , _UpperCAmelCase : Tuple=1E-9 , _UpperCAmelCase : Dict="mean" , _UpperCAmelCase : Any="relative_shift" , _UpperCAmelCase : Any=True , _UpperCAmelCase : int=True , _UpperCAmelCase : Dict=True , **_UpperCAmelCase : Optional[int] , ) -> List[str]:
'''simple docstring'''
_lowerCAmelCase : Optional[int] = vocab_size
_lowerCAmelCase : Dict = block_sizes
_lowerCAmelCase : Optional[int] = [1] * len(_UpperCAmelCase ) if block_repeats is None else block_repeats
assert len(_UpperCAmelCase ) == len(
self.block_repeats ), "`block_sizes` and `block_repeats` should have the same length."
_lowerCAmelCase : Any = num_decoder_layers
_lowerCAmelCase : List[Any] = d_model
_lowerCAmelCase : Optional[int] = n_head
_lowerCAmelCase : Optional[int] = d_head
_lowerCAmelCase : int = d_inner
_lowerCAmelCase : int = hidden_act
_lowerCAmelCase : Dict = hidden_dropout
_lowerCAmelCase : Tuple = attention_dropout
_lowerCAmelCase : Optional[Any] = activation_dropout
_lowerCAmelCase : Tuple = initializer_range
_lowerCAmelCase : Optional[Any] = initializer_std
_lowerCAmelCase : Dict = layer_norm_eps
assert pooling_type in [
"mean",
"max",
], f"Got {pooling_type} for `pooling_type` but only 'mean' and 'max' are supported."
_lowerCAmelCase : Any = pooling_type
assert attention_type in [
"relative_shift",
"factorized",
], f"Got {attention_type} for `attention_type` but only 'relative_shift' and 'factorized' are supported."
_lowerCAmelCase : List[Any] = attention_type
_lowerCAmelCase : Any = separate_cls
_lowerCAmelCase : int = truncate_seq
_lowerCAmelCase : List[Any] = pool_q_only
super().__init__(**_UpperCAmelCase )
@property
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]:
'''simple docstring'''
return sum(self.block_sizes )
@num_hidden_layers.setter
def SCREAMING_SNAKE_CASE ( self : int , _UpperCAmelCase : Dict ) -> Dict:
'''simple docstring'''
raise NotImplementedError(
"""This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.""" )
@property
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str:
'''simple docstring'''
return len(self.block_sizes )
@num_blocks.setter
def SCREAMING_SNAKE_CASE ( self : Optional[Any] , _UpperCAmelCase : Any ) -> Optional[Any]:
'''simple docstring'''
raise NotImplementedError("""This model does not support the setting of `num_blocks`. Please set `block_sizes`.""" )
| 429 | 0 |
'''simple docstring'''
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
# @@protoc_insertion_point(imports)
lowercase : Tuple = _symbol_database.Default()
lowercase : Tuple = _descriptor_pool.Default().AddSerializedFile(
B'''\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03'''
)
lowercase : str = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, '''sentencepiece_model_pb2''', _globals)
if _descriptor._USE_C_DESCRIPTORS is False:
lowercase : Optional[Any] = None
lowercase : Union[str, Any] = B"""H\003"""
# (generated by protobuf compiler, but `_TRAINERSPEC` is not defined)
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001"
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001"
lowercase : List[Any] = 45
lowercase : Union[str, Any] = 15_81
lowercase : List[str] = 15_17
lowercase : Tuple = 15_70
lowercase : int = 15_84
lowercase : str = 17_93
lowercase : int = 17_95
lowercase : List[Any] = 19_16
lowercase : int = 18_64
lowercase : List[str] = 19_05
lowercase : Dict = 19_19
lowercase : Tuple = 24_29
lowercase : List[Any] = 22_08
lowercase : List[Any] = 24_18
lowercase : List[str] = 23_23
lowercase : str = 24_07
# @@protoc_insertion_point(module_scope)
| 721 |
def lowerCAmelCase__ ( _a : str , _a : int ):
# "extended trapezoidal rule"
# int(f) = dx/2 * (f1 + 2f2 + ... + fn)
snake_case_ : Optional[Any] = (boundary[1] - boundary[0]) / steps
snake_case_ : str = boundary[0]
snake_case_ : Dict = boundary[1]
snake_case_ : str = make_points(_a , _a , _a )
snake_case_ : str = 0.0
y += (h / 2.0) * f(_a )
for i in x_i:
# print(i)
y += h * f(_a )
y += (h / 2.0) * f(_a )
return y
def lowerCAmelCase__ ( _a : str , _a : Optional[Any] , _a : Tuple ):
snake_case_ : Tuple = a + h
while x < (b - h):
yield x
snake_case_ : List[str] = x + h
def lowerCAmelCase__ ( _a : Tuple ): # enter your function here
snake_case_ : Tuple = (x - 0) * (x - 0)
return y
def lowerCAmelCase__ ( ):
snake_case_ : Union[str, Any] = 0.0 # Lower bound of integration
snake_case_ : List[Any] = 1.0 # Upper bound of integration
snake_case_ : Tuple = 10.0 # define number of steps or resolution
snake_case_ : List[Any] = [a, b] # define boundary of integration
snake_case_ : Any = method_a(_a , _a )
print(F'''y = {y}''' )
if __name__ == "__main__":
main()
| 114 | 0 |
import unittest
import numpy as np
import torch
from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device
enable_full_determinism()
class __UpperCamelCase ( unittest.TestCase ):
@property
def _a ( self : List[Any] ) -> str:
"""simple docstring"""
torch.manual_seed(0 )
__lowercase = UNetaDModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , )
return model
def _a ( self : Dict ) -> Optional[Any]:
"""simple docstring"""
__lowercase = self.dummy_uncond_unet
__lowercase = PNDMScheduler()
__lowercase = PNDMPipeline(unet=_lowerCAmelCase , scheduler=_lowerCAmelCase )
pndm.to(_lowerCAmelCase )
pndm.set_progress_bar_config(disable=_lowerCAmelCase )
__lowercase = torch.manual_seed(0 )
__lowercase = pndm(generator=_lowerCAmelCase , num_inference_steps=20 , output_type="""numpy""" ).images
__lowercase = torch.manual_seed(0 )
__lowercase = pndm(generator=_lowerCAmelCase , num_inference_steps=20 , output_type="""numpy""" , return_dict=_lowerCAmelCase )[0]
__lowercase = image[0, -3:, -3:, -1]
__lowercase = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
__lowercase = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
@slow
@require_torch
class __UpperCamelCase ( unittest.TestCase ):
def _a ( self : int ) -> List[str]:
"""simple docstring"""
__lowercase = """google/ddpm-cifar10-32"""
__lowercase = UNetaDModel.from_pretrained(_lowerCAmelCase )
__lowercase = PNDMScheduler()
__lowercase = PNDMPipeline(unet=_lowerCAmelCase , scheduler=_lowerCAmelCase )
pndm.to(_lowerCAmelCase )
pndm.set_progress_bar_config(disable=_lowerCAmelCase )
__lowercase = torch.manual_seed(0 )
__lowercase = pndm(generator=_lowerCAmelCase , output_type="""numpy""" ).images
__lowercase = image[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
__lowercase = np.array([0.1_564, 0.14_645, 0.1_406, 0.14_715, 0.12_425, 0.14_045, 0.13_115, 0.12_175, 0.125] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
| 80 |
import collections
import inspect
import unittest
from typing import Dict, List, Tuple
from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available
from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import MaskFormerSwinBackbone
from transformers.models.maskformer import MaskFormerSwinModel
class __UpperCamelCase :
def __init__( self : Optional[int] , _lowerCAmelCase : int , _lowerCAmelCase : Optional[int]=13 , _lowerCAmelCase : Any=32 , _lowerCAmelCase : Optional[Any]=2 , _lowerCAmelCase : Union[str, Any]=3 , _lowerCAmelCase : List[str]=16 , _lowerCAmelCase : List[str]=[1, 2, 1] , _lowerCAmelCase : Dict=[2, 2, 4] , _lowerCAmelCase : Optional[int]=2 , _lowerCAmelCase : Optional[Any]=2.0 , _lowerCAmelCase : List[str]=True , _lowerCAmelCase : Optional[int]=0.0 , _lowerCAmelCase : Any=0.0 , _lowerCAmelCase : Optional[int]=0.1 , _lowerCAmelCase : Tuple="gelu" , _lowerCAmelCase : int=False , _lowerCAmelCase : Dict=True , _lowerCAmelCase : List[str]=0.02 , _lowerCAmelCase : Union[str, Any]=1e-5 , _lowerCAmelCase : Tuple=True , _lowerCAmelCase : Dict=None , _lowerCAmelCase : List[str]=True , _lowerCAmelCase : List[Any]=10 , _lowerCAmelCase : Tuple=8 , _lowerCAmelCase : List[Any]=["stage1", "stage2", "stage3"] , _lowerCAmelCase : Union[str, Any]=[1, 2, 3] , ) -> int:
"""simple docstring"""
__lowercase = parent
__lowercase = batch_size
__lowercase = image_size
__lowercase = patch_size
__lowercase = num_channels
__lowercase = embed_dim
__lowercase = depths
__lowercase = num_heads
__lowercase = window_size
__lowercase = mlp_ratio
__lowercase = qkv_bias
__lowercase = hidden_dropout_prob
__lowercase = attention_probs_dropout_prob
__lowercase = drop_path_rate
__lowercase = hidden_act
__lowercase = use_absolute_embeddings
__lowercase = patch_norm
__lowercase = layer_norm_eps
__lowercase = initializer_range
__lowercase = is_training
__lowercase = scope
__lowercase = use_labels
__lowercase = type_sequence_label_size
__lowercase = encoder_stride
__lowercase = out_features
__lowercase = out_indices
def _a ( self : List[Any] ) -> int:
"""simple docstring"""
__lowercase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__lowercase = None
if self.use_labels:
__lowercase = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__lowercase = self.get_config()
return config, pixel_values, labels
def _a ( self : Dict ) -> Dict:
"""simple docstring"""
return MaskFormerSwinConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , )
def _a ( self : List[str] , _lowerCAmelCase : Dict , _lowerCAmelCase : str , _lowerCAmelCase : int ) -> Dict:
"""simple docstring"""
__lowercase = MaskFormerSwinModel(config=_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.eval()
__lowercase = model(_lowerCAmelCase )
__lowercase = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
__lowercase = int(config.embed_dim * 2 ** (len(config.depths ) - 1) )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) )
def _a ( self : Optional[Any] , _lowerCAmelCase : Tuple , _lowerCAmelCase : List[str] , _lowerCAmelCase : Optional[int] ) -> List[Any]:
"""simple docstring"""
__lowercase = MaskFormerSwinBackbone(config=_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.eval()
__lowercase = model(_lowerCAmelCase )
# verify feature maps
self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) )
self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] )
# verify channels
self.parent.assertEqual(len(model.channels ) , len(config.out_features ) )
self.parent.assertListEqual(model.channels , [16, 32, 64] )
# verify ValueError
with self.parent.assertRaises(_lowerCAmelCase ):
__lowercase = ["""stem"""]
__lowercase = MaskFormerSwinBackbone(config=_lowerCAmelCase )
def _a ( self : Dict ) -> Tuple:
"""simple docstring"""
__lowercase = self.prepare_config_and_inputs()
__lowercase , __lowercase , __lowercase = config_and_inputs
__lowercase = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_torch
class __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ):
__snake_case :Any = (
(
MaskFormerSwinModel,
MaskFormerSwinBackbone,
)
if is_torch_available()
else ()
)
__snake_case :Optional[int] = {'feature-extraction': MaskFormerSwinModel} if is_torch_available() else {}
__snake_case :Optional[int] = False
__snake_case :Any = False
__snake_case :List[str] = False
__snake_case :Tuple = False
__snake_case :Optional[int] = False
def _a ( self : Tuple ) -> Optional[int]:
"""simple docstring"""
__lowercase = MaskFormerSwinModelTester(self )
__lowercase = ConfigTester(self , config_class=_lowerCAmelCase , embed_dim=37 )
@require_torch_multi_gpu
@unittest.skip(
reason=(
"""`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with"""
""" `nn.DataParallel`"""
) )
def _a ( self : List[str] ) -> List[str]:
"""simple docstring"""
pass
def _a ( self : Dict ) -> Optional[int]:
"""simple docstring"""
self.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def _a ( self : List[Any] ) -> Any:
"""simple docstring"""
return
def _a ( self : Any ) -> Tuple:
"""simple docstring"""
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_lowerCAmelCase )
def _a ( self : Optional[int] ) -> str:
"""simple docstring"""
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_backbone(*_lowerCAmelCase )
@unittest.skip("""Swin does not use inputs_embeds""" )
def _a ( self : Tuple ) -> Any:
"""simple docstring"""
pass
@unittest.skip("""Swin does not support feedforward chunking""" )
def _a ( self : Tuple ) -> str:
"""simple docstring"""
pass
def _a ( self : List[Any] ) -> Optional[int]:
"""simple docstring"""
__lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__lowercase = model_class(_lowerCAmelCase )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
__lowercase = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(_lowerCAmelCase , nn.Linear ) )
def _a ( self : Dict ) -> Dict:
"""simple docstring"""
__lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__lowercase = model_class(_lowerCAmelCase )
__lowercase = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__lowercase = [*signature.parameters.keys()]
__lowercase = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] , _lowerCAmelCase )
@unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions""" )
def _a ( self : Optional[int] ) -> int:
"""simple docstring"""
pass
@unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone""" )
def _a ( self : Any ) -> Any:
"""simple docstring"""
pass
def _a ( self : Tuple , _lowerCAmelCase : Any , _lowerCAmelCase : Any , _lowerCAmelCase : int , _lowerCAmelCase : Any ) -> Dict:
"""simple docstring"""
__lowercase = model_class(_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.eval()
with torch.no_grad():
__lowercase = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) )
__lowercase = outputs.hidden_states
__lowercase = getattr(
self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 )
self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase )
# Swin has a different seq_length
__lowercase = (
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
__lowercase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , )
def _a ( self : str ) -> Optional[Any]:
"""simple docstring"""
__lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common()
__lowercase = (
self.model_tester.image_size
if isinstance(self.model_tester.image_size , collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
for model_class in self.all_model_classes:
__lowercase = True
self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__lowercase = True
self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
def _a ( self : Dict ) -> Tuple:
"""simple docstring"""
__lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common()
__lowercase = 3
__lowercase = (
self.model_tester.image_size
if isinstance(self.model_tester.image_size , collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
__lowercase = (
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
__lowercase = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
__lowercase = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
for model_class in self.all_model_classes:
__lowercase = True
self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , (padded_height, padded_width) )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__lowercase = True
self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , (padded_height, padded_width) )
@unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints""" )
def _a ( self : Tuple ) -> Any:
"""simple docstring"""
pass
@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" )
def _a ( self : Any ) -> str:
"""simple docstring"""
pass
@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" )
def _a ( self : Union[str, Any] ) -> List[Any]:
"""simple docstring"""
pass
def _a ( self : Any ) -> Union[str, Any]:
"""simple docstring"""
__lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common()
def set_nan_tensor_to_zero(_lowerCAmelCase : Optional[int] ):
__lowercase = 0
return t
def check_equivalence(_lowerCAmelCase : int , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : List[str] , _lowerCAmelCase : Optional[int]={} ):
with torch.no_grad():
__lowercase = model(**_lowerCAmelCase , return_dict=_lowerCAmelCase , **_lowerCAmelCase )
__lowercase = model(**_lowerCAmelCase , return_dict=_lowerCAmelCase , **_lowerCAmelCase ).to_tuple()
def recursive_check(_lowerCAmelCase : Optional[Any] , _lowerCAmelCase : List[Any] ):
if isinstance(_lowerCAmelCase , (List, Tuple) ):
for tuple_iterable_value, dict_iterable_value in zip(_lowerCAmelCase , _lowerCAmelCase ):
recursive_check(_lowerCAmelCase , _lowerCAmelCase )
elif isinstance(_lowerCAmelCase , _lowerCAmelCase ):
for tuple_iterable_value, dict_iterable_value in zip(
tuple_object.values() , dict_object.values() ):
recursive_check(_lowerCAmelCase , _lowerCAmelCase )
elif tuple_object is None:
return
else:
self.assertTrue(
torch.allclose(
set_nan_tensor_to_zero(_lowerCAmelCase ) , set_nan_tensor_to_zero(_lowerCAmelCase ) , atol=1e-5 ) , msg=(
"""Tuple and dict output are not equal. Difference:"""
F' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:'
F' {torch.isnan(_lowerCAmelCase ).any()} and `inf`: {torch.isinf(_lowerCAmelCase )}. Dict has'
F' `nan`: {torch.isnan(_lowerCAmelCase ).any()} and `inf`: {torch.isinf(_lowerCAmelCase )}.'
) , )
recursive_check(_lowerCAmelCase , _lowerCAmelCase )
for model_class in self.all_model_classes:
__lowercase = model_class(_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.eval()
__lowercase = self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase )
__lowercase = self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase )
check_equivalence(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
__lowercase = self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase , return_labels=_lowerCAmelCase )
__lowercase = self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase , return_labels=_lowerCAmelCase )
check_equivalence(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
__lowercase = self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase )
__lowercase = self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase )
check_equivalence(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , {"""output_hidden_states""": True} )
__lowercase = self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase , return_labels=_lowerCAmelCase )
__lowercase = self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase , return_labels=_lowerCAmelCase )
check_equivalence(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , {"""output_hidden_states""": True} )
@require_torch
class __UpperCamelCase ( unittest.TestCase , _lowerCAmelCase ):
__snake_case :Optional[Any] = (MaskFormerSwinBackbone,) if is_torch_available() else ()
__snake_case :Dict = MaskFormerSwinConfig
def _a ( self : Union[str, Any] ) -> List[str]:
"""simple docstring"""
__lowercase = MaskFormerSwinModelTester(self )
def _a ( self : List[Any] ) -> Dict:
"""simple docstring"""
__lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common()
__lowercase = inputs_dict["""pixel_values"""].shape[0]
for backbone_class in self.all_model_classes:
__lowercase = backbone_class(_lowerCAmelCase )
backbone.to(_lowerCAmelCase )
backbone.eval()
__lowercase = backbone(**_lowerCAmelCase )
# Test default outputs and verify feature maps
self.assertIsInstance(outputs.feature_maps , _lowerCAmelCase )
self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) )
for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ):
self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) )
self.assertIsNone(outputs.hidden_states )
self.assertIsNone(outputs.attentions )
# Test output_hidden_states=True
__lowercase = backbone(**_lowerCAmelCase , output_hidden_states=_lowerCAmelCase )
self.assertIsNotNone(outputs.hidden_states )
self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) )
# We skip the stem layer
for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ):
for hidden_state in hidden_states:
# Hidden states are in the format (batch_size, (height * width), n_channels)
__lowercase , __lowercase , __lowercase = hidden_state.shape
self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) )
# Test output_attentions=True
if self.has_attentions:
__lowercase = backbone(**_lowerCAmelCase , output_attentions=_lowerCAmelCase )
self.assertIsNotNone(outputs.attentions )
| 80 | 1 |
'''simple docstring'''
def __lowerCamelCase ( __lowerCAmelCase : int , __lowerCAmelCase : float , __lowerCAmelCase : float ) -> float:
return round(float(moles / volume ) * nfactor )
def __lowerCamelCase ( __lowerCAmelCase : float , __lowerCAmelCase : float , __lowerCAmelCase : float ) -> float:
return round(float((moles * 0.0821 * temperature) / (volume) ) )
def __lowerCamelCase ( __lowerCAmelCase : float , __lowerCAmelCase : float , __lowerCAmelCase : float ) -> float:
return round(float((moles * 0.0821 * temperature) / (pressure) ) )
def __lowerCamelCase ( __lowerCAmelCase : float , __lowerCAmelCase : float , __lowerCAmelCase : float ) -> float:
return round(float((pressure * volume) / (0.0821 * moles) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 517 |
'''simple docstring'''
import os
import sys
from contextlib import contextmanager
# Windows only
if os.name == "nt":
import ctypes
import msvcrt # noqa
class _lowerCAmelCase ( ctypes.Structure ):
"""simple docstring"""
snake_case_ = [("size", ctypes.c_int), ("visible", ctypes.c_byte)]
def __lowerCamelCase ( ) -> Optional[int]:
if os.name == "nt":
snake_case = CursorInfo()
snake_case = ctypes.windll.kernelaa.GetStdHandle(-11 )
ctypes.windll.kernelaa.GetConsoleCursorInfo(__lowerCAmelCase , ctypes.byref(__lowerCAmelCase ) )
snake_case = False
ctypes.windll.kernelaa.SetConsoleCursorInfo(__lowerCAmelCase , ctypes.byref(__lowerCAmelCase ) )
elif os.name == "posix":
sys.stdout.write("""\033[?25l""" )
sys.stdout.flush()
def __lowerCamelCase ( ) -> Tuple:
if os.name == "nt":
snake_case = CursorInfo()
snake_case = ctypes.windll.kernelaa.GetStdHandle(-11 )
ctypes.windll.kernelaa.GetConsoleCursorInfo(__lowerCAmelCase , ctypes.byref(__lowerCAmelCase ) )
snake_case = True
ctypes.windll.kernelaa.SetConsoleCursorInfo(__lowerCAmelCase , ctypes.byref(__lowerCAmelCase ) )
elif os.name == "posix":
sys.stdout.write("""\033[?25h""" )
sys.stdout.flush()
@contextmanager
def __lowerCamelCase ( ) -> Optional[Any]:
try:
hide_cursor()
yield
finally:
show_cursor()
| 517 | 1 |
from collections.abc import Iterable
from typing import Any
class UpperCamelCase :
def __init__( self : Union[str, Any] , snake_case__ : int | None = None ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = value
SCREAMING_SNAKE_CASE = None # Added in order to delete a node easier
SCREAMING_SNAKE_CASE = None
SCREAMING_SNAKE_CASE = None
def __repr__( self : List[Any] ):
"""simple docstring"""
from pprint import pformat
if self.left is None and self.right is None:
return str(self.value )
return pformat({F"""{self.value}""": (self.left, self.right)} , indent=1 )
class UpperCamelCase :
def __init__( self : Any , snake_case__ : Node | None = None ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = root
def __str__( self : Optional[Any] ):
"""simple docstring"""
return str(self.root )
def UpperCamelCase ( self : List[Any] , snake_case__ : Node , snake_case__ : Node | None ):
"""simple docstring"""
if new_children is not None: # reset its kids
SCREAMING_SNAKE_CASE = node.parent
if node.parent is not None: # reset its parent
if self.is_right(snake_case__ ): # If it is the right children
SCREAMING_SNAKE_CASE = new_children
else:
SCREAMING_SNAKE_CASE = new_children
else:
SCREAMING_SNAKE_CASE = new_children
def UpperCamelCase ( self : Optional[int] , snake_case__ : Node ):
"""simple docstring"""
if node.parent and node.parent.right:
return node == node.parent.right
return False
def UpperCamelCase ( self : Optional[int] ):
"""simple docstring"""
return self.root is None
def UpperCamelCase ( self : List[str] , snake_case__ : Any ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = Node(snake_case__ ) # create a new Node
if self.empty(): # if Tree is empty
SCREAMING_SNAKE_CASE = new_node # set its root
else: # Tree is not empty
SCREAMING_SNAKE_CASE = self.root # from root
if parent_node is None:
return
while True: # While we don't get to a leaf
if value < parent_node.value: # We go left
if parent_node.left is None:
SCREAMING_SNAKE_CASE = new_node # We insert the new node in a leaf
break
else:
SCREAMING_SNAKE_CASE = parent_node.left
else:
if parent_node.right is None:
SCREAMING_SNAKE_CASE = new_node
break
else:
SCREAMING_SNAKE_CASE = parent_node.right
SCREAMING_SNAKE_CASE = parent_node
def UpperCamelCase ( self : Optional[Any] , *snake_case__ : Union[str, Any] ):
"""simple docstring"""
for value in values:
self.__insert(snake_case__ )
def UpperCamelCase ( self : Dict , snake_case__ : str ):
"""simple docstring"""
if self.empty():
raise IndexError('Warning: Tree is empty! please use another.' )
else:
SCREAMING_SNAKE_CASE = self.root
# use lazy evaluation here to avoid NoneType Attribute error
while node is not None and node.value is not value:
SCREAMING_SNAKE_CASE = node.left if value < node.value else node.right
return node
def UpperCamelCase ( self : Optional[Any] , snake_case__ : Node | None = None ):
"""simple docstring"""
if node is None:
if self.root is None:
return None
SCREAMING_SNAKE_CASE = self.root
if not self.empty():
while node.right is not None:
SCREAMING_SNAKE_CASE = node.right
return node
def UpperCamelCase ( self : List[Any] , snake_case__ : Node | None = None ):
"""simple docstring"""
if node is None:
SCREAMING_SNAKE_CASE = self.root
if self.root is None:
return None
if not self.empty():
SCREAMING_SNAKE_CASE = self.root
while node.left is not None:
SCREAMING_SNAKE_CASE = node.left
return node
def UpperCamelCase ( self : Tuple , snake_case__ : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.search(snake_case__ ) # Look for the node with that label
if node is not None:
if node.left is None and node.right is None: # If it has no children
self.__reassign_nodes(snake_case__ , snake_case__ )
elif node.left is None: # Has only right children
self.__reassign_nodes(snake_case__ , node.right )
elif node.right is None: # Has only left children
self.__reassign_nodes(snake_case__ , node.left )
else:
SCREAMING_SNAKE_CASE = self.get_max(
node.left ) # Gets the max value of the left branch
self.remove(tmp_node.value ) # type: ignore
SCREAMING_SNAKE_CASE = (
tmp_node.value # type: ignore
) # Assigns the value to the node to delete and keep tree structure
def UpperCamelCase ( self : Optional[int] , snake_case__ : Node | None ):
"""simple docstring"""
if node is not None:
yield node # Preorder Traversal
yield from self.preorder_traverse(node.left )
yield from self.preorder_traverse(node.right )
def UpperCamelCase ( self : Any , snake_case__ : Optional[int]=None ):
"""simple docstring"""
if traversal_function is None:
return self.preorder_traverse(self.root )
else:
return traversal_function(self.root )
def UpperCamelCase ( self : Any , snake_case__ : list , snake_case__ : Node | None ):
"""simple docstring"""
if node:
self.inorder(snake_case__ , node.left )
arr.append(node.value )
self.inorder(snake_case__ , node.right )
def UpperCamelCase ( self : List[Any] , snake_case__ : int , snake_case__ : Node ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = []
self.inorder(snake_case__ , snake_case__ ) # append all values to list using inorder traversal
return arr[k - 1]
def __lowerCAmelCase ( _UpperCamelCase : Node | None ) -> list[Node]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = []
if curr_node is not None:
SCREAMING_SNAKE_CASE = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node]
return node_list
def __lowerCAmelCase ( ) -> None:
'''simple docstring'''
SCREAMING_SNAKE_CASE = (8, 3, 6, 1, 10, 14, 13, 4, 7)
SCREAMING_SNAKE_CASE = BinarySearchTree()
for i in testlist:
t.insert(_UpperCamelCase )
# Prints all the elements of the list in order traversal
print(_UpperCamelCase )
if t.search(6 ) is not None:
print('The value 6 exists' )
else:
print('The value 6 doesn\'t exist' )
if t.search(-1 ) is not None:
print('The value -1 exists' )
else:
print('The value -1 doesn\'t exist' )
if not t.empty():
print('Max Value: ' , t.get_max().value ) # type: ignore
print('Min Value: ' , t.get_min().value ) # type: ignore
for i in testlist:
t.remove(_UpperCamelCase )
print(_UpperCamelCase )
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
| 439 |
from __future__ import annotations
import unittest
from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available
from transformers.testing_utils import require_tf, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel
@require_tf
class UpperCamelCase :
__UpperCamelCase =BlenderbotSmallConfig
__UpperCamelCase ={}
__UpperCamelCase ="gelu"
def __init__( self : Optional[int] , snake_case__ : Dict , snake_case__ : Optional[int]=1_3 , snake_case__ : Optional[int]=7 , snake_case__ : Optional[Any]=True , snake_case__ : List[str]=False , snake_case__ : int=9_9 , snake_case__ : Any=3_2 , snake_case__ : Tuple=2 , snake_case__ : Optional[int]=4 , snake_case__ : int=3_7 , snake_case__ : Optional[Any]=0.1 , snake_case__ : int=0.1 , snake_case__ : Any=2_0 , snake_case__ : List[Any]=2 , snake_case__ : int=1 , snake_case__ : int=0 , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = parent
SCREAMING_SNAKE_CASE = batch_size
SCREAMING_SNAKE_CASE = seq_length
SCREAMING_SNAKE_CASE = is_training
SCREAMING_SNAKE_CASE = use_labels
SCREAMING_SNAKE_CASE = vocab_size
SCREAMING_SNAKE_CASE = hidden_size
SCREAMING_SNAKE_CASE = num_hidden_layers
SCREAMING_SNAKE_CASE = num_attention_heads
SCREAMING_SNAKE_CASE = intermediate_size
SCREAMING_SNAKE_CASE = hidden_dropout_prob
SCREAMING_SNAKE_CASE = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE = max_position_embeddings
SCREAMING_SNAKE_CASE = eos_token_id
SCREAMING_SNAKE_CASE = pad_token_id
SCREAMING_SNAKE_CASE = bos_token_id
def UpperCamelCase ( self : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size )
SCREAMING_SNAKE_CASE = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 )
SCREAMING_SNAKE_CASE = tf.concat([input_ids, eos_tensor] , axis=1 )
SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
SCREAMING_SNAKE_CASE = self.config_cls(
vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , )
SCREAMING_SNAKE_CASE = prepare_blenderbot_small_inputs_dict(snake_case__ , snake_case__ , snake_case__ )
return config, inputs_dict
def UpperCamelCase ( self : Dict , snake_case__ : Tuple , snake_case__ : Any ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = TFBlenderbotSmallModel(config=snake_case__ ).get_decoder()
SCREAMING_SNAKE_CASE = inputs_dict['input_ids']
SCREAMING_SNAKE_CASE = input_ids[:1, :]
SCREAMING_SNAKE_CASE = inputs_dict['attention_mask'][:1, :]
SCREAMING_SNAKE_CASE = inputs_dict['head_mask']
SCREAMING_SNAKE_CASE = 1
# first forward pass
SCREAMING_SNAKE_CASE = model(snake_case__ , attention_mask=snake_case__ , head_mask=snake_case__ , use_cache=snake_case__ )
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size )
SCREAMING_SNAKE_CASE = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta )
# append to next input_ids and
SCREAMING_SNAKE_CASE = tf.concat([input_ids, next_tokens] , axis=-1 )
SCREAMING_SNAKE_CASE = tf.concat([attention_mask, next_attn_mask] , axis=-1 )
SCREAMING_SNAKE_CASE = model(snake_case__ , attention_mask=snake_case__ )[0]
SCREAMING_SNAKE_CASE = model(snake_case__ , attention_mask=snake_case__ , past_key_values=snake_case__ )[0]
self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] )
# select random slice
SCREAMING_SNAKE_CASE = int(ids_tensor((1,) , output_from_past.shape[-1] ) )
SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx]
SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(snake_case__ , snake_case__ , rtol=1E-3 )
def __lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : Optional[int] , _UpperCamelCase : str , _UpperCamelCase : Dict=None , _UpperCamelCase : Optional[int]=None , _UpperCamelCase : Any=None , _UpperCamelCase : List[str]=None , _UpperCamelCase : Optional[Any]=None , ) -> str:
'''simple docstring'''
if attention_mask is None:
SCREAMING_SNAKE_CASE = tf.cast(tf.math.not_equal(_UpperCamelCase , config.pad_token_id ) , tf.inta )
if decoder_attention_mask is None:
SCREAMING_SNAKE_CASE = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ),
] , axis=-1 , )
if head_mask is None:
SCREAMING_SNAKE_CASE = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
SCREAMING_SNAKE_CASE = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
SCREAMING_SNAKE_CASE = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
@require_tf
class UpperCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ):
__UpperCamelCase =(
(TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else ()
)
__UpperCamelCase =(TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else ()
__UpperCamelCase =(
{
"conversational": TFBlenderbotSmallForConditionalGeneration,
"feature-extraction": TFBlenderbotSmallModel,
"summarization": TFBlenderbotSmallForConditionalGeneration,
"text2text-generation": TFBlenderbotSmallForConditionalGeneration,
"translation": TFBlenderbotSmallForConditionalGeneration,
}
if is_tf_available()
else {}
)
__UpperCamelCase =True
__UpperCamelCase =False
__UpperCamelCase =False
def UpperCamelCase ( self : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = TFBlenderbotSmallModelTester(self )
SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=snake_case__ )
def UpperCamelCase ( self : Any ):
"""simple docstring"""
self.config_tester.run_common_tests()
def UpperCamelCase ( self : List[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*snake_case__ )
@require_tokenizers
@require_tf
class UpperCamelCase ( unittest.TestCase ):
__UpperCamelCase =[
"Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like "
" i'm going to throw up.\nand why is that?"
]
__UpperCamelCase ="facebook/blenderbot_small-90M"
@cached_property
def UpperCamelCase ( self : Union[str, Any] ):
"""simple docstring"""
return BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' )
@cached_property
def UpperCamelCase ( self : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name )
return model
@slow
def UpperCamelCase ( self : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , return_tensors='tf' )
SCREAMING_SNAKE_CASE = self.model.generate(
model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=snake_case__ , )
SCREAMING_SNAKE_CASE = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=snake_case__ )[0]
assert generated_words in (
"i don't know. i just feel like i'm going to throw up. it's not fun.",
"i'm not sure. i just feel like i've been feeling like i have to be in a certain place",
"i'm not sure. i just feel like i've been in a bad situation.",
)
| 439 | 1 |
from __future__ import annotations
def _A( UpperCamelCase__ : list[int] , UpperCamelCase__ : list[int] , UpperCamelCase__ : int ) -> tuple[float, list[float]]:
'''simple docstring'''
__lowercase = list(range(len(UpperCamelCase__ ) ) )
__lowercase = [v / w for v, w in zip(UpperCamelCase__ , UpperCamelCase__ )]
index.sort(key=lambda UpperCamelCase__ : ratio[i] , reverse=UpperCamelCase__ )
__lowercase = 0
__lowercase = [0] * len(UpperCamelCase__ )
for i in index:
if weight[i] <= capacity:
__lowercase = 1
max_value += value[i]
capacity -= weight[i]
else:
__lowercase = capacity / weight[i]
max_value += value[i] * capacity / weight[i]
break
return max_value, fractions
if __name__ == "__main__":
import doctest
doctest.testmod()
| 715 |
import math
def _A( ) -> None:
'''simple docstring'''
__lowercase = input('''Enter message: ''' )
__lowercase = int(input(F'Enter key [2-{len(UpperCamelCase__ ) - 1}]: ' ) )
__lowercase = input('''Encryption/Decryption [e/d]: ''' )
if mode.lower().startswith('''e''' ):
__lowercase = encrypt_message(UpperCamelCase__ , UpperCamelCase__ )
elif mode.lower().startswith('''d''' ):
__lowercase = decrypt_message(UpperCamelCase__ , UpperCamelCase__ )
# Append pipe symbol (vertical bar) to identify spaces at the end.
print(F'Output:\n{text + "|"}' )
def _A( UpperCamelCase__ : int , UpperCamelCase__ : str ) -> str:
'''simple docstring'''
__lowercase = [''''''] * key
for col in range(UpperCamelCase__ ):
__lowercase = col
while pointer < len(UpperCamelCase__ ):
cipher_text[col] += message[pointer]
pointer += key
return "".join(UpperCamelCase__ )
def _A( UpperCamelCase__ : int , UpperCamelCase__ : str ) -> str:
'''simple docstring'''
__lowercase = math.ceil(len(UpperCamelCase__ ) / key )
__lowercase = key
__lowercase = (num_cols * num_rows) - len(UpperCamelCase__ )
__lowercase = [''''''] * num_cols
__lowercase = 0
__lowercase = 0
for symbol in message:
plain_text[col] += symbol
col += 1
if (
(col == num_cols)
or (col == num_cols - 1)
and (row >= num_rows - num_shaded_boxes)
):
__lowercase = 0
row += 1
return "".join(UpperCamelCase__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 362 | 0 |
from __future__ import annotations
import numpy as np
from numpy import floataa
from numpy.typing import NDArray
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : NDArray[floataa] , _SCREAMING_SNAKE_CASE : NDArray[floataa] , _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : int , ):
"""simple docstring"""
__a , __a = coefficient_matrix.shape
__a , __a = constant_matrix.shape
if rowsa != colsa:
__a = f"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}"
raise ValueError(_SCREAMING_SNAKE_CASE )
if colsa != 1:
__a = f"Constant matrix must be nx1 but received {rowsa}x{colsa}"
raise ValueError(_SCREAMING_SNAKE_CASE )
if rowsa != rowsa:
__a = (
"""Coefficient and constant matrices dimensions must be nxn and nx1 but """
f"received {rowsa}x{colsa} and {rowsa}x{colsa}"
)
raise ValueError(_SCREAMING_SNAKE_CASE )
if len(_SCREAMING_SNAKE_CASE ) != rowsa:
__a = (
"""Number of initial values must be equal to number of rows in coefficient """
f"matrix but received {len(_SCREAMING_SNAKE_CASE )} and {rowsa}"
)
raise ValueError(_SCREAMING_SNAKE_CASE )
if iterations <= 0:
raise ValueError("""Iterations must be at least 1""" )
__a = np.concatenate(
(coefficient_matrix, constant_matrix) , axis=1 )
__a , __a = table.shape
strictly_diagonally_dominant(_SCREAMING_SNAKE_CASE )
# Iterates the whole matrix for given number of times
for _ in range(_SCREAMING_SNAKE_CASE ):
__a = []
for row in range(_SCREAMING_SNAKE_CASE ):
__a = 0
for col in range(_SCREAMING_SNAKE_CASE ):
if col == row:
__a = table[row][col]
elif col == cols - 1:
__a = table[row][col]
else:
temp += (-1) * table[row][col] * init_val[col]
__a = (temp + val) / denom
new_val.append(_SCREAMING_SNAKE_CASE )
__a = new_val
return [float(_SCREAMING_SNAKE_CASE ) for i in new_val]
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : NDArray[floataa] ):
"""simple docstring"""
__a , __a = table.shape
__a = True
for i in range(0 , _SCREAMING_SNAKE_CASE ):
__a = 0
for j in range(0 , cols - 1 ):
if i == j:
continue
else:
total += table[i][j]
if table[i][i] <= total:
raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" )
return is_diagonally_dominant
# Test Cases
if __name__ == "__main__":
import doctest
doctest.testmod()
| 225 |
import unittest
from transformers import EsmConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel
from transformers.models.esm.modeling_esm import (
ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
EsmEmbeddings,
create_position_ids_from_input_ids,
)
class SCREAMING_SNAKE_CASE :
def __init__( self : Optional[Any] , __lowercase : List[Any] , __lowercase : int=13 , __lowercase : int=7 , __lowercase : str=False , __lowercase : int=True , __lowercase : Union[str, Any]=False , __lowercase : str=True , __lowercase : Optional[int]=33 , __lowercase : Dict=32 , __lowercase : Tuple=5 , __lowercase : List[Any]=4 , __lowercase : Dict=37 , __lowercase : Any="gelu" , __lowercase : Optional[Any]=0.1 , __lowercase : Optional[Any]=0.1 , __lowercase : List[str]=512 , __lowercase : str=16 , __lowercase : Tuple=2 , __lowercase : Tuple=0.02 , __lowercase : Tuple=3 , __lowercase : Union[str, Any]=4 , __lowercase : Dict=None , ):
'''simple docstring'''
__a = parent
__a = batch_size
__a = seq_length
__a = is_training
__a = use_input_mask
__a = use_token_type_ids
__a = use_labels
__a = vocab_size
__a = hidden_size
__a = num_hidden_layers
__a = num_attention_heads
__a = intermediate_size
__a = hidden_act
__a = hidden_dropout_prob
__a = attention_probs_dropout_prob
__a = max_position_embeddings
__a = type_vocab_size
__a = type_sequence_label_size
__a = initializer_range
__a = num_labels
__a = num_choices
__a = scope
def UpperCamelCase_ ( self : List[Any] ):
'''simple docstring'''
__a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__a = None
if self.use_input_mask:
__a = random_attention_mask([self.batch_size, self.seq_length] )
__a = None
__a = None
__a = None
if self.use_labels:
__a = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__a = ids_tensor([self.batch_size] , self.num_choices )
__a = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def UpperCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
return EsmConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , 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 , )
def UpperCamelCase_ ( self : Dict , __lowercase : List[str] , __lowercase : int , __lowercase : List[Any] , __lowercase : str , __lowercase : Tuple , __lowercase : Optional[int] ):
'''simple docstring'''
__a = EsmModel(config=__lowercase )
model.to(__lowercase )
model.eval()
__a = model(__lowercase , attention_mask=__lowercase )
__a = model(__lowercase )
__a = model(__lowercase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) )
def UpperCamelCase_ ( self : Tuple , __lowercase : Union[str, Any] , __lowercase : Optional[Any] , __lowercase : int , __lowercase : Dict , __lowercase : Union[str, Any] , __lowercase : int ):
'''simple docstring'''
__a = EsmForMaskedLM(config=__lowercase )
model.to(__lowercase )
model.eval()
__a = model(__lowercase , attention_mask=__lowercase , labels=__lowercase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def UpperCamelCase_ ( self : str , __lowercase : List[Any] , __lowercase : List[Any] , __lowercase : Optional[int] , __lowercase : Union[str, Any] , __lowercase : Any , __lowercase : Any ):
'''simple docstring'''
__a = self.num_labels
__a = EsmForTokenClassification(config=__lowercase )
model.to(__lowercase )
model.eval()
__a = model(__lowercase , attention_mask=__lowercase , labels=__lowercase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def UpperCamelCase_ ( self : Dict ):
'''simple docstring'''
__a = self.prepare_config_and_inputs()
(
(
__a
) , (
__a
) , (
__a
) , (
__a
) , (
__a
) , (
__a
) ,
) = config_and_inputs
__a = {"""input_ids""": input_ids, """attention_mask""": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ):
__lowerCamelCase : Optional[Any] =False
__lowerCamelCase : Optional[Any] =(
(
EsmForMaskedLM,
EsmModel,
EsmForSequenceClassification,
EsmForTokenClassification,
)
if is_torch_available()
else ()
)
__lowerCamelCase : List[Any] =()
__lowerCamelCase : str =(
{
'feature-extraction': EsmModel,
'fill-mask': EsmForMaskedLM,
'text-classification': EsmForSequenceClassification,
'token-classification': EsmForTokenClassification,
'zero-shot': EsmForSequenceClassification,
}
if is_torch_available()
else {}
)
__lowerCamelCase : str =True
def UpperCamelCase_ ( self : int ):
'''simple docstring'''
__a = EsmModelTester(self )
__a = ConfigTester(self , config_class=__lowercase , hidden_size=37 )
def UpperCamelCase_ ( self : Tuple ):
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCamelCase_ ( self : List[Any] ):
'''simple docstring'''
__a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__lowercase )
def UpperCamelCase_ ( self : str ):
'''simple docstring'''
__a = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
__a = type
self.model_tester.create_and_check_model(*__lowercase )
def UpperCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
__a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*__lowercase )
def UpperCamelCase_ ( self : Dict ):
'''simple docstring'''
__a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*__lowercase )
@slow
def UpperCamelCase_ ( self : List[Any] ):
'''simple docstring'''
for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__a = EsmModel.from_pretrained(__lowercase )
self.assertIsNotNone(__lowercase )
def UpperCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
__a = self.model_tester.prepare_config_and_inputs()[0]
__a = EsmEmbeddings(config=__lowercase )
__a = torch.as_tensor([[12, 31, 13, model.padding_idx]] )
__a = torch.as_tensor(
[
[
0 + model.padding_idx + 1,
1 + model.padding_idx + 1,
2 + model.padding_idx + 1,
model.padding_idx,
]
] )
__a = create_position_ids_from_input_ids(__lowercase , model.padding_idx )
self.assertEqual(position_ids.shape , expected_positions.shape )
self.assertTrue(torch.all(torch.eq(__lowercase , __lowercase ) ) )
def UpperCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
__a = self.model_tester.prepare_config_and_inputs()[0]
__a = EsmEmbeddings(config=__lowercase )
__a = torch.empty(2 , 4 , 30 )
__a = [
0 + embeddings.padding_idx + 1,
1 + embeddings.padding_idx + 1,
2 + embeddings.padding_idx + 1,
3 + embeddings.padding_idx + 1,
]
__a = torch.as_tensor([expected_single_positions, expected_single_positions] )
__a = embeddings.create_position_ids_from_inputs_embeds(__lowercase )
self.assertEqual(position_ids.shape , expected_positions.shape )
self.assertTrue(torch.all(torch.eq(__lowercase , __lowercase ) ) )
@unittest.skip("""Esm does not support embedding resizing""" )
def UpperCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
pass
@unittest.skip("""Esm does not support embedding resizing""" )
def UpperCamelCase_ ( self : int ):
'''simple docstring'''
pass
@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" )
def UpperCamelCase_ ( self : int ):
'''simple docstring'''
pass
@require_torch
class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ):
@slow
def UpperCamelCase_ ( self : Dict ):
'''simple docstring'''
with torch.no_grad():
__a = EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" )
model.eval()
__a = torch.tensor([[0, 1, 2, 3, 4, 5]] )
__a = model(__lowercase )[0]
__a = 33
__a = torch.Size((1, 6, vocab_size) )
self.assertEqual(output.shape , __lowercase )
__a = torch.tensor(
[[[8.9215, -10.5898, -6.4671], [-6.3967, -13.9114, -1.1212], [-7.7812, -13.9516, -3.7406]]] )
self.assertTrue(torch.allclose(output[:, :3, :3] , __lowercase , atol=1E-4 ) )
@slow
def UpperCamelCase_ ( self : Dict ):
'''simple docstring'''
with torch.no_grad():
__a = EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" )
model.eval()
__a = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] )
__a = model(__lowercase )[0]
# compare the actual values for a slice.
__a = torch.tensor(
[[[0.1444, 0.5413, 0.3248], [0.3034, 0.0053, 0.3108], [0.3228, -0.2499, 0.3415]]] )
self.assertTrue(torch.allclose(output[:, :3, :3] , __lowercase , atol=1E-4 ) )
| 225 | 1 |
from __future__ import annotations
import inspect
import unittest
from math import floor
import numpy as np
from transformers import CvtConfig
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 TFCvtForImageClassification, TFCvtModel
from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class snake_case_ ( _lowerCAmelCase ):
def snake_case_ ( self ):
a_ : str = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(_lowerCAmelCase , "embed_dim" ) )
self.parent.assertTrue(hasattr(_lowerCAmelCase , "num_heads" ) )
class snake_case_ :
def __init__( self , a_ , a_=1_3 , a_=6_4 , a_=3 , a_=[1_6, 4_8, 9_6] , a_=[1, 3, 6] , a_=[1, 2, 1_0] , a_=[7, 3, 3] , a_=[4, 2, 2] , a_=[2, 1, 1] , a_=[2, 2, 2] , a_=[False, False, True] , a_=[0.0, 0.0, 0.0] , a_=0.02 , a_=1e-12 , a_=True , a_=True , a_=2 , ):
a_ : Tuple = parent
a_ : List[Any] = batch_size
a_ : str = image_size
a_ : int = patch_sizes
a_ : Union[str, Any] = patch_stride
a_ : int = patch_padding
a_ : Optional[Any] = is_training
a_ : Tuple = use_labels
a_ : Dict = num_labels
a_ : Dict = num_channels
a_ : List[Any] = embed_dim
a_ : List[Any] = num_heads
a_ : Optional[int] = stride_kv
a_ : str = depth
a_ : Optional[int] = cls_token
a_ : Tuple = attention_drop_rate
a_ : Dict = initializer_range
a_ : List[str] = layer_norm_eps
def snake_case_ ( self ):
a_ : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
a_ : str = None
if self.use_labels:
# create a random int32 tensor of given shape
a_ : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels )
a_ : List[str] = self.get_config()
return config, pixel_values, labels
def snake_case_ ( self ):
return CvtConfig(
image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , )
def snake_case_ ( self , a_ , a_ , a_ ):
a_ : Optional[Any] = TFCvtModel(config=_lowerCAmelCase )
a_ : int = model(_lowerCAmelCase , training=_lowerCAmelCase )
a_ : Tuple = (self.image_size, self.image_size)
a_ , a_ : Optional[Any] = image_size[0], image_size[1]
for i in range(len(self.depth ) ):
a_ : Any = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 )
a_ : List[str] = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) )
def snake_case_ ( self , a_ , a_ , a_ ):
a_ : Optional[Any] = self.num_labels
a_ : int = TFCvtForImageClassification(_lowerCAmelCase )
a_ : Optional[int] = model(_lowerCAmelCase , labels=_lowerCAmelCase , training=_lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def snake_case_ ( self ):
a_ : Any = self.prepare_config_and_inputs()
a_ , a_ , a_ : Optional[int] = config_and_inputs
a_ : Union[str, Any] = {"pixel_values": pixel_values}
return config, inputs_dict
@require_tf
class snake_case_ ( _lowerCAmelCase ,_lowerCAmelCase ,unittest.TestCase ):
__lowerCAmelCase = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
__lowerCAmelCase = (
{'feature-extraction': TFCvtModel, 'image-classification': TFCvtForImageClassification}
if is_tf_available()
else {}
)
__lowerCAmelCase = False
__lowerCAmelCase = False
__lowerCAmelCase = False
__lowerCAmelCase = False
__lowerCAmelCase = False
def snake_case_ ( self ):
a_ : List[Any] = TFCvtModelTester(self )
a_ : Dict = TFCvtConfigTester(self , config_class=_lowerCAmelCase , has_text_modality=_lowerCAmelCase , hidden_size=3_7 )
def snake_case_ ( self ):
self.config_tester.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
@unittest.skip(reason="Cvt does not output attentions" )
def snake_case_ ( self ):
pass
@unittest.skip(reason="Cvt does not use inputs_embeds" )
def snake_case_ ( self ):
pass
@unittest.skip(reason="Cvt does not support input and output embeddings" )
def snake_case_ ( self ):
pass
@unittest.skipIf(
not is_tf_available() or len(tf.config.list_physical_devices("GPU" ) ) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , )
def snake_case_ ( self ):
super().test_dataset_conversion()
@unittest.skipIf(
not is_tf_available() or len(tf.config.list_physical_devices("GPU" ) ) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , )
@slow
def snake_case_ ( self ):
super().test_keras_fit()
@unittest.skip(reason="Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8" )
def snake_case_ ( self ):
a_ : List[Any] = tf.keras.mixed_precision.Policy("mixed_float16" )
tf.keras.mixed_precision.set_global_policy(_lowerCAmelCase )
super().test_keras_fit()
tf.keras.mixed_precision.set_global_policy("float32" )
def snake_case_ ( self ):
a_ , a_ : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a_ : Tuple = model_class(_lowerCAmelCase )
a_ : List[Any] = inspect.signature(model.call )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
a_ : int = [*signature.parameters.keys()]
a_ : Optional[Any] = ["pixel_values"]
self.assertListEqual(arg_names[:1] , _lowerCAmelCase )
def snake_case_ ( self ):
def check_hidden_states_output(a_ , a_ , a_ ):
a_ : int = model_class(_lowerCAmelCase )
a_ : List[str] = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) )
a_ : Dict = outputs.hidden_states
a_ : List[str] = len(self.model_tester.depth )
self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase )
# verify the first hidden states (first block)
self.assertListEqual(
list(hidden_states[0].shape[-3:] ) , [
self.model_tester.embed_dim[0],
self.model_tester.image_size // 4,
self.model_tester.image_size // 4,
] , )
a_ , a_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a_ : Union[str, Any] = True
check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
a_ : int = True
check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
def snake_case_ ( self ):
a_ : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_lowerCAmelCase )
def snake_case_ ( self ):
a_ : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase )
@slow
def snake_case_ ( self ):
for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
a_ : Dict = TFCvtModel.from_pretrained(_lowerCAmelCase )
self.assertIsNotNone(_lowerCAmelCase )
def lowerCAmelCase_ ( ) -> List[Any]:
a_ : Dict = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_tf
@require_vision
class snake_case_ ( unittest.TestCase ):
@cached_property
def snake_case_ ( self ):
return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
@slow
def snake_case_ ( self ):
a_ : Optional[int] = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
a_ : Union[str, Any] = self.default_image_processor
a_ : Optional[int] = prepare_img()
a_ : Optional[int] = image_processor(images=_lowerCAmelCase , return_tensors="tf" )
# forward pass
a_ : Union[str, Any] = model(**_lowerCAmelCase )
# verify the logits
a_ : List[Any] = tf.TensorShape((1, 1_0_0_0) )
self.assertEqual(outputs.logits.shape , _lowerCAmelCase )
a_ : Optional[Any] = tf.constant([0.9_285, 0.9_015, -0.3_150] )
self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , _lowerCAmelCase , atol=1e-4 ) ) | 709 |
"""simple docstring"""
import unittest
from transformers import SPIECE_UNDERLINE
from transformers.models.speechta import SpeechTaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.tokenization_utils import AddedToken
from ...test_tokenization_common import TokenizerTesterMixin
SCREAMING_SNAKE_CASE_ = get_tests_dir("""fixtures/test_sentencepiece_bpe_char.model""")
@require_sentencepiece
@require_tokenizers
class snake_case_ ( a_ ,unittest.TestCase ):
__lowerCAmelCase = SpeechTaTokenizer
__lowerCAmelCase = False
__lowerCAmelCase = True
def snake_case_ ( self ):
super().setUp()
# We have a SentencePiece fixture for testing
a_ : Any = SpeechTaTokenizer(a_ )
a_ : Optional[int] = AddedToken("<mask>" , lstrip=a_ , rstrip=a_ )
a_ : Any = mask_token
tokenizer.add_special_tokens({"mask_token": mask_token} )
tokenizer.add_tokens(["<ctc_blank>"] )
tokenizer.save_pretrained(self.tmpdirname )
def snake_case_ ( self , a_ ):
a_ : Tuple = "this is a test"
a_ : Any = "this is a test"
return input_text, output_text
def snake_case_ ( self , a_ , a_=False , a_=2_0 , a_=5 ):
a_ , a_ : Optional[Any] = self.get_input_output_texts(a_ )
a_ : Optional[Any] = tokenizer.encode(a_ , add_special_tokens=a_ )
a_ : Dict = tokenizer.decode(a_ , clean_up_tokenization_spaces=a_ )
return text, ids
def snake_case_ ( self ):
a_ : List[Any] = "<pad>"
a_ : Optional[int] = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ )
def snake_case_ ( self ):
a_ : List[Any] = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<s>" )
self.assertEqual(vocab_keys[1] , "<pad>" )
self.assertEqual(vocab_keys[-4] , "œ" )
self.assertEqual(vocab_keys[-2] , "<mask>" )
self.assertEqual(vocab_keys[-1] , "<ctc_blank>" )
self.assertEqual(len(a_ ) , 8_1 )
def snake_case_ ( self ):
self.assertEqual(self.get_tokenizer().vocab_size , 7_9 )
def snake_case_ ( self ):
a_ : Any = self.get_tokenizers(do_lower_case=a_ )
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
a_ : Dict = tokenizer.vocab_size
a_ : List[str] = len(a_ )
self.assertNotEqual(a_ , 0 )
# We usually have added tokens from the start in tests because our vocab fixtures are
# smaller than the original vocabs - let's not assert this
# self.assertEqual(vocab_size, all_size)
a_ : Optional[int] = ["aaaaa bbbbbb", "cccccccccdddddddd"]
a_ : int = tokenizer.add_tokens(a_ )
a_ : List[Any] = tokenizer.vocab_size
a_ : Tuple = len(a_ )
self.assertNotEqual(a_ , 0 )
self.assertEqual(a_ , a_ )
self.assertEqual(a_ , len(a_ ) )
self.assertEqual(a_ , all_size + len(a_ ) )
a_ : str = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l" , add_special_tokens=a_ )
self.assertGreaterEqual(len(a_ ) , 4 )
self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 )
self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 )
a_ : Tuple = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"}
a_ : Dict = tokenizer.add_special_tokens(a_ )
a_ : Optional[Any] = tokenizer.vocab_size
a_ : Any = len(a_ )
self.assertNotEqual(a_ , 0 )
self.assertEqual(a_ , a_ )
self.assertEqual(a_ , len(a_ ) )
self.assertEqual(a_ , all_size_a + len(a_ ) )
a_ : Any = tokenizer.encode(
">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l" , add_special_tokens=a_ )
self.assertGreaterEqual(len(a_ ) , 6 )
self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 )
self.assertGreater(tokens[0] , tokens[1] )
self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 )
self.assertGreater(tokens[-3] , tokens[-4] )
self.assertEqual(tokens[0] , tokenizer.eos_token_id )
self.assertEqual(tokens[-3] , tokenizer.pad_token_id )
def snake_case_ ( self ):
pass
def snake_case_ ( self ):
pass
def snake_case_ ( self ):
a_ : Union[str, Any] = self.get_tokenizer()
a_ : Any = tokenizer.tokenize("This is a test" )
# fmt: off
self.assertListEqual(a_ , [SPIECE_UNDERLINE, "T", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "a", SPIECE_UNDERLINE, "t", "e", "s", "t"] )
# fmt: on
self.assertListEqual(
tokenizer.convert_tokens_to_ids(a_ ) , [4, 3_2, 1_1, 1_0, 1_2, 4, 1_0, 1_2, 4, 7, 4, 6, 5, 1_2, 6] , )
a_ : Optional[int] = tokenizer.tokenize("I was born in 92000, and this is falsé." )
self.assertListEqual(
a_ , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "92000", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] )
a_ : Tuple = tokenizer.convert_tokens_to_ids(a_ )
# fmt: off
self.assertListEqual(a_ , [4, 3_0, 4, 2_0, 7, 1_2, 4, 2_5, 8, 1_3, 9, 4, 1_0, 9, 4, 3, 2_3, 4, 7, 9, 1_4, 4, 6, 1_1, 1_0, 1_2, 4, 1_0, 1_2, 4, 1_9, 7, 1_5, 1_2, 7_3, 2_6] )
# fmt: on
a_ : Tuple = tokenizer.convert_ids_to_tokens(a_ )
self.assertListEqual(
a_ , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "<unk>", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] )
@slow
def snake_case_ ( self ):
# Use custom sequence because this tokenizer does not handle numbers.
a_ : List[Any] = [
"Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides "
"general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural "
"Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained "
"models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.",
"BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly "
"conditioning on both left and right context in all layers.",
"The quick brown fox jumps over the lazy dog.",
]
# fmt: off
a_ : Tuple = {
"input_ids": [
[4, 3_2, 1_3, 7, 9, 1_2, 1_9, 8, 1_3, 1_8, 5, 1_3, 1_2, 4, 6_4, 1_9, 8, 1_3, 1_8, 5, 1_3, 1_5, 2_2, 4, 2_8, 9, 8, 2_0, 9, 4, 7, 1_2, 4, 2_4, 2_2, 6, 8, 1_3, 1_7, 1_1, 3_9, 6, 1_3, 7, 9, 1_2, 1_9, 8, 1_3, 1_8, 5, 1_3, 1_2, 4, 7, 9, 1_4, 4, 2_4, 2_2, 6, 8, 1_3, 1_7, 1_1, 3_9, 2_4, 1_3, 5, 6, 1_3, 7, 1_0, 9, 5, 1_4, 3_9, 2_5, 5, 1_3, 6, 6_3, 4, 2_4, 1_3, 8, 2_7, 1_0, 1_4, 5, 1_2, 4, 2_1, 5, 9, 5, 1_3, 7, 1_5, 3_9, 2_4, 1_6, 1_3, 2_4, 8, 1_2, 5, 4, 7, 1_3, 1_7, 1_1, 1_0, 6, 5, 1_7, 6, 1_6, 1_3, 5, 1_2, 4, 6_4, 4_0, 4_7, 5_4, 3_2, 2_3, 4, 5_3, 4_9, 3_2, 2_3, 4, 5_4, 8, 4_0, 4_7, 5_4, 3_2, 7, 2_3, 4, 6_9, 5_2, 4_3, 2_3, 4, 5_1, 1_0, 1_2, 6, 1_0, 1_5, 4_0, 5, 1_3, 6, 2_3, 4, 6_9, 5_2, 4_8, 5, 6, 2_6, 2_6, 2_6, 6_3, 4, 1_9, 8, 1_3, 4, 4_8, 7, 6, 1_6, 1_3, 7, 1_5, 4, 5_2, 7, 9, 2_1, 1_6, 7, 2_1, 5, 4, 6_1, 9, 1_4, 5, 1_3, 1_2, 6, 7, 9, 1_4, 1_0, 9, 2_1, 4, 6_4, 4_8, 5_2, 6_1, 6_3, 4, 7, 9, 1_4, 4, 4_8, 7, 6, 1_6, 1_3, 7, 1_5, 4, 5_2, 7, 9, 2_1, 1_6, 7, 2_1, 5, 4, 5_3, 5, 9, 5, 1_3, 7, 6, 1_0, 8, 9, 4, 6_4, 4_8, 5_2, 5_3, 6_3, 4, 2_0, 1_0, 6, 1_1, 4, 8, 2_7, 5, 1_3, 4, 6, 1_1, 1_0, 1_3, 6, 2_2, 3_9, 6, 2_0, 8, 4, 2_4, 1_3, 5, 6, 1_3, 7, 1_0, 9, 5, 1_4, 4, 1_8, 8, 1_4, 5, 1_5, 1_2, 4, 1_0, 9, 4, 8, 9, 5, 4, 1_1, 1_6, 9, 1_4, 1_3, 5, 1_4, 4, 2_4, 1_5, 1_6, 1_2, 4, 1_5, 7, 9, 2_1, 1_6, 7, 2_1, 5, 1_2, 4, 7, 9, 1_4, 4, 1_4, 5, 5, 2_4, 4, 1_0, 9, 6, 5, 1_3, 8, 2_4, 5, 1_3, 7, 2_5, 1_0, 1_5, 1_0, 6, 2_2, 4, 2_5, 5, 6, 2_0, 5, 5, 9, 4, 5_8, 7, 3_7, 2_3, 4, 4_9, 2_2, 3_2, 8, 1_3, 1_7, 1_1, 4, 7, 9, 1_4, 4, 3_2, 5, 9, 1_2, 8, 1_3, 5_5, 1_5, 8, 2_0, 2_6, 2],
[4, 4_0, 4_7, 5_4, 3_2, 4, 1_0, 1_2, 4, 1_4, 5, 1_2, 1_0, 2_1, 9, 5, 1_4, 4, 6, 8, 4, 2_4, 1_3, 5, 3_9, 6, 1_3, 7, 1_0, 9, 4, 1_4, 5, 5, 2_4, 4, 2_5, 1_0, 1_4, 1_0, 1_3, 5, 1_7, 6, 1_0, 8, 9, 7, 1_5, 4, 1_3, 5, 2_4, 1_3, 5, 1_2, 5, 9, 6, 7, 6, 1_0, 8, 9, 1_2, 4, 1_9, 1_3, 8, 1_8, 4, 1_6, 9, 1_5, 7, 2_5, 5, 1_5, 5, 1_4, 4, 6, 5, 3_7, 6, 4, 2_5, 2_2, 4, 4_6, 8, 1_0, 9, 6, 1_5, 2_2, 4, 1_7, 8, 9, 1_4, 1_0, 6, 1_0, 8, 9, 1_0, 9, 2_1, 4, 8, 9, 4, 2_5, 8, 6, 1_1, 4, 1_5, 5, 1_9, 6, 4, 7, 9, 1_4, 4, 1_3, 1_0, 2_1, 1_1, 6, 4, 1_7, 8, 9, 6, 5, 3_7, 6, 4, 1_0, 9, 4, 7, 1_5, 1_5, 4, 1_5, 7, 2_2, 5, 1_3, 1_2, 2_6, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[4, 3_2, 1_1, 5, 4, 4_5, 1_6, 1_0, 1_7, 2_8, 4, 2_5, 1_3, 8, 2_0, 9, 4, 1_9, 8, 3_7, 4, 4_6, 1_6, 1_8, 2_4, 1_2, 4, 8, 2_7, 5, 1_3, 4, 6, 1_1, 5, 4, 1_5, 7, 5_7, 2_2, 4, 1_4, 8, 2_1, 2_6, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]
}
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=a_ , model_name="microsoft/speecht5_asr" , revision="c5ef64c71905caeccde0e4462ef3f9077224c524" , sequences=a_ , ) | 370 | 0 |
from math import pi
def SCREAMING_SNAKE_CASE_ ( __A : int , __A : int ) -> float:
"""simple docstring"""
return 2 * pi * radius * (angle / 3_60)
if __name__ == "__main__":
print(arc_length(90, 10))
| 570 |
import copy
import inspect
import unittest
from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available
from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor
if is_torch_available():
import torch
from transformers import TimmBackbone, TimmBackboneConfig
from ...test_pipeline_mixin import PipelineTesterMixin
class SCREAMING_SNAKE_CASE__ :
def __init__( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]="resnet50" , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : Any=3_2 , SCREAMING_SNAKE_CASE__ : Tuple=3 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , ) -> List[str]:
a_ : Any = parent
a_ : Tuple = out_indices if out_indices is not None else [4]
a_ : Tuple = stage_names
a_ : List[Any] = out_features
a_ : List[str] = backbone
a_ : List[str] = batch_size
a_ : str = image_size
a_ : Tuple = num_channels
a_ : Tuple = use_pretrained_backbone
a_ : str = is_training
def SCREAMING_SNAKE_CASE ( self : Any ) -> Dict:
a_ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
a_ : Optional[Any] = self.get_config()
return config, pixel_values
def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str:
return TimmBackboneConfig(
image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , )
def SCREAMING_SNAKE_CASE ( self : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Union[str, Any]:
a_ : List[str] = TimmBackbone(config=SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
with torch.no_grad():
a_ : str = model(SCREAMING_SNAKE_CASE__ )
self.parent.assertEqual(
result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 1_4, 1_4) , )
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict:
a_ : List[Any] = self.prepare_config_and_inputs()
a_ , a_ : List[str] = config_and_inputs
a_ : Union[str, Any] = {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
@require_timm
class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ):
snake_case__ : Tuple = (TimmBackbone,) if is_torch_available() else ()
snake_case__ : Optional[int] = {'''feature-extraction''': TimmBackbone} if is_torch_available() else {}
snake_case__ : Any = False
snake_case__ : Optional[int] = False
snake_case__ : Optional[int] = False
snake_case__ : List[str] = False
def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple:
a_ : List[Any] = TimmBackboneModelTester(self )
a_ : Optional[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ )
def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]:
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple:
a_ : Union[str, Any] = 'resnet18'
a_ : Dict = 'microsoft/resnet-18'
a_ : Union[str, Any] = AutoBackbone.from_pretrained(SCREAMING_SNAKE_CASE__ , use_timm_backbone=SCREAMING_SNAKE_CASE__ )
a_ : Dict = AutoBackbone.from_pretrained(SCREAMING_SNAKE_CASE__ )
self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) )
self.assertEqual(len(timm_model.stage_names ) , len(transformers_model.stage_names ) )
self.assertEqual(timm_model.channels , transformers_model.channels )
# Out indices are set to the last layer by default. For timm models, we don't know
# the number of layers in advance, so we set it to (-1,), whereas for transformers
# models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
self.assertEqual(timm_model.out_indices , (-1,) )
self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names ) - 1] )
a_ : Dict = AutoBackbone.from_pretrained(SCREAMING_SNAKE_CASE__ , use_timm_backbone=SCREAMING_SNAKE_CASE__ , out_indices=[1, 2, 3] )
a_ : int = AutoBackbone.from_pretrained(SCREAMING_SNAKE_CASE__ , out_indices=[1, 2, 3] )
self.assertEqual(timm_model.out_indices , transformers_model.out_indices )
self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) )
self.assertEqual(timm_model.channels , transformers_model.channels )
@unittest.skip('TimmBackbone doesn\'t support feed forward chunking' )
def SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]:
pass
@unittest.skip('TimmBackbone doesn\'t have num_hidden_layers attribute' )
def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]:
pass
@unittest.skip('TimmBackbone initialization is managed on the timm side' )
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]:
pass
@unittest.skip('TimmBackbone models doesn\'t have inputs_embeds' )
def SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]:
pass
@unittest.skip('TimmBackbone models doesn\'t have inputs_embeds' )
def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple:
pass
@unittest.skip('TimmBackbone model cannot be created without specifying a backbone checkpoint' )
def SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[Any]:
pass
@unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' )
def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]:
pass
@unittest.skip('model weights aren\'t tied in TimmBackbone.' )
def SCREAMING_SNAKE_CASE ( self : int ) -> Union[str, Any]:
pass
@unittest.skip('model weights aren\'t tied in TimmBackbone.' )
def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict:
pass
@unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' )
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple:
pass
@unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' )
def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any:
pass
@unittest.skip('TimmBackbone doesn\'t have hidden size info in its configuration.' )
def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]:
pass
@unittest.skip('TimmBackbone doesn\'t support output_attentions.' )
def SCREAMING_SNAKE_CASE ( self : Any ) -> Any:
pass
@unittest.skip('Safetensors is not supported by timm.' )
def SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]:
pass
@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any:
pass
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]:
a_ , a_ : int = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a_ : List[Any] = model_class(SCREAMING_SNAKE_CASE__ )
a_ : Optional[int] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
a_ : List[Any] = [*signature.parameters.keys()]
a_ : Dict = ['pixel_values']
self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ )
def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]:
a_ , a_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
a_ : List[str] = True
a_ : Dict = self.has_attentions
# no need to test all models as different heads yield the same functionality
a_ : Optional[Any] = self.all_model_classes[0]
a_ : Dict = model_class(SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
a_ : List[str] = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
a_ : Any = model(**SCREAMING_SNAKE_CASE__ )
a_ : Any = outputs[0][-1]
# Encoder-/Decoder-only models
a_ : str = outputs.hidden_states[0]
hidden_states.retain_grad()
if self.has_attentions:
a_ : Optional[int] = outputs.attentions[0]
attentions.retain_grad()
output.flatten()[0].backward(retain_graph=SCREAMING_SNAKE_CASE__ )
self.assertIsNotNone(hidden_states.grad )
if self.has_attentions:
self.assertIsNotNone(attentions.grad )
def SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]:
a_ , a_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a_ : Optional[Any] = model_class(SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
a_ : str = model(**SCREAMING_SNAKE_CASE__ )
self.assertEqual(len(result.feature_maps ) , len(config.out_indices ) )
self.assertEqual(len(model.channels ) , len(config.out_indices ) )
# Check output of last stage is taken if out_features=None, out_indices=None
a_ : Tuple = copy.deepcopy(SCREAMING_SNAKE_CASE__ )
a_ : Tuple = None
a_ : str = model_class(SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
a_ : Union[str, Any] = model(**SCREAMING_SNAKE_CASE__ )
self.assertEqual(len(result.feature_maps ) , 1 )
self.assertEqual(len(model.channels ) , 1 )
# Check backbone can be initialized with fresh weights
a_ : Dict = copy.deepcopy(SCREAMING_SNAKE_CASE__ )
a_ : List[str] = False
a_ : Optional[int] = model_class(SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
a_ : Optional[int] = model(**SCREAMING_SNAKE_CASE__ )
| 570 | 1 |
import unittest
import numpy as np
from transformers.testing_utils import require_pytesseract, require_torch
from transformers.utils import is_pytesseract_available, is_torch_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_pytesseract_available():
from PIL import Image
from transformers import LayoutLMvaImageProcessor
class __magic_name__ ( unittest.TestCase ):
"""simple docstring"""
def __init__( self , a__ , a__=7 , a__=3 , a__=18 , a__=30 , a__=4_00 , a__=True , a__=None , a__=True , ):
_lowerCamelCase = size if size is not None else {'''height''': 18, '''width''': 18}
_lowerCamelCase = parent
_lowerCamelCase = batch_size
_lowerCamelCase = num_channels
_lowerCamelCase = image_size
_lowerCamelCase = min_resolution
_lowerCamelCase = max_resolution
_lowerCamelCase = do_resize
_lowerCamelCase = size
_lowerCamelCase = apply_ocr
def _UpperCAmelCase ( self ):
return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr}
@require_torch
@require_pytesseract
class __magic_name__ ( lowercase_ ,unittest.TestCase ):
"""simple docstring"""
_UpperCamelCase = LayoutLMvaImageProcessor if is_pytesseract_available() else None
def _UpperCAmelCase ( self ):
_lowerCamelCase = LayoutLMvaImageProcessingTester(self )
@property
def _UpperCAmelCase ( self ):
return self.image_processor_tester.prepare_image_processor_dict()
def _UpperCAmelCase ( self ):
_lowerCamelCase = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(a__ , '''do_resize''' ) )
self.assertTrue(hasattr(a__ , '''size''' ) )
self.assertTrue(hasattr(a__ , '''apply_ocr''' ) )
def _UpperCAmelCase ( self ):
_lowerCamelCase = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} )
_lowerCamelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} )
def _UpperCAmelCase ( self ):
pass
def _UpperCAmelCase ( self ):
# Initialize image_processing
_lowerCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=a__ )
for image in image_inputs:
self.assertIsInstance(a__ , Image.Image )
# Test not batched input
_lowerCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''' )
self.assertEqual(
encoding.pixel_values.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
self.assertIsInstance(encoding.words , a__ )
self.assertIsInstance(encoding.boxes , a__ )
# Test batched
_lowerCamelCase = 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.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
def _UpperCAmelCase ( self ):
# Initialize image_processing
_lowerCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=a__ , numpify=a__ )
for image in image_inputs:
self.assertIsInstance(a__ , np.ndarray )
# Test not batched input
_lowerCamelCase = 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.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
# Test batched
_lowerCamelCase = 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.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
def _UpperCAmelCase ( self ):
# Initialize image_processing
_lowerCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=a__ , torchify=a__ )
for image in image_inputs:
self.assertIsInstance(a__ , torch.Tensor )
# Test not batched input
_lowerCamelCase = 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.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
# Test batched
_lowerCamelCase = 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.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
def _UpperCAmelCase ( self ):
# with apply_OCR = True
_lowerCamelCase = LayoutLMvaImageProcessor()
from datasets import load_dataset
_lowerCamelCase = load_dataset('''hf-internal-testing/fixtures_docvqa''' , split='''test''' )
_lowerCamelCase = Image.open(ds[0]['''file'''] ).convert('''RGB''' )
_lowerCamelCase = image_processing(a__ , return_tensors='''pt''' )
self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) )
self.assertEqual(len(encoding.words ) , len(encoding.boxes ) )
# fmt: off
# the words and boxes were obtained with Tesseract 4.1.1
_lowerCamelCase = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231
_lowerCamelCase = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231
# fmt: on
self.assertListEqual(encoding.words , a__ )
self.assertListEqual(encoding.boxes , a__ )
# with apply_OCR = False
_lowerCamelCase = LayoutLMvaImageProcessor(apply_ocr=a__ )
_lowerCamelCase = image_processing(a__ , return_tensors='''pt''' )
self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) )
| 710 |
import argparse
import torch
from transformers import (
SpeechTaConfig,
SpeechTaFeatureExtractor,
SpeechTaForSpeechToSpeech,
SpeechTaForSpeechToText,
SpeechTaForTextToSpeech,
SpeechTaProcessor,
SpeechTaTokenizer,
logging,
)
from transformers.tokenization_utils import AddedToken
logging.set_verbosity_info()
_UpperCAmelCase = logging.get_logger("transformers.models.speecht5")
_UpperCAmelCase = {
"speech_encoder_prenet.layer_norm": "speecht5.encoder.prenet.feature_projection.layer_norm",
"speech_encoder_prenet.post_extract_proj": "speecht5.encoder.prenet.feature_projection.projection",
"speech_encoder_prenet.pos_conv.0": "speecht5.encoder.prenet.pos_conv_embed.conv",
"speech_encoder_prenet.mask_emb": "speecht5.encoder.prenet.masked_spec_embed",
}
_UpperCAmelCase = {
"text_encoder_prenet.encoder_prenet.0": "speecht5.encoder.prenet.embed_tokens",
"text_encoder_prenet.encoder_prenet.1.alpha": "speecht5.encoder.prenet.encode_positions.alpha",
}
_UpperCAmelCase = {
"speech_decoder_prenet.decoder_prenet.0.0.prenet.0.0": "speecht5.decoder.prenet.layers.0",
"speech_decoder_prenet.decoder_prenet.0.0.prenet.1.0": "speecht5.decoder.prenet.layers.1",
"speech_decoder_prenet.decoder_prenet.0.1": "speecht5.decoder.prenet.final_layer",
"speech_decoder_prenet.decoder_prenet.1.alpha": "speecht5.decoder.prenet.encode_positions.alpha",
"speech_decoder_prenet.spkembs_layer.0": "speecht5.decoder.prenet.speaker_embeds_layer",
}
_UpperCAmelCase = {
"speech_decoder_postnet.feat_out": "speech_decoder_postnet.feat_out",
"speech_decoder_postnet.prob_out": "speech_decoder_postnet.prob_out",
"speech_decoder_postnet.postnet.postnet.0.0": "speech_decoder_postnet.layers.0.conv",
"speech_decoder_postnet.postnet.postnet.0.1": "speech_decoder_postnet.layers.0.batch_norm",
"speech_decoder_postnet.postnet.postnet.1.0": "speech_decoder_postnet.layers.1.conv",
"speech_decoder_postnet.postnet.postnet.1.1": "speech_decoder_postnet.layers.1.batch_norm",
"speech_decoder_postnet.postnet.postnet.2.0": "speech_decoder_postnet.layers.2.conv",
"speech_decoder_postnet.postnet.postnet.2.1": "speech_decoder_postnet.layers.2.batch_norm",
"speech_decoder_postnet.postnet.postnet.3.0": "speech_decoder_postnet.layers.3.conv",
"speech_decoder_postnet.postnet.postnet.3.1": "speech_decoder_postnet.layers.3.batch_norm",
"speech_decoder_postnet.postnet.postnet.4.0": "speech_decoder_postnet.layers.4.conv",
"speech_decoder_postnet.postnet.postnet.4.1": "speech_decoder_postnet.layers.4.batch_norm",
}
_UpperCAmelCase = {
"text_decoder_prenet.embed_tokens": "speecht5.decoder.prenet.embed_tokens",
}
_UpperCAmelCase = {
"text_decoder_postnet.output_projection": "text_decoder_postnet.lm_head",
}
_UpperCAmelCase = {
"encoder.layers.*.self_attn.k_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.k_proj",
"encoder.layers.*.self_attn.v_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.v_proj",
"encoder.layers.*.self_attn.q_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.q_proj",
"encoder.layers.*.self_attn.out_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.out_proj",
"encoder.layers.*.self_attn_layer_norm": "speecht5.encoder.wrapped_encoder.layers.*.layer_norm",
"encoder.layers.*.fc1": "speecht5.encoder.wrapped_encoder.layers.*.feed_forward.intermediate_dense",
"encoder.layers.*.fc2": "speecht5.encoder.wrapped_encoder.layers.*.feed_forward.output_dense",
"encoder.layers.*.final_layer_norm": "speecht5.encoder.wrapped_encoder.layers.*.final_layer_norm",
"encoder.layer_norm": "speecht5.encoder.wrapped_encoder.layer_norm",
"encoder.pos_emb.pe_k": "speecht5.encoder.wrapped_encoder.embed_positions.pe_k",
}
_UpperCAmelCase = {
"decoder.layers.*.self_attn.k_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.k_proj",
"decoder.layers.*.self_attn.v_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.v_proj",
"decoder.layers.*.self_attn.q_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.q_proj",
"decoder.layers.*.self_attn.out_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.out_proj",
"decoder.layers.*.self_attn_layer_norm": "speecht5.decoder.wrapped_decoder.layers.*.self_attn_layer_norm",
"decoder.layers.*.encoder_attn.k_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.k_proj",
"decoder.layers.*.encoder_attn.v_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.v_proj",
"decoder.layers.*.encoder_attn.q_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.q_proj",
"decoder.layers.*.encoder_attn.out_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.out_proj",
"decoder.layers.*.encoder_attn_layer_norm": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn_layer_norm",
"decoder.layers.*.fc1": "speecht5.decoder.wrapped_decoder.layers.*.feed_forward.intermediate_dense",
"decoder.layers.*.fc2": "speecht5.decoder.wrapped_decoder.layers.*.feed_forward.output_dense",
"decoder.layers.*.final_layer_norm": "speecht5.decoder.wrapped_decoder.layers.*.final_layer_norm",
}
_UpperCAmelCase = {
**MAPPING_SPEECH_ENCODER_PRENET,
**MAPPING_ENCODER,
**MAPPING_DECODER,
**MAPPING_TEXT_DECODER_PRENET,
**MAPPING_TEXT_DECODER_POSTNET,
}
_UpperCAmelCase = {
**MAPPING_TEXT_ENCODER_PRENET,
**MAPPING_ENCODER,
**MAPPING_DECODER,
**MAPPING_SPEECH_DECODER_PRENET,
**MAPPING_SPEECH_DECODER_POSTNET,
}
_UpperCAmelCase = {
**MAPPING_SPEECH_ENCODER_PRENET,
**MAPPING_ENCODER,
**MAPPING_DECODER,
**MAPPING_SPEECH_DECODER_PRENET,
**MAPPING_SPEECH_DECODER_POSTNET,
}
_UpperCAmelCase = []
_UpperCAmelCase = [
"encoder.version",
"encoder.layers.*.norm_k.weight",
"encoder.layers.*.norm_k.bias",
"decoder.version",
"decoder.layers.*.norm_k.weight",
"decoder.layers.*.norm_k.bias",
"decoder.pos_emb.pe_k",
"speech_encoder_prenet.embed_positions._float_tensor",
"text_decoder_prenet.embed_positions._float_tensor",
]
_UpperCAmelCase = IGNORE_KEYS + [
"encoder.proj",
"text_encoder_prenet.*",
"speech_decoder_prenet.*",
"speech_decoder_postnet.*",
]
_UpperCAmelCase = IGNORE_KEYS + [
"encoder.proj",
"speech_encoder_prenet.*",
"text_decoder_prenet.*",
"text_decoder_postnet.*",
]
_UpperCAmelCase = IGNORE_KEYS + [
"encoder.proj",
"text_encoder_prenet.*",
"text_decoder_prenet.*",
"text_decoder_postnet.*",
]
def _lowerCamelCase ( _a , _a , _a , _a , _a ):
"""simple docstring"""
for attribute in key.split('''.''' ):
_lowerCamelCase = getattr(_a , _a )
if weight_type is not None:
_lowerCamelCase = getattr(_a , _a ).shape
else:
_lowerCamelCase = hf_pointer.shape
if hf_shape != value.shape:
raise ValueError(
F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be'''
F''' {value.shape} for {full_name}''' )
if weight_type == "weight":
_lowerCamelCase = value
elif weight_type == "weight_g":
_lowerCamelCase = value
elif weight_type == "weight_v":
_lowerCamelCase = value
elif weight_type == "bias":
_lowerCamelCase = value
elif weight_type == "running_mean":
_lowerCamelCase = value
elif weight_type == "running_var":
_lowerCamelCase = value
elif weight_type == "num_batches_tracked":
_lowerCamelCase = value
else:
_lowerCamelCase = value
logger.info(F'''{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.''' )
def _lowerCamelCase ( _a , _a ):
"""simple docstring"""
for key in ignore_keys:
if key.endswith('''.*''' ):
if name.startswith(key[:-1] ):
return True
elif ".*." in key:
_lowerCamelCase , _lowerCamelCase = key.split('''.*.''' )
if prefix in name and suffix in name:
return True
elif key in name:
return True
return False
def _lowerCamelCase ( _a , _a , _a ):
"""simple docstring"""
_lowerCamelCase = []
if task == "s2t":
_lowerCamelCase = hf_model.speechta.encoder.prenet.feature_encoder
_lowerCamelCase = MAPPING_S2T
_lowerCamelCase = IGNORE_KEYS_S2T
elif task == "t2s":
_lowerCamelCase = None
_lowerCamelCase = MAPPING_T2S
_lowerCamelCase = IGNORE_KEYS_T2S
elif task == "s2s":
_lowerCamelCase = hf_model.speechta.encoder.prenet.feature_encoder
_lowerCamelCase = MAPPING_S2S
_lowerCamelCase = IGNORE_KEYS_S2S
else:
raise ValueError(F'''Unsupported task: {task}''' )
for name, value in fairseq_dict.items():
if should_ignore(_a , _a ):
logger.info(F'''{name} was ignored''' )
continue
_lowerCamelCase = False
if "conv_layers" in name:
load_conv_layer(
_a , _a , _a , _a , hf_model.config.feat_extract_norm == '''group''' , )
_lowerCamelCase = True
else:
for key, mapped_key in MAPPING.items():
# mapped_key = "speecht5." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if "*" in key:
_lowerCamelCase , _lowerCamelCase = key.split('''.*.''' )
if prefix in name and suffix in name:
_lowerCamelCase = suffix
# if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]:
if key in name:
_lowerCamelCase = True
if "*" in mapped_key:
_lowerCamelCase = name.split(_a )[0].split('''.''' )[-2]
_lowerCamelCase = mapped_key.replace('''*''' , _a )
if "weight_g" in name:
_lowerCamelCase = '''weight_g'''
elif "weight_v" in name:
_lowerCamelCase = '''weight_v'''
elif "bias" in name:
_lowerCamelCase = '''bias'''
elif "weight" in name:
_lowerCamelCase = '''weight'''
elif "running_mean" in name:
_lowerCamelCase = '''running_mean'''
elif "running_var" in name:
_lowerCamelCase = '''running_var'''
elif "num_batches_tracked" in name:
_lowerCamelCase = '''num_batches_tracked'''
else:
_lowerCamelCase = 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 _lowerCamelCase ( _a , _a , _a , _a , _a ):
"""simple docstring"""
_lowerCamelCase = full_name.split('''conv_layers.''' )[-1]
_lowerCamelCase = name.split('''.''' )
_lowerCamelCase = int(items[0] )
_lowerCamelCase = int(items[1] )
if type_id == 0:
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' )
_lowerCamelCase = value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' )
_lowerCamelCase = value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' )
_lowerCamelCase = value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' )
_lowerCamelCase = value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
else:
unused_weights.append(_a )
@torch.no_grad()
def _lowerCamelCase ( _a , _a , _a , _a=None , _a=None , _a=None , ):
"""simple docstring"""
if config_path is not None:
_lowerCamelCase = SpeechTaConfig.from_pretrained(_a )
else:
_lowerCamelCase = SpeechTaConfig()
if task == "s2t":
_lowerCamelCase = config.max_text_positions
_lowerCamelCase = SpeechTaForSpeechToText(_a )
elif task == "t2s":
_lowerCamelCase = 1_8_7_6
_lowerCamelCase = 6_0_0
_lowerCamelCase = config.max_speech_positions
_lowerCamelCase = SpeechTaForTextToSpeech(_a )
elif task == "s2s":
_lowerCamelCase = 1_8_7_6
_lowerCamelCase = config.max_speech_positions
_lowerCamelCase = SpeechTaForSpeechToSpeech(_a )
else:
raise ValueError(F'''Unknown task name: {task}''' )
if vocab_path:
_lowerCamelCase = SpeechTaTokenizer(_a , model_max_length=config.max_text_positions )
# Mask token behaves like a normal word, i.e. include the space before it
_lowerCamelCase = AddedToken('''<mask>''' , lstrip=_a , rstrip=_a )
_lowerCamelCase = mask_token
tokenizer.add_special_tokens({'''mask_token''': mask_token} )
tokenizer.add_tokens(['''<ctc_blank>'''] )
_lowerCamelCase = SpeechTaFeatureExtractor()
_lowerCamelCase = SpeechTaProcessor(tokenizer=_a , feature_extractor=_a )
processor.save_pretrained(_a )
_lowerCamelCase = torch.load(_a )
recursively_load_weights(fairseq_checkpoint['''model'''] , _a , _a )
model.save_pretrained(_a )
if repo_id:
print('''Pushing to the hub...''' )
processor.push_to_hub(_a )
model.push_to_hub(_a )
if __name__ == "__main__":
_UpperCAmelCase = argparse.ArgumentParser()
parser.add_argument(
"--task",
default="s2t",
type=str,
help="Type of the SpeechT5 model you'd like to convert. Should be one of 's2t', 't2s', 's2s'.",
)
parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to fairseq checkpoint")
parser.add_argument("--vocab_path", default=None, type=str, help="Path to SentencePiece model")
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
parser.add_argument(
"--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model."
)
parser.add_argument(
"--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub."
)
_UpperCAmelCase = parser.parse_args()
convert_speechta_checkpoint(
args.task,
args.checkpoint_path,
args.pytorch_dump_folder_path,
args.config_path,
args.vocab_path,
args.push_to_hub,
)
| 297 | 0 |
"""simple docstring"""
import numpy as np
import torch
from torch.utils.data import Dataset, IterableDataset
from ..utils.generic import ModelOutput
class a__ ( __lowercase ):
def __init__( self , _a , _a , _a ):
lowercase : Any = dataset
lowercase : str = process
lowercase : Union[str, Any] = params
def __len__( self ):
return len(self.dataset )
def __getitem__( self , _a ):
lowercase : Union[str, Any] = self.dataset[i]
lowercase : Dict = self.process(_a , **self.params )
return processed
class a__ ( __lowercase ):
def __init__( self , _a , _a , _a , _a=None ):
lowercase : Tuple = loader
lowercase : List[Any] = infer
lowercase : Tuple = params
if loader_batch_size == 1:
# Let's spare some time by deactivating altogether
lowercase : Any = None
lowercase : Tuple = loader_batch_size
# Internal bookkeeping
lowercase : Union[str, Any] = None
lowercase : Optional[Any] = None
def __len__( self ):
return len(self.loader )
def __iter__( self ):
lowercase : Dict = iter(self.loader )
return self
def __magic_name__ ( self ):
if isinstance(self._loader_batch_data , torch.Tensor ):
# Batch data is simple tensor, just fetch the slice
lowercase : List[Any] = self._loader_batch_data[self._loader_batch_index]
else:
# Batch data is assumed to be BaseModelOutput (or dict)
lowercase : Optional[Any] = {}
for k, element in self._loader_batch_data.items():
if isinstance(_a , _a ):
# Convert ModelOutput to tuple first
lowercase : int = element.to_tuple()
if isinstance(element[0] , torch.Tensor ):
lowercase : List[str] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element )
elif isinstance(element[0] , np.ndarray ):
lowercase : Optional[Any] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element )
continue
if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(_a , _a ):
# Those are stored as lists of tensors so need specific unbatching.
if isinstance(element[0] , torch.Tensor ):
lowercase : Any = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element )
elif isinstance(element[0] , np.ndarray ):
lowercase : Optional[Any] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element )
continue
if element is None:
# This can happen for optional data that get passed around
lowercase : Tuple = None
elif isinstance(element[self._loader_batch_index] , torch.Tensor ):
# Take correct batch data, but make it looked like batch_size=1
# For compatibility with other methods within transformers
lowercase : List[str] = element[self._loader_batch_index].unsqueeze(0 )
elif isinstance(element[self._loader_batch_index] , np.ndarray ):
# Take correct batch data, but make it looked like batch_size=1
# For compatibility with other methods within transformers
lowercase : Union[str, Any] = np.expand_dims(element[self._loader_batch_index] , 0 )
else:
# This is typically a list, so no need to `unsqueeze`.
lowercase : int = element[self._loader_batch_index]
# Recreate the element by reusing the original class to make it look
# batch_size=1
lowercase : Union[str, Any] = self._loader_batch_data.__class__(_a )
self._loader_batch_index += 1
return result
def __magic_name__ ( self ):
if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
# We are currently unrolling a batch so we just need to return
# the current item within a batch
return self.loader_batch_item()
# We're out of items within a batch
lowercase : List[Any] = next(self.iterator )
lowercase : Union[str, Any] = self.infer(_a , **self.params )
# We now have a batch of "inferred things".
if self.loader_batch_size is not None:
# Try to infer the size of the batch
if isinstance(_a , torch.Tensor ):
lowercase : List[Any] = processed
else:
lowercase : Optional[Any] = list(processed.keys() )[0]
lowercase : Dict = processed[key]
if isinstance(_a , _a ):
lowercase : List[str] = len(_a )
else:
lowercase : int = first_tensor.shape[0]
if 0 < observed_batch_size < self.loader_batch_size:
# could be last batch so we can't unroll as many
# elements.
lowercase : Optional[int] = observed_batch_size
# Setting internal index to unwrap the batch
lowercase : Union[str, Any] = processed
lowercase : Any = 0
return self.loader_batch_item()
else:
# We're not unrolling batches
return processed
class a__ ( __lowercase ):
def __init__( self , _a , _a , _a , _a=None ):
super().__init__(_a , _a , _a )
def __iter__( self ):
lowercase : Dict = iter(self.loader )
lowercase : List[str] = None
return self
def __magic_name__ ( self ):
if self.subiterator is None:
lowercase : Any = self.infer(next(self.iterator ) , **self.params )
try:
# Try to return next item
lowercase : List[Any] = next(self.subiterator )
except StopIteration:
# When a preprocess iterator ends, we can start lookig at the next item
# ChunkIterator will keep feeding until ALL elements of iterator
# all have created their subiterator and have been iterating against.
#
# Another way to look at it, is we're basically flattening lists of lists
# into a single list, but with generators
lowercase : List[Any] = self.infer(next(self.iterator ) , **self.params )
lowercase : List[str] = next(self.subiterator )
return processed
class a__ ( __lowercase ):
def __iter__( self ):
lowercase : Tuple = iter(self.loader )
return self
def __magic_name__ ( self ):
lowercase : Dict = False
lowercase : Union[str, Any] = []
if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
while self._loader_batch_index < self.loader_batch_size:
lowercase : Union[str, Any] = self.loader_batch_item()
lowercase : List[str] = item.pop("is_last" )
accumulator.append(_a )
if is_last:
return accumulator
while not is_last:
lowercase : Union[str, Any] = self.infer(next(self.iterator ) , **self.params )
if self.loader_batch_size is not None:
if isinstance(_a , torch.Tensor ):
lowercase : str = processed
else:
lowercase : Optional[Any] = list(processed.keys() )[0]
lowercase : List[str] = processed[key]
if isinstance(_a , _a ):
lowercase : Tuple = len(_a )
else:
lowercase : Dict = first_tensor.shape[0]
if 0 < observed_batch_size < self.loader_batch_size:
# could be last batch so we can't unroll as many
# elements.
lowercase : List[str] = observed_batch_size
lowercase : List[Any] = processed
lowercase : str = 0
while self._loader_batch_index < self.loader_batch_size:
lowercase : List[Any] = self.loader_batch_item()
lowercase : List[Any] = item.pop("is_last" )
accumulator.append(_a )
if is_last:
return accumulator
else:
lowercase : Tuple = processed
lowercase : List[Any] = item.pop("is_last" )
accumulator.append(_a )
return accumulator
class a__ ( __lowercase ):
def __init__( self , _a , _a ):
lowercase : List[Any] = dataset
lowercase : Optional[int] = key
def __len__( self ):
return len(self.dataset )
def __getitem__( self , _a ):
return self.dataset[i][self.key]
class a__ ( __lowercase ):
def __init__( self , _a , _a , _a ):
lowercase : List[str] = dataset
lowercase : Any = keya
lowercase : int = keya
def __len__( self ):
return len(self.dataset )
def __getitem__( self , _a ):
return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
| 361 |
'''simple docstring'''
import cva
import numpy as np
class _A :
def __init__( self : Any , __magic_name__ : float , __magic_name__ : int ) -> Optional[int]:
"""simple docstring"""
if k in (0.04, 0.06):
__snake_case : List[str] = k
__snake_case : int = window_size
else:
raise ValueError("""invalid k value""" )
def __str__( self : Union[str, Any] ) -> str:
"""simple docstring"""
return str(self.k )
def lowercase__ ( self : Dict , __magic_name__ : str ) -> tuple[cva.Mat, list[list[int]]]:
"""simple docstring"""
__snake_case : Dict = cva.imread(__magic_name__ , 0 )
__snake_case , __snake_case : List[str] = img.shape
__snake_case : list[list[int]] = []
__snake_case : str = img.copy()
__snake_case : Tuple = cva.cvtColor(__magic_name__ , cva.COLOR_GRAY2RGB )
__snake_case , __snake_case : List[Any] = np.gradient(__magic_name__ )
__snake_case : Optional[Any] = dx**2
__snake_case : Tuple = dy**2
__snake_case : List[Any] = dx * dy
__snake_case : List[Any] = 0.04
__snake_case : Tuple = self.window_size // 2
for y in range(__magic_name__ , h - offset ):
for x in range(__magic_name__ , w - offset ):
__snake_case : Dict = ixx[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
__snake_case : Optional[int] = iyy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
__snake_case : str = ixy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
__snake_case : List[str] = (wxx * wyy) - (wxy**2)
__snake_case : Dict = wxx + wyy
__snake_case : List[str] = 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_55 )
return color_img, corner_list
if __name__ == "__main__":
__UpperCamelCase = HarrisCorner(0.04, 3)
__UpperCamelCase , __UpperCamelCase = edge_detect.detect("path_to_image")
cva.imwrite("detect.png", color_img)
| 26 | 0 |
"""simple docstring"""
from .configuration_bert_masked import MaskedBertConfig
from .modeling_bert_masked import (
MaskedBertForMultipleChoice,
MaskedBertForQuestionAnswering,
MaskedBertForSequenceClassification,
MaskedBertForTokenClassification,
MaskedBertModel,
)
from .modules import *
| 712 |
"""simple docstring"""
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
lowerCamelCase_ = logging.get_logger(__name__)
lowerCamelCase_ = '''▁'''
lowerCamelCase_ = {'''vocab_file''': '''sentencepiece.bpe.model'''}
lowerCamelCase_ = {
'''vocab_file''': {
'''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model''',
}
}
lowerCamelCase_ = {
'''facebook/xglm-564M''': 2048,
}
class UpperCamelCase_ (__A ):
__magic_name__ = VOCAB_FILES_NAMES
__magic_name__ = PRETRAINED_VOCAB_FILES_MAP
__magic_name__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__magic_name__ = ['''input_ids''', '''attention_mask''']
def __init__( self : int , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Union[str, Any]="<s>" , lowerCAmelCase_ : Any="</s>" , lowerCAmelCase_ : Tuple="</s>" , lowerCAmelCase_ : List[str]="<s>" , lowerCAmelCase_ : Union[str, Any]="<unk>" , lowerCAmelCase_ : Any="<pad>" , lowerCAmelCase_ : Optional[Dict[str, Any]] = None , **lowerCAmelCase_ : List[str] , ) -> None:
UpperCAmelCase_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs
# Compatibility with the original tokenizer
UpperCAmelCase_ : Any = 7
UpperCAmelCase_ : Dict = [f"""<madeupword{i}>""" for i in range(self.num_madeup_words )]
UpperCAmelCase_ : Optional[int] = kwargs.get("additional_special_tokens" , [] )
kwargs["additional_special_tokens"] += [
word for word in madeup_words if word not in kwargs["additional_special_tokens"]
]
super().__init__(
bos_token=lowerCAmelCase_ , eos_token=lowerCAmelCase_ , unk_token=lowerCAmelCase_ , sep_token=lowerCAmelCase_ , cls_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **lowerCAmelCase_ , )
UpperCAmelCase_ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(lowerCAmelCase_ ) )
UpperCAmelCase_ : Union[str, Any] = vocab_file
# Original fairseq vocab and spm vocab must be "aligned":
# Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
# fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-'
# spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
UpperCAmelCase_ : int = 1
# Mimic fairseq token-to-id alignment for the first 4 token
UpperCAmelCase_ : Tuple = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}
UpperCAmelCase_ : List[str] = len(self.sp_model )
UpperCAmelCase_ : List[Any] = {f"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )}
self.fairseq_tokens_to_ids.update(lowerCAmelCase_ )
UpperCAmelCase_ : Tuple = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
def __getstate__( self : Tuple ) -> Union[str, Any]:
UpperCAmelCase_ : Tuple = self.__dict__.copy()
UpperCAmelCase_ : Dict = None
UpperCAmelCase_ : Optional[Any] = self.sp_model.serialized_model_proto()
return state
def __setstate__( self : Optional[Any] , lowerCAmelCase_ : Any ) -> Any:
UpperCAmelCase_ : Tuple = d
# for backward compatibility
if not hasattr(self , "sp_model_kwargs" ):
UpperCAmelCase_ : int = {}
UpperCAmelCase_ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.LoadFromSerializedProto(self.sp_model_proto )
def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None ) -> List[int]:
if token_ids_a is None:
return [self.sep_token_id] + token_ids_a
UpperCAmelCase_ : Optional[Any] = [self.sep_token_id]
return sep + token_ids_a + sep + sep + token_ids_a
def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None , lowerCAmelCase_ : bool = False ) -> List[int]:
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=lowerCAmelCase_ , token_ids_a=lowerCAmelCase_ , already_has_special_tokens=lowerCAmelCase_ )
if token_ids_a is None:
return [1] + ([0] * len(lowerCAmelCase_ ))
return [1] + ([0] * len(lowerCAmelCase_ )) + [1, 1] + ([0] * len(lowerCAmelCase_ ))
def _SCREAMING_SNAKE_CASE ( self : int , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None ) -> List[int]:
UpperCAmelCase_ : str = [self.sep_token_id]
if token_ids_a is None:
return len(sep + token_ids_a ) * [0]
return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0]
@property
def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any:
return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words
def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]:
UpperCAmelCase_ : Union[str, Any] = {self.convert_ids_to_tokens(lowerCAmelCase_ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def _SCREAMING_SNAKE_CASE ( self : int , lowerCAmelCase_ : str ) -> List[str]:
return self.sp_model.encode(lowerCAmelCase_ , out_type=lowerCAmelCase_ )
def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase_ : Optional[Any] ) -> Optional[int]:
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
UpperCAmelCase_ : Optional[int] = self.sp_model.PieceToId(lowerCAmelCase_ )
# Need to return unknown token if the SP model returned 0
return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase_ : Union[str, Any] ) -> Any:
if index in self.fairseq_ids_to_tokens:
return self.fairseq_ids_to_tokens[index]
return self.sp_model.IdToPiece(index - self.fairseq_offset )
def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase_ : Tuple ) -> Optional[int]:
UpperCAmelCase_ : Any = "".join(lowerCAmelCase_ ).replace(lowerCAmelCase_ , " " ).strip()
return out_string
def _SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ) -> Tuple[str]:
if not os.path.isdir(lowerCAmelCase_ ):
logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" )
return
UpperCAmelCase_ : List[Any] = os.path.join(
lowerCAmelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase_ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , lowerCAmelCase_ )
elif not os.path.isfile(self.vocab_file ):
with open(lowerCAmelCase_ , "wb" ) as fi:
UpperCAmelCase_ : str = self.sp_model.serialized_model_proto()
fi.write(lowerCAmelCase_ )
return (out_vocab_file,)
| 463 | 0 |
'''simple docstring'''
def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> int:
while second != 0:
lowerCamelCase_ = first & second
first ^= second
lowerCamelCase_ = 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) = }''')
| 42 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
A_ : List[Any] = logging.get_logger(__name__)
A_ : Optional[int] = {
"facebook/dpr-ctx_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-question_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-reader-single-nq-base": (
"https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-ctx_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json"
),
"facebook/dpr-question_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json"
),
"facebook/dpr-reader-multiset-base": (
"https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json"
),
}
class lowerCamelCase (A__ ):
lowerCamelCase__ : Optional[int] = 'dpr'
def __init__( self : Optional[int] , __UpperCAmelCase : List[str]=3_0_5_2_2 , __UpperCAmelCase : int=7_6_8 , __UpperCAmelCase : Optional[Any]=1_2 , __UpperCAmelCase : Dict=1_2 , __UpperCAmelCase : Any=3_0_7_2 , __UpperCAmelCase : int="gelu" , __UpperCAmelCase : int=0.1 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : Any=5_1_2 , __UpperCAmelCase : Union[str, Any]=2 , __UpperCAmelCase : Any=0.02 , __UpperCAmelCase : Dict=1e-12 , __UpperCAmelCase : Optional[Any]=0 , __UpperCAmelCase : Union[str, Any]="absolute" , __UpperCAmelCase : int = 0 , **__UpperCAmelCase : Dict , ) -> Tuple:
super().__init__(pad_token_id=__UpperCAmelCase , **__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = vocab_size
SCREAMING_SNAKE_CASE__ = hidden_size
SCREAMING_SNAKE_CASE__ = num_hidden_layers
SCREAMING_SNAKE_CASE__ = num_attention_heads
SCREAMING_SNAKE_CASE__ = hidden_act
SCREAMING_SNAKE_CASE__ = intermediate_size
SCREAMING_SNAKE_CASE__ = hidden_dropout_prob
SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE__ = max_position_embeddings
SCREAMING_SNAKE_CASE__ = type_vocab_size
SCREAMING_SNAKE_CASE__ = initializer_range
SCREAMING_SNAKE_CASE__ = layer_norm_eps
SCREAMING_SNAKE_CASE__ = projection_dim
SCREAMING_SNAKE_CASE__ = position_embedding_type
| 196 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase = logging.get_logger(__name__)
UpperCamelCase = {
"transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json",
}
class lowerCAmelCase_ ( __snake_case ):
_UpperCamelCase : Tuple = "transfo-xl"
_UpperCamelCase : Any = ["mems"]
_UpperCamelCase : Tuple = {
"n_token": "vocab_size",
"hidden_size": "d_model",
"num_attention_heads": "n_head",
"num_hidden_layers": "n_layer",
}
def __init__( self , _lowerCAmelCase=2_6_7_7_3_5 , _lowerCAmelCase=[2_0_0_0_0, 4_0_0_0_0, 2_0_0_0_0_0] , _lowerCAmelCase=1_0_2_4 , _lowerCAmelCase=1_0_2_4 , _lowerCAmelCase=1_6 , _lowerCAmelCase=6_4 , _lowerCAmelCase=4_0_9_6 , _lowerCAmelCase=4 , _lowerCAmelCase=False , _lowerCAmelCase=1_8 , _lowerCAmelCase=1_6_0_0 , _lowerCAmelCase=1_0_0_0 , _lowerCAmelCase=True , _lowerCAmelCase=True , _lowerCAmelCase=0 , _lowerCAmelCase=-1 , _lowerCAmelCase=True , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.0 , _lowerCAmelCase=True , _lowerCAmelCase="normal" , _lowerCAmelCase=0.01 , _lowerCAmelCase=0.01 , _lowerCAmelCase=0.02 , _lowerCAmelCase=1E-5 , _lowerCAmelCase=0 , **_lowerCAmelCase , ):
_lowercase : List[str] = vocab_size
_lowercase : Any = []
self.cutoffs.extend(_lowerCAmelCase )
if proj_share_all_but_first:
_lowercase : Any = [False] + [True] * len(self.cutoffs )
else:
_lowercase : List[str] = [False] + [False] * len(self.cutoffs )
_lowercase : List[str] = d_model
_lowercase : List[str] = d_embed
_lowercase : List[str] = d_head
_lowercase : List[str] = d_inner
_lowercase : Optional[Any] = div_val
_lowercase : str = pre_lnorm
_lowercase : List[Any] = n_layer
_lowercase : List[str] = n_head
_lowercase : Union[str, Any] = mem_len
_lowercase : List[str] = same_length
_lowercase : str = attn_type
_lowercase : List[Any] = clamp_len
_lowercase : List[str] = sample_softmax
_lowercase : Union[str, Any] = adaptive
_lowercase : List[Any] = dropout
_lowercase : List[Any] = dropatt
_lowercase : str = untie_r
_lowercase : Optional[int] = init
_lowercase : List[Any] = init_range
_lowercase : str = proj_init_std
_lowercase : int = init_std
_lowercase : Any = layer_norm_epsilon
super().__init__(eos_token_id=_lowerCAmelCase , **_lowerCAmelCase )
@property
def __a ( self ):
# Message copied from Transformer-XL documentation
logger.info(F"""The model {self.model_type} is one of the few models that has no sequence length limit.""" )
return -1
@max_position_embeddings.setter
def __a ( self , _lowerCAmelCase ):
# Message copied from Transformer-XL documentation
raise NotImplementedError(
F"""The model {self.model_type} is one of the few models that has no sequence length limit.""" )
| 710 |
from collections.abc import Sequence
def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> float:
return sum(c * (x**i) for i, c in enumerate(SCREAMING_SNAKE_CASE ) )
def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> float:
_lowercase : Optional[Any] = 0.0
for coeff in reversed(SCREAMING_SNAKE_CASE ):
_lowercase : Optional[int] = result * x + coeff
return result
if __name__ == "__main__":
UpperCamelCase = (0.0, 0.0, 5.0, 9.3, 7.0)
UpperCamelCase = 10.0
print(evaluate_poly(poly, x))
print(horner(poly, x))
| 677 | 0 |
'''simple docstring'''
import argparse
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt
if __name__ == "__main__":
UpperCAmelCase_ : int = argparse.ArgumentParser()
parser.add_argument(
'--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.'
)
parser.add_argument(
'--original_config_file',
type=str,
required=True,
help='The YAML config file corresponding to the original architecture.',
)
parser.add_argument(
'--num_in_channels',
default=None,
type=int,
help='The number of input channels. If `None` number of input channels will be automatically inferred.',
)
parser.add_argument(
'--image_size',
default=512,
type=int,
help=(
'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2'
' Base. Use 768 for Stable Diffusion v2.'
),
)
parser.add_argument(
'--extract_ema',
action='store_true',
help=(
'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights'
' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield'
' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.'
),
)
parser.add_argument(
'--upcast_attention',
action='store_true',
help=(
'Whether the attention computation should always be upcasted. This is necessary when running stable'
' diffusion 2.1.'
),
)
parser.add_argument(
'--from_safetensors',
action='store_true',
help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.',
)
parser.add_argument(
'--to_safetensors',
action='store_true',
help='Whether to store pipeline in safetensors format or not.',
)
parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.')
parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)')
def A_ ( _lowerCAmelCase : Any ):
"""simple docstring"""
if string == "True":
return True
elif string == "False":
return False
else:
raise ValueError(F'could not parse string as bool {string}' )
parser.add_argument(
'--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool
)
parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int)
UpperCAmelCase_ : Optional[Any] = parser.parse_args()
UpperCAmelCase_ : Tuple = download_controlnet_from_original_ckpt(
checkpoint_path=args.checkpoint_path,
original_config_file=args.original_config_file,
image_size=args.image_size,
extract_ema=args.extract_ema,
num_in_channels=args.num_in_channels,
upcast_attention=args.upcast_attention,
from_safetensors=args.from_safetensors,
device=args.device,
use_linear_projection=args.use_linear_projection,
cross_attention_dim=args.cross_attention_dim,
)
controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) | 44 |
'''simple docstring'''
import random
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
UNetaDConditionModel,
VideoToVideoSDPipeline,
)
from diffusers.utils import floats_tensor, is_xformers_available, skip_mps
from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device
from ..pipeline_params import (
TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
@skip_mps
class _snake_case (__SCREAMING_SNAKE_CASE , unittest.TestCase):
__A : Union[str, Any] =VideoToVideoSDPipeline
__A : Tuple =TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"}) - {"image", "width", "height"}
__A : Union[str, Any] =TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"}) - {"image"}
__A : str =PipelineTesterMixin.required_optional_params - {"latents"}
__A : Dict =False
# No `output_type`.
__A : Optional[int] =frozenset(
[
"num_inference_steps",
"generator",
"latents",
"return_dict",
"callback",
"callback_steps",
])
def UpperCamelCase__ ( self ):
torch.manual_seed(0 )
UpperCAmelCase_ : Optional[int] = UNetaDConditionModel(
block_out_channels=(32, 64, 64, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") ,up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") ,cross_attention_dim=32 ,attention_head_dim=4 ,)
UpperCAmelCase_ : int = DDIMScheduler(
beta_start=0.00085 ,beta_end=0.012 ,beta_schedule="scaled_linear" ,clip_sample=_snake_case ,set_alpha_to_one=_snake_case ,)
torch.manual_seed(0 )
UpperCAmelCase_ : Dict = AutoencoderKL(
block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] ,up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] ,latent_channels=4 ,sample_size=1_28 ,)
torch.manual_seed(0 )
UpperCAmelCase_ : Dict = CLIPTextConfig(
bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=10_00 ,hidden_act="gelu" ,projection_dim=5_12 ,)
UpperCAmelCase_ : Union[str, Any] = CLIPTextModel(_snake_case )
UpperCAmelCase_ : List[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
UpperCAmelCase_ : Optional[int] = {
"unet": unet,
"scheduler": scheduler,
"vae": vae,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
}
return components
def UpperCamelCase__ ( self ,_snake_case ,_snake_case=0 ):
# 3 frames
UpperCAmelCase_ : Dict = floats_tensor((1, 3, 3, 32, 32) ,rng=random.Random(_snake_case ) ).to(_snake_case )
if str(_snake_case ).startswith("mps" ):
UpperCAmelCase_ : Tuple = torch.manual_seed(_snake_case )
else:
UpperCAmelCase_ : Tuple = torch.Generator(device=_snake_case ).manual_seed(_snake_case )
UpperCAmelCase_ : Union[str, Any] = {
"prompt": "A painting of a squirrel eating a burger",
"video": video,
"generator": generator,
"num_inference_steps": 2,
"guidance_scale": 6.0,
"output_type": "pt",
}
return inputs
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : str = "cpu" # ensure determinism for the device-dependent torch.Generator
UpperCAmelCase_ : Dict = self.get_dummy_components()
UpperCAmelCase_ : str = VideoToVideoSDPipeline(**_snake_case )
UpperCAmelCase_ : int = sd_pipe.to(_snake_case )
sd_pipe.set_progress_bar_config(disable=_snake_case )
UpperCAmelCase_ : Tuple = self.get_dummy_inputs(_snake_case )
UpperCAmelCase_ : str = "np"
UpperCAmelCase_ : Dict = sd_pipe(**_snake_case ).frames
UpperCAmelCase_ : Tuple = frames[0][-3:, -3:, -1]
assert frames[0].shape == (32, 32, 3)
UpperCAmelCase_ : Dict = np.array([1_06, 1_17, 1_13, 1_74, 1_37, 1_12, 1_48, 1_51, 1_31] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
@unittest.skipIf(
torch_device != "cuda" or not is_xformers_available() ,reason="XFormers attention is only available with CUDA and `xformers` installed" ,)
def UpperCamelCase__ ( self ):
self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=_snake_case ,expected_max_diff=5E-3 )
@unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." )
def UpperCamelCase__ ( self ):
pass
@unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." )
def UpperCamelCase__ ( self ):
pass
@unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." )
def UpperCamelCase__ ( self ):
pass
def UpperCamelCase__ ( self ):
return super().test_progress_bar()
@slow
@skip_mps
class _snake_case (unittest.TestCase):
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : Dict = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" ,torch_dtype=torch.floataa )
pipe.enable_model_cpu_offload()
# 10 frames
UpperCAmelCase_ : str = torch.Generator(device="cpu" ).manual_seed(0 )
UpperCAmelCase_ : int = torch.randn((1, 10, 3, 10_24, 5_76) ,generator=_snake_case )
UpperCAmelCase_ : List[Any] = video.to("cuda" )
UpperCAmelCase_ : List[Any] = "Spiderman is surfing"
UpperCAmelCase_ : Optional[Any] = pipe(_snake_case ,video=_snake_case ,generator=_snake_case ,num_inference_steps=3 ,output_type="pt" ).frames
UpperCAmelCase_ : Any = np.array([-1.0458984, -1.1279297, -0.9663086, -0.91503906, -0.75097656] )
assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1E-2
| 71 | 0 |
import json
import multiprocessing as mp
import re
from collections import defaultdict
from functools import partial
from typing import Dict, List, Optional, Set, Tuple, Type
from datasets import Dataset
from datasketch import MinHash, MinHashLSH
from dpu_utils.utils.iterators import ThreadedIterator
from tqdm import tqdm
A__ = re.compile('''[^A-Za-z_0-9]''')
# parameters used in DuplicationIndex
A__ = 10
A__ = 256
def _lowerCAmelCase ( __lowerCAmelCase ) -> Optional[MinHash]:
"""simple docstring"""
if len(__lowerCAmelCase ) < MIN_NUM_TOKENS:
return None
snake_case__ : List[Any] = MinHash(num_perm=__lowerCAmelCase )
for token in set(__lowerCAmelCase ):
min_hash.update(token.encode() )
return min_hash
def _lowerCAmelCase ( __lowerCAmelCase ) -> Set[str]:
"""simple docstring"""
return {t for t in NON_ALPHA.split(__lowerCAmelCase ) if len(t.strip() ) > 0}
class a :
def __init__( self :Any ,*,
__lowercase :float = 0.85 ,):
snake_case__ : Union[str, Any] = duplication_jaccard_threshold
snake_case__ : Tuple = NUM_PERM
snake_case__ : Tuple = MinHashLSH(threshold=self._duplication_jaccard_threshold ,num_perm=self._num_perm )
snake_case__ : Tuple = defaultdict(__lowercase )
def __lowerCamelCase ( self :Optional[int] ,__lowercase :Tuple ,__lowercase :MinHash ):
snake_case__ : Tuple = self._index.query(__lowercase )
if code_key in self._index.keys:
print(F"""Duplicate key {code_key}""" )
return
self._index.insert(__lowercase ,__lowercase )
if len(__lowercase ) > 0:
for base_duplicate in close_duplicates:
if base_duplicate in self._duplicate_clusters:
self._duplicate_clusters[base_duplicate].add(__lowercase )
break
else:
self._duplicate_clusters[close_duplicates[0]].add(__lowercase )
def __lowerCamelCase ( self :Optional[int] ):
snake_case__ : str = []
for base, duplicates in self._duplicate_clusters.items():
snake_case__ : Optional[int] = [base] + list(__lowercase )
# reformat the cluster to be a list of dict
snake_case__ : Dict = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster]
duplicate_clusters.append(__lowercase )
return duplicate_clusters
def __lowerCamelCase ( self :List[str] ,__lowercase :Any ):
snake_case__ : List[Any] = self.get_duplicate_clusters()
with open(__lowercase ,'''w''' ) as f:
json.dump(__lowercase ,__lowercase )
def _lowerCAmelCase ( __lowerCAmelCase ) -> List[Any]:
"""simple docstring"""
snake_case__ , snake_case__ : Optional[int] = element
snake_case__ : List[str] = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] )
if min_hash is not None:
return (index, data["repo_name"], data["path"]), min_hash
def _lowerCAmelCase ( __lowerCAmelCase ) -> int:
"""simple docstring"""
with mp.Pool() as pool:
for data in pool.imap_unordered(
_compute_min_hash , ThreadedIterator(__lowerCAmelCase , max_queue_size=10000 ) , chunksize=100 , ):
if data is not None:
yield data
def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> Any:
"""simple docstring"""
snake_case__ : Any = DuplicationIndex(duplication_jaccard_threshold=__lowerCAmelCase )
for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(__lowerCAmelCase ) ) , max_queue_size=100 ) ):
di.add(__lowerCAmelCase , __lowerCAmelCase )
# Returns a List[Cluster] where Cluster is List[str] with the filenames.
return di.get_duplicate_clusters()
def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> float:
"""simple docstring"""
snake_case__ : Union[str, Any] = get_tokens(__lowerCAmelCase )
snake_case__ : Dict = get_tokens(__lowerCAmelCase )
return len(tokensa & tokensa ) / len(tokensa | tokensa )
A__ = None
def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]:
"""simple docstring"""
snake_case__ : Tuple = []
for elementa in cluster:
snake_case__ : Union[str, Any] = _shared_dataset[elementa['''base_index''']]['''content''']
for elementa in extremes:
snake_case__ : List[Any] = _shared_dataset[elementa['''base_index''']]['''content''']
if jaccard_similarity(__lowerCAmelCase , __lowerCAmelCase ) >= jaccard_threshold:
elementa["copies"] += 1
break
else:
snake_case__ : Tuple = 1
extremes.append(__lowerCAmelCase )
return extremes
def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]:
"""simple docstring"""
global _shared_dataset
snake_case__ : Tuple = dataset
snake_case__ : Union[str, Any] = []
snake_case__ : Union[str, Any] = partial(_find_cluster_extremes_shared , jaccard_threshold=__lowerCAmelCase )
with mp.Pool() as pool:
for extremes in tqdm(
pool.imap_unordered(
__lowerCAmelCase , __lowerCAmelCase , ) , total=len(__lowerCAmelCase ) , ):
extremes_list.append(__lowerCAmelCase )
return extremes_list
def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]:
"""simple docstring"""
snake_case__ : List[Any] = make_duplicate_clusters(__lowerCAmelCase , __lowerCAmelCase )
snake_case__ : Any = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster}
snake_case__ : str = {}
snake_case__ : List[str] = find_extremes(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
for extremes in extremes_clusters:
for element in extremes:
snake_case__ : str = element
snake_case__ : Optional[int] = duplicate_indices - set(extreme_dict.keys() )
snake_case__ : List[str] = dataset.filter(lambda __lowerCAmelCase , __lowerCAmelCase : idx not in remove_indices , with_indices=__lowerCAmelCase )
# update duplicate_clusters
for cluster in duplicate_clusters:
for element in cluster:
snake_case__ : Any = element['''base_index'''] in extreme_dict
if element["is_extreme"]:
snake_case__ : List[str] = extreme_dict[element['''base_index''']]['''copies''']
print(f"""Original dataset size: {len(__lowerCAmelCase )}""" )
print(f"""Number of duplicate clusters: {len(__lowerCAmelCase )}""" )
print(f"""Files in duplicate cluster: {len(__lowerCAmelCase )}""" )
print(f"""Unique files in duplicate cluster: {len(__lowerCAmelCase )}""" )
print(f"""Filtered dataset size: {len(__lowerCAmelCase )}""" )
return ds_filter, duplicate_clusters
| 219 |
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 ( __lowerCamelCase , unittest.TestCase ):
__lowerCAmelCase : str = ShapEPipeline
__lowerCAmelCase : Union[str, Any] = ["""prompt"""]
__lowerCAmelCase : Union[str, Any] = ["""prompt"""]
__lowerCAmelCase : Tuple = [
"""num_images_per_prompt""",
"""num_inference_steps""",
"""generator""",
"""latents""",
"""guidance_scale""",
"""frame_size""",
"""output_type""",
"""return_dict""",
]
__lowerCAmelCase : Optional[Any] = False
@property
def __lowerCamelCase ( self :Dict ):
return 3_2
@property
def __lowerCamelCase ( self :str ):
return 3_2
@property
def __lowerCamelCase ( self :Optional[int] ):
return self.time_input_dim * 4
@property
def __lowerCamelCase ( self :int ):
return 8
@property
def __lowerCamelCase ( self :int ):
snake_case__ : Optional[Any] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )
return tokenizer
@property
def __lowerCamelCase ( self :int ):
torch.manual_seed(0 )
snake_case__ : Optional[Any] = 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-0_5 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_0_0_0 ,)
return CLIPTextModelWithProjection(__lowercase )
@property
def __lowerCamelCase ( self :str ):
torch.manual_seed(0 )
snake_case__ : Optional[Any] = {
'''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[int] = PriorTransformer(**__lowercase )
return model
@property
def __lowerCamelCase ( self :Optional[int] ):
torch.manual_seed(0 )
snake_case__ : Dict = {
'''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[str] = ShapERenderer(**__lowercase )
return model
def __lowerCamelCase ( self :Union[str, Any] ):
snake_case__ : str = self.dummy_prior
snake_case__ : Optional[Any] = self.dummy_text_encoder
snake_case__ : List[Any] = self.dummy_tokenizer
snake_case__ : Optional[int] = self.dummy_renderer
snake_case__ : str = HeunDiscreteScheduler(
beta_schedule='''exp''' ,num_train_timesteps=1_0_2_4 ,prediction_type='''sample''' ,use_karras_sigmas=__lowercase ,clip_sample=__lowercase ,clip_sample_range=1.0 ,)
snake_case__ : Tuple = {
'''prior''': prior,
'''text_encoder''': text_encoder,
'''tokenizer''': tokenizer,
'''renderer''': renderer,
'''scheduler''': scheduler,
}
return components
def __lowerCamelCase ( self :Union[str, Any] ,__lowercase :int ,__lowercase :str=0 ):
if str(__lowercase ).startswith('''mps''' ):
snake_case__ : List[str] = torch.manual_seed(__lowercase )
else:
snake_case__ : Optional[Any] = torch.Generator(device=__lowercase ).manual_seed(__lowercase )
snake_case__ : Optional[int] = {
'''prompt''': '''horse''',
'''generator''': generator,
'''num_inference_steps''': 1,
'''frame_size''': 3_2,
'''output_type''': '''np''',
}
return inputs
def __lowerCamelCase ( self :Tuple ):
snake_case__ : str = '''cpu'''
snake_case__ : str = self.get_dummy_components()
snake_case__ : Optional[Any] = self.pipeline_class(**__lowercase )
snake_case__ : Tuple = pipe.to(__lowercase )
pipe.set_progress_bar_config(disable=__lowercase )
snake_case__ : Tuple = pipe(**self.get_dummy_inputs(__lowercase ) )
snake_case__ : Dict = output.images[0]
snake_case__ : Dict = image[0, -3:, -3:, -1]
assert image.shape == (2_0, 3_2, 3_2, 3)
snake_case__ : Tuple = np.array(
[
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def __lowerCamelCase ( self :Any ):
# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
self._test_inference_batch_consistent(batch_sizes=[1, 2] )
def __lowerCamelCase ( self :Optional[int] ):
snake_case__ : Optional[int] = torch_device == '''cpu'''
snake_case__ : Dict = True
self._test_inference_batch_single_identical(
batch_size=2 ,test_max_difference=__lowercase ,relax_max_difference=__lowercase ,)
def __lowerCamelCase ( self :Union[str, Any] ):
snake_case__ : List[Any] = self.get_dummy_components()
snake_case__ : Any = self.pipeline_class(**__lowercase )
snake_case__ : str = pipe.to(__lowercase )
pipe.set_progress_bar_config(disable=__lowercase )
snake_case__ : Any = 1
snake_case__ : str = 2
snake_case__ : Any = self.get_dummy_inputs(__lowercase )
for key in inputs.keys():
if key in self.batch_params:
snake_case__ : Optional[Any] = batch_size * [inputs[key]]
snake_case__ : Any = pipe(**__lowercase ,num_images_per_prompt=__lowercase )[0]
assert images.shape[0] == batch_size * num_images_per_prompt
@slow
@require_torch_gpu
class a ( unittest.TestCase ):
def __lowerCamelCase ( self :List[Any] ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __lowerCamelCase ( self :Optional[int] ):
snake_case__ : Tuple = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/shap_e/test_shap_e_np_out.npy''' )
snake_case__ : Optional[int] = ShapEPipeline.from_pretrained('''openai/shap-e''' )
snake_case__ : Any = pipe.to(__lowercase )
pipe.set_progress_bar_config(disable=__lowercase )
snake_case__ : Optional[int] = torch.Generator(device=__lowercase ).manual_seed(0 )
snake_case__ : Tuple = pipe(
'''a shark''' ,generator=__lowercase ,guidance_scale=15.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(__lowercase ,__lowercase )
| 219 | 1 |
import argparse
from collections import OrderedDict
from pathlib import Path
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from torchvision.transforms import functional as F
from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection
from transformers.utils import logging
logging.set_verbosity_info()
__magic_name__ : Dict = logging.get_logger(__name__)
# here we list all keys to be renamed (original name on the left, our name on the right)
__magic_name__ : List[Any] = []
for i in range(6):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append(
(F'transformer.encoder.layers.{i}.self_attn.out_proj.weight', F'encoder.layers.{i}.self_attn.out_proj.weight')
)
rename_keys.append(
(F'transformer.encoder.layers.{i}.self_attn.out_proj.bias', F'encoder.layers.{i}.self_attn.out_proj.bias')
)
rename_keys.append((F'transformer.encoder.layers.{i}.linear1.weight', F'encoder.layers.{i}.fc1.weight'))
rename_keys.append((F'transformer.encoder.layers.{i}.linear1.bias', F'encoder.layers.{i}.fc1.bias'))
rename_keys.append((F'transformer.encoder.layers.{i}.linear2.weight', F'encoder.layers.{i}.fc2.weight'))
rename_keys.append((F'transformer.encoder.layers.{i}.linear2.bias', F'encoder.layers.{i}.fc2.bias'))
rename_keys.append(
(F'transformer.encoder.layers.{i}.norm1.weight', F'encoder.layers.{i}.self_attn_layer_norm.weight')
)
rename_keys.append((F'transformer.encoder.layers.{i}.norm1.bias', F'encoder.layers.{i}.self_attn_layer_norm.bias'))
rename_keys.append((F'transformer.encoder.layers.{i}.norm2.weight', F'encoder.layers.{i}.final_layer_norm.weight'))
rename_keys.append((F'transformer.encoder.layers.{i}.norm2.bias', F'encoder.layers.{i}.final_layer_norm.bias'))
# decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms
rename_keys.append(
(F'transformer.decoder.layers.{i}.self_attn.out_proj.weight', F'decoder.layers.{i}.self_attn.out_proj.weight')
)
rename_keys.append(
(F'transformer.decoder.layers.{i}.self_attn.out_proj.bias', F'decoder.layers.{i}.self_attn.out_proj.bias')
)
rename_keys.append(
(
F'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight',
F'decoder.layers.{i}.encoder_attn.out_proj.weight',
)
)
rename_keys.append(
(
F'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias',
F'decoder.layers.{i}.encoder_attn.out_proj.bias',
)
)
rename_keys.append((F'transformer.decoder.layers.{i}.linear1.weight', F'decoder.layers.{i}.fc1.weight'))
rename_keys.append((F'transformer.decoder.layers.{i}.linear1.bias', F'decoder.layers.{i}.fc1.bias'))
rename_keys.append((F'transformer.decoder.layers.{i}.linear2.weight', F'decoder.layers.{i}.fc2.weight'))
rename_keys.append((F'transformer.decoder.layers.{i}.linear2.bias', F'decoder.layers.{i}.fc2.bias'))
rename_keys.append(
(F'transformer.decoder.layers.{i}.norm1.weight', F'decoder.layers.{i}.self_attn_layer_norm.weight')
)
rename_keys.append((F'transformer.decoder.layers.{i}.norm1.bias', F'decoder.layers.{i}.self_attn_layer_norm.bias'))
rename_keys.append(
(F'transformer.decoder.layers.{i}.norm2.weight', F'decoder.layers.{i}.encoder_attn_layer_norm.weight')
)
rename_keys.append(
(F'transformer.decoder.layers.{i}.norm2.bias', F'decoder.layers.{i}.encoder_attn_layer_norm.bias')
)
rename_keys.append((F'transformer.decoder.layers.{i}.norm3.weight', F'decoder.layers.{i}.final_layer_norm.weight'))
rename_keys.append((F'transformer.decoder.layers.{i}.norm3.bias', F'decoder.layers.{i}.final_layer_norm.bias'))
# convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads
rename_keys.extend(
[
('''input_proj.weight''', '''input_projection.weight'''),
('''input_proj.bias''', '''input_projection.bias'''),
('''query_embed.weight''', '''query_position_embeddings.weight'''),
('''transformer.encoder.norm.weight''', '''encoder.layernorm.weight'''),
('''transformer.encoder.norm.bias''', '''encoder.layernorm.bias'''),
('''transformer.decoder.norm.weight''', '''decoder.layernorm.weight'''),
('''transformer.decoder.norm.bias''', '''decoder.layernorm.bias'''),
('''class_embed.weight''', '''class_labels_classifier.weight'''),
('''class_embed.bias''', '''class_labels_classifier.bias'''),
('''bbox_embed.layers.0.weight''', '''bbox_predictor.layers.0.weight'''),
('''bbox_embed.layers.0.bias''', '''bbox_predictor.layers.0.bias'''),
('''bbox_embed.layers.1.weight''', '''bbox_predictor.layers.1.weight'''),
('''bbox_embed.layers.1.bias''', '''bbox_predictor.layers.1.bias'''),
('''bbox_embed.layers.2.weight''', '''bbox_predictor.layers.2.weight'''),
('''bbox_embed.layers.2.bias''', '''bbox_predictor.layers.2.bias'''),
]
)
def lowercase__ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase = state_dict.pop(_UpperCamelCase)
UpperCamelCase = val
def lowercase__ ( _UpperCamelCase) -> Dict:
"""simple docstring"""
UpperCamelCase = OrderedDict()
for key, value in state_dict.items():
if "backbone.0.body" in key:
UpperCamelCase = key.replace('backbone.0.body' , 'backbone.conv_encoder.model')
UpperCamelCase = value
else:
UpperCamelCase = value
return new_state_dict
def lowercase__ ( _UpperCamelCase) -> List[str]:
"""simple docstring"""
UpperCamelCase = ''
# first: transformer encoder
for i in range(6):
# read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias)
UpperCamelCase = state_dict.pop(F'{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight')
UpperCamelCase = state_dict.pop(F'{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias')
# next, add query, keys and values (in that order) to the state dict
UpperCamelCase = in_proj_weight[:2_56, :]
UpperCamelCase = in_proj_bias[:2_56]
UpperCamelCase = in_proj_weight[2_56:5_12, :]
UpperCamelCase = in_proj_bias[2_56:5_12]
UpperCamelCase = in_proj_weight[-2_56:, :]
UpperCamelCase = in_proj_bias[-2_56:]
# next: transformer decoder (which is a bit more complex because it also includes cross-attention)
for i in range(6):
# read in weights + bias of input projection layer of self-attention
UpperCamelCase = state_dict.pop(F'{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight')
UpperCamelCase = state_dict.pop(F'{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias')
# next, add query, keys and values (in that order) to the state dict
UpperCamelCase = in_proj_weight[:2_56, :]
UpperCamelCase = in_proj_bias[:2_56]
UpperCamelCase = in_proj_weight[2_56:5_12, :]
UpperCamelCase = in_proj_bias[2_56:5_12]
UpperCamelCase = in_proj_weight[-2_56:, :]
UpperCamelCase = in_proj_bias[-2_56:]
# read in weights + bias of input projection layer of cross-attention
UpperCamelCase = state_dict.pop(
F'{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight')
UpperCamelCase = state_dict.pop(F'{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias')
# next, add query, keys and values (in that order) of cross-attention to the state dict
UpperCamelCase = in_proj_weight_cross_attn[:2_56, :]
UpperCamelCase = in_proj_bias_cross_attn[:2_56]
UpperCamelCase = in_proj_weight_cross_attn[2_56:5_12, :]
UpperCamelCase = in_proj_bias_cross_attn[2_56:5_12]
UpperCamelCase = in_proj_weight_cross_attn[-2_56:, :]
UpperCamelCase = in_proj_bias_cross_attn[-2_56:]
def lowercase__ ( _UpperCamelCase , _UpperCamelCase) -> int:
"""simple docstring"""
UpperCamelCase , UpperCamelCase = image.size
UpperCamelCase = max(_UpperCamelCase , _UpperCamelCase)
UpperCamelCase = 8_00 if 'detection' in checkpoint_url else 10_00
UpperCamelCase = target_max_size / current_max_size
UpperCamelCase = image.resize((int(round(scale * width)), int(round(scale * height))))
return resized_image
def lowercase__ ( _UpperCamelCase) -> Tuple:
"""simple docstring"""
UpperCamelCase = F.to_tensor(_UpperCamelCase)
UpperCamelCase = F.normalize(_UpperCamelCase , mean=[0.4_8_5, 0.4_5_6, 0.4_0_6] , std=[0.2_2_9, 0.2_2_4, 0.2_2_5])
return image
@torch.no_grad()
def lowercase__ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase) -> List[str]:
"""simple docstring"""
logger.info('Converting model...')
# load original state dict
UpperCamelCase = torch.hub.load_state_dict_from_url(_UpperCamelCase , map_location='cpu')
# rename keys
for src, dest in rename_keys:
rename_key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase)
UpperCamelCase = rename_backbone_keys(_UpperCamelCase)
# query, key and value matrices need special treatment
read_in_q_k_v(_UpperCamelCase)
# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
UpperCamelCase = 'model.'
for key in state_dict.copy().keys():
if not key.startswith('class_labels_classifier') and not key.startswith('bbox_predictor'):
UpperCamelCase = state_dict.pop(_UpperCamelCase)
UpperCamelCase = val
# create HuggingFace model and load state dict
UpperCamelCase = TableTransformerConfig(
backbone='resnet18' , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , )
if "detection" in checkpoint_url:
UpperCamelCase = 15
UpperCamelCase = 2
UpperCamelCase = {0: 'table', 1: 'table rotated'}
UpperCamelCase = idalabel
UpperCamelCase = {v: k for k, v in idalabel.items()}
else:
UpperCamelCase = 1_25
UpperCamelCase = 6
UpperCamelCase = {
0: 'table',
1: 'table column',
2: 'table row',
3: 'table column header',
4: 'table projected row header',
5: 'table spanning cell',
}
UpperCamelCase = idalabel
UpperCamelCase = {v: k for k, v in idalabel.items()}
UpperCamelCase = DetrImageProcessor(
format='coco_detection' , max_size=8_00 if 'detection' in checkpoint_url else 10_00)
UpperCamelCase = TableTransformerForObjectDetection(_UpperCamelCase)
model.load_state_dict(_UpperCamelCase)
model.eval()
# verify our conversion
UpperCamelCase = 'example_pdf.png' if 'detection' in checkpoint_url else 'example_table.png'
UpperCamelCase = hf_hub_download(repo_id='nielsr/example-pdf' , repo_type='dataset' , filename=_UpperCamelCase)
UpperCamelCase = Image.open(_UpperCamelCase).convert('RGB')
UpperCamelCase = normalize(resize(_UpperCamelCase , _UpperCamelCase)).unsqueeze(0)
UpperCamelCase = model(_UpperCamelCase)
if "detection" in checkpoint_url:
UpperCamelCase = (1, 15, 3)
UpperCamelCase = torch.tensor(
[[-6.7_8_9_7, -1_6.9_9_8_5, 6.7_9_3_7], [-8.0_1_8_6, -2_2.2_1_9_2, 6.9_6_7_7], [-7.3_1_1_7, -2_1.0_7_0_8, 7.4_0_5_5]])
UpperCamelCase = torch.tensor([[0.4_8_6_7, 0.1_7_6_7, 0.6_7_3_2], [0.6_7_1_8, 0.4_4_7_9, 0.3_8_3_0], [0.4_7_1_6, 0.1_7_6_0, 0.6_3_6_4]])
else:
UpperCamelCase = (1, 1_25, 7)
UpperCamelCase = torch.tensor(
[[-1_8.1_4_3_0, -8.3_2_1_4, 4.8_2_7_4], [-1_8.4_6_8_5, -7.1_3_6_1, -4.2_6_6_7], [-2_6.3_6_9_3, -9.3_4_2_9, -4.9_9_6_2]])
UpperCamelCase = torch.tensor([[0.4_9_8_3, 0.5_5_9_5, 0.9_4_4_0], [0.4_9_1_6, 0.6_3_1_5, 0.5_9_5_4], [0.6_1_0_8, 0.8_6_3_7, 0.1_1_3_5]])
assert outputs.logits.shape == expected_shape
assert torch.allclose(outputs.logits[0, :3, :3] , _UpperCamelCase , atol=1e-4)
assert torch.allclose(outputs.pred_boxes[0, :3, :3] , _UpperCamelCase , atol=1e-4)
print('Looks ok!')
if pytorch_dump_folder_path is not None:
# Save model and image processor
logger.info(F'Saving PyTorch model and image processor to {pytorch_dump_folder_path}...')
Path(_UpperCamelCase).mkdir(exist_ok=_UpperCamelCase)
model.save_pretrained(_UpperCamelCase)
image_processor.save_pretrained(_UpperCamelCase)
if push_to_hub:
# Push model to HF hub
logger.info('Pushing model to the hub...')
UpperCamelCase = (
'microsoft/table-transformer-detection'
if 'detection' in checkpoint_url
else 'microsoft/table-transformer-structure-recognition'
)
model.push_to_hub(_UpperCamelCase)
image_processor.push_to_hub(_UpperCamelCase)
if __name__ == "__main__":
__magic_name__ : Optional[Any] = argparse.ArgumentParser()
parser.add_argument(
'''--checkpoint_url''',
default='''https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth''',
type=str,
choices=[
'''https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth''',
'''https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth''',
],
help='''URL of the Table Transformer checkpoint you\'d like to convert.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.'''
)
parser.add_argument(
'''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
)
__magic_name__ : int = parser.parse_args()
convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
| 280 |
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile
from transformers import MaMaaaTokenizer, is_torch_available
from transformers.testing_utils import (
get_tests_dir,
nested_simplify,
require_sentencepiece,
require_tokenizers,
require_torch,
slow,
)
from transformers.utils import is_sentencepiece_available
if is_sentencepiece_available():
from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json
from ...test_tokenization_common import TokenizerTesterMixin
if is_sentencepiece_available():
__magic_name__ : Any = get_tests_dir('''fixtures/test_sentencepiece.model''')
if is_torch_available():
from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right
__magic_name__ : Optional[Any] = 12_8022
__magic_name__ : Dict = 12_8028
@require_sentencepiece
class A__ ( __snake_case , unittest.TestCase ):
'''simple docstring'''
snake_case__ = MaMaaaTokenizer
snake_case__ = False
snake_case__ = False
snake_case__ = True
def _SCREAMING_SNAKE_CASE ( self : List[str] ):
"""simple docstring"""
super().setUp()
UpperCamelCase = ['</s>', '<unk>', '▁This', '▁is', '▁a', '▁t', 'est', '\u0120', '<pad>']
UpperCamelCase = dict(zip(_SCREAMING_SNAKE_CASE , range(len(_SCREAMING_SNAKE_CASE ) ) ) )
UpperCamelCase = Path(self.tmpdirname )
save_json(_SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['vocab_file'] )
if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
copyfile(_SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['spm_file'] )
UpperCamelCase = MaMaaaTokenizer.from_pretrained(self.tmpdirname )
tokenizer.save_pretrained(self.tmpdirname )
def _SCREAMING_SNAKE_CASE ( self : str , **_SCREAMING_SNAKE_CASE : List[str] ):
"""simple docstring"""
return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
return (
"This is a test",
"This is a test",
)
def _SCREAMING_SNAKE_CASE ( self : List[Any] ):
"""simple docstring"""
UpperCamelCase = '</s>'
UpperCamelCase = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ):
"""simple docstring"""
UpperCamelCase = self.get_tokenizer()
UpperCamelCase = list(tokenizer.get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '</s>' )
self.assertEqual(vocab_keys[1] , '<unk>' )
self.assertEqual(vocab_keys[-1] , '<s>' )
self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) )
@unittest.skip('Skip this test while all models are still to be uploaded.' )
def _SCREAMING_SNAKE_CASE ( self : str ):
"""simple docstring"""
pass
def _SCREAMING_SNAKE_CASE ( self : Any ):
"""simple docstring"""
UpperCamelCase = self.get_tokenizer()
UpperCamelCase = tokenizer.tokenize('This is a test' )
self.assertListEqual(_SCREAMING_SNAKE_CASE , ['▁This', '▁is', '▁a', '▁t', 'est'] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) , [2, 3, 4, 5, 6] , )
UpperCamelCase = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] )
self.assertListEqual(_SCREAMING_SNAKE_CASE , ['▁This', '▁is', '▁a', '▁t', 'est'] )
UpperCamelCase = tokenizer.convert_tokens_to_string(_SCREAMING_SNAKE_CASE )
self.assertEqual(_SCREAMING_SNAKE_CASE , 'This is a test' )
@slow
def _SCREAMING_SNAKE_CASE ( self : str ):
"""simple docstring"""
UpperCamelCase = {'input_ids': [[12_8022, 11_0108, 397, 11, 3_8272, 2247, 12_4811, 285, 1_8105, 1586, 207, 7, 3_9534, 4428, 397, 1019, 1_8105, 1586, 207, 7, 4_1337, 1_6786, 241, 7, 2_0214, 17, 12_5690, 1_0398, 7, 4_4378, 5_8069, 6_8342, 7798, 7343, 11, 299, 3_3310, 4, 158, 3_7350, 9_4077, 4569, 299, 3_3310, 90, 4, 5_2840, 290, 4, 3_1270, 112, 299, 682, 4, 5_2840, 3_9953, 1_4079, 193, 5_2519, 9_0894, 1_7894, 12_0697, 11, 4_0445, 551, 17, 1019, 5_2519, 9_0894, 1_7756, 963, 11, 4_0445, 480, 17, 9792, 1120, 5173, 1393, 6240, 1_6786, 241, 12_0996, 28, 1245, 1393, 11_8240, 1_1123, 1019, 9_3612, 2691, 1_0618, 9_8058, 12_0409, 1928, 279, 4, 4_0683, 367, 178, 207, 1019, 103, 10_3121, 506, 6_5296, 5, 2], [12_8022, 2_1217, 367, 117, 12_5450, 128, 719, 7, 7308, 40, 9_3612, 1_2669, 1116, 1_6704, 71, 1_7785, 3699, 1_5592, 35, 144, 9584, 241, 1_1943, 713, 950, 799, 2247, 8_8427, 150, 149, 11_8813, 12_0706, 1019, 10_6906, 8_1518, 28, 1224, 2_2799, 397, 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], [12_8022, 1658, 12_3311, 5155, 5578, 4722, 279, 1_4947, 2366, 1120, 1197, 14, 1348, 9232, 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]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=_SCREAMING_SNAKE_CASE , model_name='facebook/m2m100_418M' , revision='c168bae485c864188cf9aa0e4108b0b6934dc91e' , )
@require_torch
@require_sentencepiece
@require_tokenizers
class A__ ( unittest.TestCase ):
'''simple docstring'''
snake_case__ = """facebook/m2m100_418M"""
snake_case__ = [
"""In my opinion, there are two levels of response from the French government.""",
"""NSA Affair Emphasizes Complete Lack of Debate on Intelligence""",
]
snake_case__ = [
"""Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""",
"""L'affaire NSA souligne l'absence totale de débat sur le renseignement""",
]
# fmt: off
snake_case__ = [EN_CODE, 5_93, 19_49, 11_57_81, 4, 7_15_86, 42_34, 6_06_33, 12_62_33, 4_32, 12_38_08, 1_55_92, 11_97, 11_71_32, 12_06_18, 5, 2]
@classmethod
def _SCREAMING_SNAKE_CASE ( cls : Any ):
"""simple docstring"""
UpperCamelCase = MaMaaaTokenizer.from_pretrained(
cls.checkpoint_name , src_lang='en' , tgt_lang='fr' )
UpperCamelCase = 1
return cls
def _SCREAMING_SNAKE_CASE ( self : str ):
"""simple docstring"""
self.assertEqual(self.tokenizer.get_lang_id('ar' ) , 12_8006 )
self.assertEqual(self.tokenizer.get_lang_id('en' ) , 12_8022 )
self.assertEqual(self.tokenizer.get_lang_id('ro' ) , 12_8076 )
self.assertEqual(self.tokenizer.get_lang_id('mr' ) , 12_8063 )
def _SCREAMING_SNAKE_CASE ( self : Tuple ):
"""simple docstring"""
UpperCamelCase = self.tokenizer.get_vocab()
self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , self.tokenizer.vocab_size )
self.assertEqual(vocab['<unk>'] , 3 )
self.assertIn(self.tokenizer.get_lang_token('en' ) , _SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ):
"""simple docstring"""
UpperCamelCase = 'en'
UpperCamelCase = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0]
self.assertListEqual(self.expected_src_tokens , _SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ):
"""simple docstring"""
self.assertIn(_SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids )
# fmt: off
UpperCamelCase = [FR_CODE, 5364, 82, 8642, 4, 294, 47, 8, 1_4028, 136, 3286, 9706, 6, 9_0797, 6, 14_4012, 162, 8_8128, 3_0061, 5, 2]
# fmt: on
UpperCamelCase = self.tokenizer.decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE )
UpperCamelCase = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=_SCREAMING_SNAKE_CASE )
self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
self.assertNotIn(self.tokenizer.eos_token , _SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ):
"""simple docstring"""
UpperCamelCase = tempfile.mkdtemp()
UpperCamelCase = self.tokenizer.lang_token_to_id
self.tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE )
UpperCamelCase = MaMaaaTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE )
self.assertDictEqual(new_tok.lang_token_to_id , _SCREAMING_SNAKE_CASE )
@require_torch
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ):
"""simple docstring"""
UpperCamelCase = 'en'
UpperCamelCase = 'fr'
UpperCamelCase = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=_SCREAMING_SNAKE_CASE , return_tensors='pt' )
UpperCamelCase = shift_tokens_right(
batch['labels'] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id )
for k in batch:
UpperCamelCase = batch[k].tolist()
# batch = {k: v.tolist() for k,v in batch.items()}
# fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
# batch.decoder_inputs_ids[0][0] ==
assert batch.input_ids[1][0] == EN_CODE
assert batch.input_ids[1][-1] == 2
assert batch.labels[1][0] == FR_CODE
assert batch.labels[1][-1] == 2
assert batch.decoder_input_ids[1][:2] == [2, FR_CODE]
@require_torch
def _SCREAMING_SNAKE_CASE ( self : Any ):
"""simple docstring"""
UpperCamelCase = 'mr'
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('mr' )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
UpperCamelCase = 'zh'
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('zh' )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
@require_torch
def _SCREAMING_SNAKE_CASE ( self : Tuple ):
"""simple docstring"""
UpperCamelCase = 'mr'
self.tokenizer._switch_to_target_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('mr' )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
self.tokenizer._switch_to_input_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] )
UpperCamelCase = 'zh'
self.tokenizer._switch_to_target_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('zh' )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
self.tokenizer._switch_to_input_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] )
@require_torch
def _SCREAMING_SNAKE_CASE ( self : Any ):
"""simple docstring"""
UpperCamelCase = self.tokenizer._build_translation_inputs('A test' , return_tensors='pt' , src_lang='en' , tgt_lang='ar' )
self.assertEqual(
nested_simplify(_SCREAMING_SNAKE_CASE ) , {
# en_XX, A, test, EOS
'input_ids': [[12_8022, 58, 4183, 2]],
'attention_mask': [[1, 1, 1, 1]],
# ar_AR
'forced_bos_token_id': 12_8006,
} , )
| 280 | 1 |
import itertools
import os
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
import numpy as np
import datasets
from .execute import check_correctness
lowerCamelCase_ : Optional[Any] = """\
@misc{chen2021evaluating,
title={Evaluating Large Language Models Trained on Code},
author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \
and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \
and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \
and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \
and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \
and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \
and Mohammad Bavarian and Clemens Winter and Philippe Tillet \
and Felipe Petroski Such and Dave Cummings and Matthias Plappert \
and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \
and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \
and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \
and William Saunders and Christopher Hesse and Andrew N. Carr \
and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \
and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \
and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \
and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},
year={2021},
eprint={2107.03374},
archivePrefix={arXiv},
primaryClass={cs.LG}
}
"""
lowerCamelCase_ : Union[str, Any] = """\
This metric implements the evaluation harness for the HumanEval problem solving dataset
described in the paper \"Evaluating Large Language Models Trained on Code\"
(https://arxiv.org/abs/2107.03374).
"""
lowerCamelCase_ : Optional[int] = """
Calculates how good are predictions given some references, using certain scores
Args:
predictions: list of candidates to evaluate. Each candidates should be a list
of strings with several code candidates to solve the problem.
references: a list with a test for each prediction. Each test should evaluate the
correctness of a code candidate.
k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])
num_workers: number of workers used to evaluate the canidate programs (Default: 4).
timeout:
Returns:
pass_at_k: dict with pass rates for each k
results: dict with granular results of each unittest
Examples:
>>> code_eval = datasets.load_metric(\"code_eval\")
>>> test_cases = [\"assert add(2,3)==5\"]
>>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]]
>>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])
>>> print(pass_at_k)
{'pass@1': 0.5, 'pass@2': 1.0}
"""
lowerCamelCase_ : Optional[Any] = """
################################################################################
!!!WARNING!!!
################################################################################
The \"code_eval\" metric executes untrusted model-generated code in Python.
Although it is highly unlikely that model-generated code will do something
overtly malicious in response to this test suite, model-generated code may act
destructively due to a lack of model capability or alignment.
Users are strongly encouraged to sandbox this evaluation suite so that it
does not perform destructive actions on their host or network. For more
information on how OpenAI sandboxes its code, see the paper \"Evaluating Large
Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374).
Once you have read this disclaimer and taken appropriate precautions,
set the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this
with:
>>> import os
>>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\"
################################################################################\
"""
lowerCamelCase_ : Union[str, Any] = """The MIT License
Copyright (c) OpenAI (https://openai.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the \"Software\"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE."""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class a__ ( datasets.Metric ):
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
return datasets.MetricInfo(
# This is the description that will appear on the metrics page.
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'predictions': datasets.Sequence(datasets.Value('string' ) ),
'references': datasets.Value('string' ),
} ) , homepage='https://github.com/openai/human-eval' , codebase_urls=['https://github.com/openai/human-eval'] , reference_urls=['https://github.com/openai/human-eval'] , license=_LICENSE , )
def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=[1, 1_0, 1_0_0] , UpperCAmelCase=4 , UpperCAmelCase=3.0 ) -> List[Any]:
if os.getenv('HF_ALLOW_CODE_EVAL' , 0 ) != "1":
raise ValueError(_WARNING )
if os.name == "nt":
raise NotImplementedError('This metric is currently not supported on Windows.' )
with ThreadPoolExecutor(max_workers=UpperCAmelCase ) as executor:
__a = []
__a = Counter()
__a = 0
__a = defaultdict(UpperCAmelCase )
for task_id, (candidates, test_case) in enumerate(zip(UpperCAmelCase , UpperCAmelCase ) ):
for candidate in candidates:
__a = candidate + '\n' + test_case
__a = (test_program, timeout, task_id, completion_id[task_id])
__a = executor.submit(UpperCAmelCase , *UpperCAmelCase )
futures.append(UpperCAmelCase )
completion_id[task_id] += 1
n_samples += 1
for future in as_completed(UpperCAmelCase ):
__a = future.result()
results[result["task_id"]].append((result['completion_id'], result) )
__a , __a = [], []
for result in results.values():
result.sort()
__a = [r[1]['passed'] for r in result]
total.append(len(UpperCAmelCase ) )
correct.append(sum(UpperCAmelCase ) )
__a = np.array(UpperCAmelCase )
__a = np.array(UpperCAmelCase )
__a = k
__a = {f'''pass@{k}''': estimate_pass_at_k(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ).mean() for k in ks if (total >= k).all()}
return pass_at_k, results
def lowerCAmelCase( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ):
def estimator(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> float:
if n - c < k:
return 1.0
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) )
if isinstance(__lowerCamelCase , __lowerCamelCase ):
__a = itertools.repeat(__lowerCamelCase , len(__lowerCamelCase ) )
else:
assert len(__lowerCamelCase ) == len(__lowerCamelCase )
__a = iter(__lowerCamelCase )
return np.array([estimator(int(__lowerCamelCase ) , int(__lowerCamelCase ) , __lowerCamelCase ) for n, c in zip(__lowerCamelCase , __lowerCamelCase )] )
| 246 | import itertools
import random
import unittest
import numpy as np
from transformers import BatchFeature, SpeechTaFeatureExtractor
from transformers.testing_utils import require_torch
from transformers.utils.import_utils import is_torch_available
from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin
if is_torch_available():
import torch
lowerCamelCase_ : List[Any] = random.Random()
def lowerCAmelCase( __lowerCamelCase , __lowerCamelCase=1.0 , __lowerCamelCase=None , __lowerCamelCase=None ):
if rng is None:
__a = global_rng
__a = []
for batch_idx in range(shape[0] ):
values.append([] )
for _ in range(shape[1] ):
values[-1].append(rng.random() * scale )
return values
@require_torch
class a__ ( unittest.TestCase ):
def __init__( self , UpperCAmelCase , UpperCAmelCase=7 , UpperCAmelCase=4_0_0 , UpperCAmelCase=2_0_0_0 , UpperCAmelCase=1 , UpperCAmelCase=0.0 , UpperCAmelCase=1_6_0_0_0 , UpperCAmelCase=True , UpperCAmelCase=8_0 , UpperCAmelCase=1_6 , UpperCAmelCase=6_4 , UpperCAmelCase="hann_window" , UpperCAmelCase=8_0 , UpperCAmelCase=7_6_0_0 , UpperCAmelCase=1e-10 , UpperCAmelCase=True , ) -> Tuple:
__a = parent
__a = batch_size
__a = min_seq_length
__a = max_seq_length
__a = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
__a = feature_size
__a = padding_value
__a = sampling_rate
__a = do_normalize
__a = num_mel_bins
__a = hop_length
__a = win_length
__a = win_function
__a = fmin
__a = fmax
__a = mel_floor
__a = return_attention_mask
def __SCREAMING_SNAKE_CASE ( self ) -> List[str]:
return {
"feature_size": self.feature_size,
"padding_value": self.padding_value,
"sampling_rate": self.sampling_rate,
"do_normalize": self.do_normalize,
"num_mel_bins": self.num_mel_bins,
"hop_length": self.hop_length,
"win_length": self.win_length,
"win_function": self.win_function,
"fmin": self.fmin,
"fmax": self.fmax,
"mel_floor": self.mel_floor,
"return_attention_mask": self.return_attention_mask,
}
def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase=False , UpperCAmelCase=False ) -> Optional[int]:
def _flatten(UpperCAmelCase ):
return list(itertools.chain(*UpperCAmelCase ) )
if equal_length:
__a = floats_list((self.batch_size, self.max_seq_length) )
else:
# make sure that inputs increase in size
__a = [
_flatten(floats_list((x, self.feature_size) ) )
for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff )
]
if numpify:
__a = [np.asarray(UpperCAmelCase ) for x in speech_inputs]
return speech_inputs
def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase=False , UpperCAmelCase=False ) -> List[Any]:
if equal_length:
__a = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )]
else:
# make sure that inputs increase in size
__a = [
floats_list((x, self.num_mel_bins) )
for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff )
]
if numpify:
__a = [np.asarray(UpperCAmelCase ) for x in speech_inputs]
return speech_inputs
@require_torch
class a__ ( __snake_case , unittest.TestCase ):
A__ : Tuple = SpeechTaFeatureExtractor
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
__a = SpeechTaFeatureExtractionTester(self )
def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase ) -> Optional[Any]:
self.assertTrue(np.all(np.mean(UpperCAmelCase , axis=0 ) < 1e-3 ) )
self.assertTrue(np.all(np.abs(np.var(UpperCAmelCase , axis=0 ) - 1 ) < 1e-3 ) )
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
# Tests that all call wrap to encode_plus and batch_encode_plus
__a = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
# create three inputs of length 800, 1000, and 1200
__a = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
__a = [np.asarray(UpperCAmelCase ) for speech_input in speech_inputs]
# Test not batched input
__a = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values
__a = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values
self.assertTrue(np.allclose(UpperCAmelCase , UpperCAmelCase , atol=1e-3 ) )
# Test batched
__a = feat_extract(UpperCAmelCase , return_tensors='np' ).input_values
__a = feat_extract(UpperCAmelCase , return_tensors='np' ).input_values
for enc_seq_a, enc_seq_a in zip(UpperCAmelCase , UpperCAmelCase ):
self.assertTrue(np.allclose(UpperCAmelCase , UpperCAmelCase , atol=1e-3 ) )
def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
__a = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
__a = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
__a = ['longest', 'max_length', 'do_not_pad']
__a = [None, 1_6_0_0, None]
for max_length, padding in zip(UpperCAmelCase , UpperCAmelCase ):
__a = feat_extract(UpperCAmelCase , padding=UpperCAmelCase , max_length=UpperCAmelCase , return_tensors='np' )
__a = processed.input_values
self._check_zero_mean_unit_variance(input_values[0][:8_0_0] )
self.assertTrue(input_values[0][8_0_0:].sum() < 1e-6 )
self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] )
self.assertTrue(input_values[0][1_0_0_0:].sum() < 1e-6 )
self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] )
def __SCREAMING_SNAKE_CASE ( self ) -> Tuple:
__a = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
__a = range(8_0_0 , 1_4_0_0 , 2_0_0 )
__a = [floats_list((1, x) )[0] for x in lengths]
__a = ['longest', 'max_length', 'do_not_pad']
__a = [None, 1_6_0_0, None]
for max_length, padding in zip(UpperCAmelCase , UpperCAmelCase ):
__a = feat_extract(UpperCAmelCase , max_length=UpperCAmelCase , padding=UpperCAmelCase )
__a = processed.input_values
self._check_zero_mean_unit_variance(input_values[0][:8_0_0] )
self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] )
self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] )
def __SCREAMING_SNAKE_CASE ( self ) -> Tuple:
__a = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
__a = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
__a = feat_extract(
UpperCAmelCase , truncation=UpperCAmelCase , max_length=1_0_0_0 , padding='max_length' , return_tensors='np' )
__a = processed.input_values
self._check_zero_mean_unit_variance(input_values[0, :8_0_0] )
self._check_zero_mean_unit_variance(input_values[1] )
self._check_zero_mean_unit_variance(input_values[2] )
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
__a = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
__a = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
__a = feat_extract(
UpperCAmelCase , truncation=UpperCAmelCase , max_length=1_0_0_0 , padding='longest' , return_tensors='np' )
__a = processed.input_values
self._check_zero_mean_unit_variance(input_values[0, :8_0_0] )
self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] )
self._check_zero_mean_unit_variance(input_values[2] )
# make sure that if max_length < longest -> then pad to max_length
self.assertTrue(input_values.shape == (3, 1_0_0_0) )
__a = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
__a = feat_extract(
UpperCAmelCase , truncation=UpperCAmelCase , max_length=2_0_0_0 , padding='longest' , return_tensors='np' )
__a = processed.input_values
self._check_zero_mean_unit_variance(input_values[0, :8_0_0] )
self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] )
self._check_zero_mean_unit_variance(input_values[2] )
# make sure that if max_length > longest -> then pad to longest
self.assertTrue(input_values.shape == (3, 1_2_0_0) )
def __SCREAMING_SNAKE_CASE ( self ) -> List[str]:
__a = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
__a = np.random.rand(1_0_0 ).astype(np.floataa )
__a = np_speech_inputs.tolist()
for inputs in [py_speech_inputs, np_speech_inputs]:
__a = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' )
self.assertTrue(np_processed.input_values.dtype == np.floataa )
__a = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' )
self.assertTrue(pt_processed.input_values.dtype == torch.floataa )
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
# Tests that all call wrap to encode_plus and batch_encode_plus
__a = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
# create three inputs of length 800, 1000, and 1200
__a = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
__a = [np.asarray(UpperCAmelCase ) for speech_input in speech_inputs]
# Test feature size
__a = feature_extractor(audio_target=UpperCAmelCase , padding=UpperCAmelCase , return_tensors='np' ).input_values
self.assertTrue(input_values.ndim == 3 )
self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins )
# Test not batched input
__a = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values
__a = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values
self.assertTrue(np.allclose(UpperCAmelCase , UpperCAmelCase , atol=1e-3 ) )
# Test batched
__a = feature_extractor(UpperCAmelCase , return_tensors='np' ).input_values
__a = feature_extractor(UpperCAmelCase , return_tensors='np' ).input_values
for enc_seq_a, enc_seq_a in zip(UpperCAmelCase , UpperCAmelCase ):
self.assertTrue(np.allclose(UpperCAmelCase , UpperCAmelCase , atol=1e-3 ) )
# Test 2-D numpy arrays are batched.
__a = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
__a = np.asarray(UpperCAmelCase )
__a = feature_extractor(UpperCAmelCase , return_tensors='np' ).input_values
__a = feature_extractor(UpperCAmelCase , return_tensors='np' ).input_values
for enc_seq_a, enc_seq_a in zip(UpperCAmelCase , UpperCAmelCase ):
self.assertTrue(np.allclose(UpperCAmelCase , UpperCAmelCase , atol=1e-3 ) )
def __SCREAMING_SNAKE_CASE ( self ) -> List[str]:
__a = self.feat_extract_tester.prepare_inputs_for_target()
__a = self.feature_extraction_class(**self.feat_extract_dict )
__a = feat_extract.model_input_names[0]
__a = BatchFeature({input_name: speech_inputs} )
self.assertTrue(all(len(UpperCAmelCase ) == len(UpperCAmelCase ) for x, y in zip(UpperCAmelCase , processed_features[input_name] ) ) )
__a = self.feat_extract_tester.prepare_inputs_for_target(equal_length=UpperCAmelCase )
__a = BatchFeature({input_name: speech_inputs} , tensor_type='np' )
__a = processed_features[input_name]
if len(batch_features_input.shape ) < 3:
__a = batch_features_input[:, :, None]
self.assertTrue(
batch_features_input.shape
== (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) )
@require_torch
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
__a = self.feat_extract_tester.prepare_inputs_for_target(equal_length=UpperCAmelCase )
__a = self.feature_extraction_class(**self.feat_extract_dict )
__a = feat_extract.model_input_names[0]
__a = BatchFeature({input_name: speech_inputs} , tensor_type='pt' )
__a = processed_features[input_name]
if len(batch_features_input.shape ) < 3:
__a = batch_features_input[:, :, None]
self.assertTrue(
batch_features_input.shape
== (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) )
@require_torch
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]:
__a = self.feature_extraction_class(**self.feat_extract_dict )
__a = self.feat_extract_tester.prepare_inputs_for_target()
__a = feat_extract.model_input_names[0]
__a = BatchFeature({input_name: speech_inputs} )
__a = feat_extract.num_mel_bins # hack!
__a = feat_extract.pad(UpperCAmelCase , padding='longest' , return_tensors='np' )[input_name]
__a = feat_extract.pad(UpperCAmelCase , padding='longest' , return_tensors='pt' )[input_name]
self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 )
def __SCREAMING_SNAKE_CASE ( self ) -> Any:
__a = self.feat_extract_dict
__a = True
__a = self.feature_extraction_class(**UpperCAmelCase )
__a = self.feat_extract_tester.prepare_inputs_for_target()
__a = [len(UpperCAmelCase ) for x in speech_inputs]
__a = feat_extract.model_input_names[0]
__a = BatchFeature({input_name: speech_inputs} )
__a = feat_extract.num_mel_bins # hack!
__a = feat_extract.pad(UpperCAmelCase , padding='longest' , return_tensors='np' )
self.assertIn('attention_mask' , UpperCAmelCase )
self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) )
self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , UpperCAmelCase )
def __SCREAMING_SNAKE_CASE ( self ) -> List[str]:
__a = self.feat_extract_dict
__a = True
__a = self.feature_extraction_class(**UpperCAmelCase )
__a = self.feat_extract_tester.prepare_inputs_for_target()
__a = [len(UpperCAmelCase ) for x in speech_inputs]
__a = feat_extract.model_input_names[0]
__a = BatchFeature({input_name: speech_inputs} )
__a = min(UpperCAmelCase )
__a = feat_extract.num_mel_bins # hack!
__a = feat_extract.pad(
UpperCAmelCase , padding='max_length' , max_length=UpperCAmelCase , truncation=UpperCAmelCase , return_tensors='np' )
self.assertIn('attention_mask' , UpperCAmelCase )
self.assertListEqual(
list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] )
self.assertListEqual(
processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] )
def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase ) -> int:
from datasets import load_dataset
__a = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' )
# automatic decoding with librispeech
__a = ds.sort('id' ).select(range(UpperCAmelCase ) )[:num_samples]['audio']
return [x["array"] for x in speech_samples]
def __SCREAMING_SNAKE_CASE ( self ) -> str:
# fmt: off
__a = torch.tensor(
[2.3804e-03, 2.0752e-03, 1.9836e-03, 2.1057e-03, 1.6174e-03,
3.0518e-04, 9.1553e-05, 3.3569e-04, 9.7656e-04, 1.8311e-03,
2.0142e-03, 2.1057e-03, 1.7395e-03, 4.5776e-04, -3.9673e-04,
4.5776e-04, 1.0071e-03, 9.1553e-05, 4.8828e-04, 1.1597e-03,
7.3242e-04, 9.4604e-04, 1.8005e-03, 1.8311e-03, 8.8501e-04,
4.2725e-04, 4.8828e-04, 7.3242e-04, 1.0986e-03, 2.1057e-03] )
# fmt: on
__a = self._load_datasamples(1 )
__a = SpeechTaFeatureExtractor()
__a = feature_extractor(UpperCAmelCase , return_tensors='pt' ).input_values
self.assertEquals(input_values.shape , (1, 9_3_6_8_0) )
self.assertTrue(torch.allclose(input_values[0, :3_0] , UpperCAmelCase , atol=1e-6 ) )
def __SCREAMING_SNAKE_CASE ( self ) -> List[str]:
# fmt: off
__a = torch.tensor(
[-2.6_870, -3.0_104, -3.1_356, -3.5_352, -3.0_044, -3.0_353, -3.4_719, -3.6_777,
-3.1_520, -2.9_435, -2.6_553, -2.8_795, -2.9_944, -2.5_921, -3.0_279, -3.0_386,
-3.0_864, -3.1_291, -3.2_353, -2.7_444, -2.6_831, -2.7_287, -3.1_761, -3.1_571,
-3.2_726, -3.0_582, -3.1_007, -3.4_533, -3.4_695, -3.0_998] )
# fmt: on
__a = self._load_datasamples(1 )
__a = SpeechTaFeatureExtractor()
__a = feature_extractor(audio_target=UpperCAmelCase , return_tensors='pt' ).input_values
self.assertEquals(input_values.shape , (1, 3_6_6, 8_0) )
self.assertTrue(torch.allclose(input_values[0, 0, :3_0] , UpperCAmelCase , atol=1e-4 ) )
| 246 | 1 |
"""simple docstring"""
lowerCamelCase__ : Dict = "Tobias Carryer"
from time import time
class lowercase__:
'''simple docstring'''
def __init__( self :str , lowerCamelCase_ :str , lowerCamelCase_ :List[str] , lowerCamelCase_ :Tuple , lowerCamelCase_ :str=int(time() ) ) -> List[str]: # noqa: B008
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[Any] = multiplier
SCREAMING_SNAKE_CASE : Dict = increment
SCREAMING_SNAKE_CASE : Optional[int] = modulo
SCREAMING_SNAKE_CASE : List[Any] = seed
def __lowerCAmelCase ( self :Tuple ) -> int:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Dict = (self.multiplier * self.seed + self.increment) % self.modulo
return self.seed
if __name__ == "__main__":
# Show the LCG in action.
lowerCamelCase__ : Any = LinearCongruentialGenerator(1664525, 1013904223, 2 << 31)
while True:
print(lcg.next_number())
| 698 |
"""simple docstring"""
from __future__ import annotations
import math
from collections.abc import Callable
def __A ( a_ : Callable[[int | float], int | float] , a_ : int | float , a_ : int | float , a_ : int = 1_00 , )-> float:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Union[str, Any] = x_start
SCREAMING_SNAKE_CASE : Union[str, Any] = fnc(a_ )
SCREAMING_SNAKE_CASE : Optional[int] = 0.0
for _ in range(a_ ):
# Approximates curve as a sequence of linear lines and sums their length
SCREAMING_SNAKE_CASE : int = (x_end - x_start) / steps + xa
SCREAMING_SNAKE_CASE : Optional[int] = fnc(a_ )
length += math.hypot(xa - xa , fxa - fxa )
# Increment step
SCREAMING_SNAKE_CASE : str = xa
SCREAMING_SNAKE_CASE : Any = fxa
return length
if __name__ == "__main__":
def __A ( a_ : Optional[Any] )-> List[Any]:
'''simple docstring'''
return math.sin(10 * x )
print("f(x) = sin(10 * x)")
print("The length of the curve from x = -10 to x = 10 is:")
lowerCamelCase__ : str = 10
while i <= 100000:
print(f'''With {i} steps: {line_length(f, -10, 10, i)}''')
i *= 10
| 698 | 1 |
'''simple docstring'''
from typing import Optional
import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
BaseModelOutputWithNoAttention,
BaseModelOutputWithPoolingAndNoAttention,
ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig
_lowercase = logging.get_logger(__name__)
# General docstring
_lowercase = '''RegNetConfig'''
# Base docstring
_lowercase = '''facebook/regnet-y-040'''
_lowercase = [1, 1088, 7, 7]
# Image classification docstring
_lowercase = '''facebook/regnet-y-040'''
_lowercase = '''tabby, tabby cat'''
_lowercase = [
'''facebook/regnet-y-040''',
# See all regnet models at https://huggingface.co/models?filter=regnet
]
class __snake_case ( nn.Module ):
"""simple docstring"""
def __init__( self : List[str] ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int = 3 ,lowerCAmelCase__ : int = 1 ,lowerCAmelCase__ : int = 1 ,lowerCAmelCase__ : Optional[str] = "relu" ,) -> str:
'''simple docstring'''
super().__init__()
lowerCAmelCase_ : Union[str, Any] = nn.Convad(
lowerCAmelCase__ ,lowerCAmelCase__ ,kernel_size=lowerCAmelCase__ ,stride=lowerCAmelCase__ ,padding=kernel_size // 2 ,groups=lowerCAmelCase__ ,bias=lowerCAmelCase__ ,)
lowerCAmelCase_ : str = nn.BatchNormad(lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = ACTaFN[activation] if activation is not None else nn.Identity()
def UpperCAmelCase_ ( self : Optional[int] ,lowerCAmelCase__ : Dict ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : Union[str, Any] = self.convolution(lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = self.normalization(lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = self.activation(lowerCAmelCase__ )
return hidden_state
class __snake_case ( nn.Module ):
"""simple docstring"""
def __init__( self : Any ,lowerCAmelCase__ : RegNetConfig ) -> Dict:
'''simple docstring'''
super().__init__()
lowerCAmelCase_ : List[str] = RegNetConvLayer(
config.num_channels ,config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act )
lowerCAmelCase_ : Optional[int] = config.num_channels
def UpperCAmelCase_ ( self : str ,lowerCAmelCase__ : Optional[int] ) -> Any:
'''simple docstring'''
lowerCAmelCase_ : Tuple = pixel_values.shape[1]
if num_channels != self.num_channels:
raise ValueError(
"Make sure that the channel dimension of the pixel values match with the one set in the configuration." )
lowerCAmelCase_ : Dict = self.embedder(lowerCAmelCase__ )
return hidden_state
class __snake_case ( nn.Module ):
"""simple docstring"""
def __init__( self : Tuple ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int = 2 ) -> Union[str, Any]:
'''simple docstring'''
super().__init__()
lowerCAmelCase_ : Union[str, Any] = nn.Convad(lowerCAmelCase__ ,lowerCAmelCase__ ,kernel_size=1 ,stride=lowerCAmelCase__ ,bias=lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = nn.BatchNormad(lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Union[str, Any] ,lowerCAmelCase__ : Tensor ) -> Tensor:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = self.convolution(lowerCAmelCase__ )
lowerCAmelCase_ : str = self.normalization(lowerCAmelCase__ )
return hidden_state
class __snake_case ( nn.Module ):
"""simple docstring"""
def __init__( self : Union[str, Any] ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ) -> Any:
'''simple docstring'''
super().__init__()
lowerCAmelCase_ : str = nn.AdaptiveAvgPoolad((1, 1) )
lowerCAmelCase_ : Optional[int] = nn.Sequential(
nn.Convad(lowerCAmelCase__ ,lowerCAmelCase__ ,kernel_size=1 ) ,nn.ReLU() ,nn.Convad(lowerCAmelCase__ ,lowerCAmelCase__ ,kernel_size=1 ) ,nn.Sigmoid() ,)
def UpperCAmelCase_ ( self : Optional[int] ,lowerCAmelCase__ : Tuple ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = self.pooler(lowerCAmelCase__ )
lowerCAmelCase_ : Dict = self.attention(lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = hidden_state * attention
return hidden_state
class __snake_case ( nn.Module ):
"""simple docstring"""
def __init__( self : List[str] ,lowerCAmelCase__ : RegNetConfig ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int = 1 ) -> Optional[Any]:
'''simple docstring'''
super().__init__()
lowerCAmelCase_ : Any = in_channels != out_channels or stride != 1
lowerCAmelCase_ : str = max(1 ,out_channels // config.groups_width )
lowerCAmelCase_ : List[Any] = (
RegNetShortCut(lowerCAmelCase__ ,lowerCAmelCase__ ,stride=lowerCAmelCase__ ) if should_apply_shortcut else nn.Identity()
)
lowerCAmelCase_ : Tuple = nn.Sequential(
RegNetConvLayer(lowerCAmelCase__ ,lowerCAmelCase__ ,kernel_size=1 ,activation=config.hidden_act ) ,RegNetConvLayer(lowerCAmelCase__ ,lowerCAmelCase__ ,stride=lowerCAmelCase__ ,groups=lowerCAmelCase__ ,activation=config.hidden_act ) ,RegNetConvLayer(lowerCAmelCase__ ,lowerCAmelCase__ ,kernel_size=1 ,activation=lowerCAmelCase__ ) ,)
lowerCAmelCase_ : Union[str, Any] = ACTaFN[config.hidden_act]
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : Optional[int] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : str = hidden_state
lowerCAmelCase_ : str = self.layer(lowerCAmelCase__ )
lowerCAmelCase_ : str = self.shortcut(lowerCAmelCase__ )
hidden_state += residual
lowerCAmelCase_ : Optional[int] = self.activation(lowerCAmelCase__ )
return hidden_state
class __snake_case ( nn.Module ):
"""simple docstring"""
def __init__( self : int ,lowerCAmelCase__ : RegNetConfig ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int = 1 ) -> Optional[int]:
'''simple docstring'''
super().__init__()
lowerCAmelCase_ : Optional[int] = in_channels != out_channels or stride != 1
lowerCAmelCase_ : Union[str, Any] = max(1 ,out_channels // config.groups_width )
lowerCAmelCase_ : Optional[int] = (
RegNetShortCut(lowerCAmelCase__ ,lowerCAmelCase__ ,stride=lowerCAmelCase__ ) if should_apply_shortcut else nn.Identity()
)
lowerCAmelCase_ : Union[str, Any] = nn.Sequential(
RegNetConvLayer(lowerCAmelCase__ ,lowerCAmelCase__ ,kernel_size=1 ,activation=config.hidden_act ) ,RegNetConvLayer(lowerCAmelCase__ ,lowerCAmelCase__ ,stride=lowerCAmelCase__ ,groups=lowerCAmelCase__ ,activation=config.hidden_act ) ,RegNetSELayer(lowerCAmelCase__ ,reduced_channels=int(round(in_channels / 4 ) ) ) ,RegNetConvLayer(lowerCAmelCase__ ,lowerCAmelCase__ ,kernel_size=1 ,activation=lowerCAmelCase__ ) ,)
lowerCAmelCase_ : Dict = ACTaFN[config.hidden_act]
def UpperCAmelCase_ ( self : Optional[int] ,lowerCAmelCase__ : str ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : str = hidden_state
lowerCAmelCase_ : List[str] = self.layer(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = self.shortcut(lowerCAmelCase__ )
hidden_state += residual
lowerCAmelCase_ : List[str] = self.activation(lowerCAmelCase__ )
return hidden_state
class __snake_case ( nn.Module ):
"""simple docstring"""
def __init__( self : List[Any] ,lowerCAmelCase__ : RegNetConfig ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int = 2 ,lowerCAmelCase__ : int = 2 ,) -> int:
'''simple docstring'''
super().__init__()
lowerCAmelCase_ : List[Any] = RegNetXLayer if config.layer_type == "x" else RegNetYLayer
lowerCAmelCase_ : Union[str, Any] = nn.Sequential(
# downsampling is done in the first layer with stride of 2
layer(
lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,stride=lowerCAmelCase__ ,) ,*[layer(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) for _ in range(depth - 1 )] ,)
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : Optional[Any] ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = self.layers(lowerCAmelCase__ )
return hidden_state
class __snake_case ( nn.Module ):
"""simple docstring"""
def __init__( self : List[str] ,lowerCAmelCase__ : RegNetConfig ) -> Dict:
'''simple docstring'''
super().__init__()
lowerCAmelCase_ : List[Any] = nn.ModuleList([] )
# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
self.stages.append(
RegNetStage(
lowerCAmelCase__ ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,) )
lowerCAmelCase_ : List[Any] = zip(config.hidden_sizes ,config.hidden_sizes[1:] )
for (in_channels, out_channels), depth in zip(lowerCAmelCase__ ,config.depths[1:] ):
self.stages.append(RegNetStage(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,depth=lowerCAmelCase__ ) )
def UpperCAmelCase_ ( self : Union[str, Any] ,lowerCAmelCase__ : Tensor ,lowerCAmelCase__ : bool = False ,lowerCAmelCase__ : bool = True ) -> BaseModelOutputWithNoAttention:
'''simple docstring'''
lowerCAmelCase_ : Dict = () if output_hidden_states else None
for stage_module in self.stages:
if output_hidden_states:
lowerCAmelCase_ : Optional[Any] = hidden_states + (hidden_state,)
lowerCAmelCase_ : int = stage_module(lowerCAmelCase__ )
if output_hidden_states:
lowerCAmelCase_ : str = hidden_states + (hidden_state,)
if not return_dict:
return tuple(v for v in [hidden_state, hidden_states] if v is not None )
return BaseModelOutputWithNoAttention(last_hidden_state=lowerCAmelCase__ ,hidden_states=lowerCAmelCase__ )
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = RegNetConfig
UpperCamelCase_ = 'regnet'
UpperCamelCase_ = 'pixel_values'
UpperCamelCase_ = True
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : Dict ) -> str:
'''simple docstring'''
if isinstance(lowerCAmelCase__ ,nn.Convad ):
nn.init.kaiming_normal_(module.weight ,mode="fan_out" ,nonlinearity="relu" )
elif isinstance(lowerCAmelCase__ ,(nn.BatchNormad, nn.GroupNorm) ):
nn.init.constant_(module.weight ,1 )
nn.init.constant_(module.bias ,0 )
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : Optional[Any] ,lowerCAmelCase__ : List[str]=False ) -> str:
'''simple docstring'''
if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ):
lowerCAmelCase_ : str = value
_lowercase = r'''
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.
Parameters:
config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''
_lowercase = r'''
Args:
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
[`ConvNextImageProcessor.__call__`] for details.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
'''
@add_start_docstrings(
'The bare RegNet model outputting raw features without any specific head on top.' , snake_case__ , )
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class __snake_case ( snake_case__ ):
"""simple docstring"""
def __init__( self : Optional[Any] ,lowerCAmelCase__ : List[str] ) -> int:
'''simple docstring'''
super().__init__(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = config
lowerCAmelCase_ : Union[str, Any] = RegNetEmbeddings(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[Any] = RegNetEncoder(lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = nn.AdaptiveAvgPoolad((1, 1) )
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(lowerCAmelCase__ )
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC ,output_type=lowerCAmelCase__ ,config_class=_CONFIG_FOR_DOC ,modality="vision" ,expected_output=_EXPECTED_OUTPUT_SHAPE ,)
def UpperCAmelCase_ ( self : List[str] ,lowerCAmelCase__ : Tensor ,lowerCAmelCase__ : Optional[bool] = None ,lowerCAmelCase__ : Optional[bool] = None ) -> BaseModelOutputWithPoolingAndNoAttention:
'''simple docstring'''
lowerCAmelCase_ : int = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
lowerCAmelCase_ : int = return_dict if return_dict is not None else self.config.use_return_dict
lowerCAmelCase_ : Optional[int] = self.embedder(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = self.encoder(
lowerCAmelCase__ ,output_hidden_states=lowerCAmelCase__ ,return_dict=lowerCAmelCase__ )
lowerCAmelCase_ : str = encoder_outputs[0]
lowerCAmelCase_ : int = self.pooler(lowerCAmelCase__ )
if not return_dict:
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=lowerCAmelCase__ ,pooler_output=lowerCAmelCase__ ,hidden_states=encoder_outputs.hidden_states ,)
@add_start_docstrings(
'\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , snake_case__ , )
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class __snake_case ( snake_case__ ):
"""simple docstring"""
def __init__( self : Any ,lowerCAmelCase__ : Union[str, Any] ) -> Optional[Any]:
'''simple docstring'''
super().__init__(lowerCAmelCase__ )
lowerCAmelCase_ : str = config.num_labels
lowerCAmelCase_ : Dict = RegNetModel(lowerCAmelCase__ )
# classification head
lowerCAmelCase_ : Optional[Any] = nn.Sequential(
nn.Flatten() ,nn.Linear(config.hidden_sizes[-1] ,config.num_labels ) if config.num_labels > 0 else nn.Identity() ,)
# initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(lowerCAmelCase__ )
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=lowerCAmelCase__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,)
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : Optional[torch.FloatTensor] = None ,lowerCAmelCase__ : Optional[torch.LongTensor] = None ,lowerCAmelCase__ : Optional[bool] = None ,lowerCAmelCase__ : Optional[bool] = None ,) -> ImageClassifierOutputWithNoAttention:
'''simple docstring'''
lowerCAmelCase_ : int = return_dict if return_dict is not None else self.config.use_return_dict
lowerCAmelCase_ : int = self.regnet(lowerCAmelCase__ ,output_hidden_states=lowerCAmelCase__ ,return_dict=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = outputs.pooler_output if return_dict else outputs[1]
lowerCAmelCase_ : Tuple = self.classifier(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
lowerCAmelCase_ : List[str] = "regression"
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
lowerCAmelCase_ : Dict = "single_label_classification"
else:
lowerCAmelCase_ : str = "multi_label_classification"
if self.config.problem_type == "regression":
lowerCAmelCase_ : Dict = MSELoss()
if self.num_labels == 1:
lowerCAmelCase_ : str = loss_fct(logits.squeeze() ,labels.squeeze() )
else:
lowerCAmelCase_ : List[Any] = loss_fct(lowerCAmelCase__ ,lowerCAmelCase__ )
elif self.config.problem_type == "single_label_classification":
lowerCAmelCase_ : Tuple = CrossEntropyLoss()
lowerCAmelCase_ : List[Any] = loss_fct(logits.view(-1 ,self.num_labels ) ,labels.view(-1 ) )
elif self.config.problem_type == "multi_label_classification":
lowerCAmelCase_ : int = BCEWithLogitsLoss()
lowerCAmelCase_ : Optional[int] = loss_fct(lowerCAmelCase__ ,lowerCAmelCase__ )
if not return_dict:
lowerCAmelCase_ : Dict = (logits,) + outputs[2:]
return (loss,) + output if loss is not None else output
return ImageClassifierOutputWithNoAttention(loss=lowerCAmelCase__ ,logits=lowerCAmelCase__ ,hidden_states=outputs.hidden_states )
| 710 |
_lowercase = {
0: '''0''',
1: '''1''',
2: '''2''',
3: '''3''',
4: '''4''',
5: '''5''',
6: '''6''',
7: '''7''',
8: '''8''',
9: '''9''',
10: '''a''',
11: '''b''',
12: '''c''',
13: '''d''',
14: '''e''',
15: '''f''',
}
def UpperCamelCase ( snake_case__):
assert type(snake_case__) in (int, float) and decimal == int(snake_case__)
lowerCAmelCase_ : Optional[Any] = int(snake_case__)
lowerCAmelCase_ : Tuple = ""
lowerCAmelCase_ : str = False
if decimal < 0:
lowerCAmelCase_ : Tuple = True
decimal *= -1
while decimal > 0:
lowerCAmelCase_ , lowerCAmelCase_ : Any = divmod(snake_case__ , 16)
lowerCAmelCase_ : Dict = values[remainder] + hexadecimal
lowerCAmelCase_ : List[str] = "0x" + hexadecimal
if negative:
lowerCAmelCase_ : Optional[Any] = "-" + hexadecimal
return hexadecimal
if __name__ == "__main__":
import doctest
doctest.testmod()
| 683 | 0 |
'''simple docstring'''
import math
from datetime import datetime, timedelta
def UpperCAmelCase__ ( UpperCAmelCase_ : int ) -> datetime:
__lowerCamelCase : Union[str, Any] = year % 19
__lowerCamelCase : List[str] = year % 4
__lowerCamelCase : Union[str, Any] = year % 7
__lowerCamelCase : Tuple = math.floor(year / 1_00 )
__lowerCamelCase : str = math.floor((13 + 8 * leap_day_inhibits) / 25 )
__lowerCamelCase : Dict = leap_day_inhibits / 4
__lowerCamelCase : Optional[Any] = (
15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number
) % 30
__lowerCamelCase : int = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7
# days to be added to March 21
__lowerCamelCase : Dict = (19 * metonic_cycle + secular_moon_shift) % 30
# PHM -> Paschal Full Moon
__lowerCamelCase : Union[str, Any] = (
2 * julian_leap_year
+ 4 * non_leap_year
+ 6 * days_to_add
+ century_starting_point
) % 7
if days_to_add == 29 and days_from_phm_to_sunday == 6:
return datetime(UpperCAmelCase_ , 4 , 19 )
elif days_to_add == 28 and days_from_phm_to_sunday == 6:
return datetime(UpperCAmelCase_ , 4 , 18 )
else:
return datetime(UpperCAmelCase_ , 3 , 22 ) + timedelta(
days=int(days_to_add + days_from_phm_to_sunday ) )
if __name__ == "__main__":
for year in (1994, 2000, 2010, 2021, 2023):
A__ : Optional[int] = """will be""" if year > datetime.now().year else """was"""
print(f'''Easter in {year} {tense} {gauss_easter(year)}''')
| 13 |
"""simple docstring"""
import os
from argparse import ArgumentParser
from typing import List
import torch.utils.data
from datasets import Dataset, IterableDataset
from datasets.distributed import split_dataset_by_node
__UpperCamelCase : str = 4
__UpperCamelCase : List[str] = 3
class SCREAMING_SNAKE_CASE ( a_ ):
"""simple docstring"""
pass
def __SCREAMING_SNAKE_CASE ( A_ ):
for shard in shards:
for i in range(A_ ):
yield {"i": i, "shard": shard}
def __SCREAMING_SNAKE_CASE ( ):
lowerCAmelCase__ : List[str] = int(os.environ['''RANK'''] )
lowerCAmelCase__ : Union[str, Any] = int(os.environ['''WORLD_SIZE'''] )
lowerCAmelCase__ : Tuple = ArgumentParser()
parser.add_argument('''--streaming''' , type=A_ )
parser.add_argument('''--local_rank''' , type=A_ )
parser.add_argument('''--num_workers''' , type=A_ , default=0 )
lowerCAmelCase__ : Tuple = parser.parse_args()
lowerCAmelCase__ : Tuple = args.streaming
lowerCAmelCase__ : Any = args.num_workers
lowerCAmelCase__ : Dict = {'''shards''': [f'shard_{shard_idx}' for shard_idx in range(A_ )]}
lowerCAmelCase__ : Optional[int] = IterableDataset.from_generator(A_ , gen_kwargs=A_ )
if not streaming:
lowerCAmelCase__ : Dict = Dataset.from_list(list(A_ ) )
lowerCAmelCase__ : Optional[Any] = split_dataset_by_node(A_ , rank=A_ , world_size=A_ )
lowerCAmelCase__ : List[Any] = torch.utils.data.DataLoader(A_ , num_workers=A_ )
lowerCAmelCase__ : Optional[int] = NUM_SHARDS * NUM_ITEMS_PER_SHARD
lowerCAmelCase__ : List[str] = full_size // world_size
expected_local_size += int(rank < (full_size % world_size) )
lowerCAmelCase__ : int = sum(1 for _ in dataloader )
if local_size != expected_local_size:
raise FailedTestError(f'local_size {local_size} != expected_local_size {expected_local_size}' )
if __name__ == "__main__":
main()
| 450 | 0 |
'''simple docstring'''
import torch
def _lowerCAmelCase ():
"""simple docstring"""
if torch.cuda.is_available():
a__ = torch.cuda.device_count()
else:
a__ = 0
print(F'Successfully ran on {num_gpus} GPUs' )
if __name__ == "__main__":
main()
| 703 |
'''simple docstring'''
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available
if is_vision_available():
from PIL import Image
from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast
@require_vision
class lowerCamelCase__ ( unittest.TestCase ):
"""simple docstring"""
def lowerCAmelCase_ ( self : List[str] ):
a__ = tempfile.mkdtemp()
a__ = BlipImageProcessor()
a__ = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-BertModel" )
a__ = BlipProcessor(a__ ,a__ )
processor.save_pretrained(self.tmpdirname )
def lowerCAmelCase_ ( self : List[str] ,**a__ : List[str] ):
return AutoProcessor.from_pretrained(self.tmpdirname ,**a__ ).tokenizer
def lowerCAmelCase_ ( self : Dict ,**a__ : str ):
return AutoProcessor.from_pretrained(self.tmpdirname ,**a__ ).image_processor
def lowerCAmelCase_ ( self : int ):
shutil.rmtree(self.tmpdirname )
def lowerCAmelCase_ ( self : str ):
a__ = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )]
a__ = [Image.fromarray(np.moveaxis(a__ ,0 ,-1 ) ) for x in image_inputs]
return image_inputs
def lowerCAmelCase_ ( self : int ):
a__ = BlipProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
a__ = self.get_tokenizer(bos_token="(BOS)" ,eos_token="(EOS)" )
a__ = self.get_image_processor(do_normalize=a__ ,padding_value=1.0 )
a__ = BlipProcessor.from_pretrained(
self.tmpdirname ,bos_token="(BOS)" ,eos_token="(EOS)" ,do_normalize=a__ ,padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer ,a__ )
self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor ,a__ )
def lowerCAmelCase_ ( self : int ):
a__ = self.get_image_processor()
a__ = self.get_tokenizer()
a__ = BlipProcessor(tokenizer=a__ ,image_processor=a__ )
a__ = self.prepare_image_inputs()
a__ = image_processor(a__ ,return_tensors="np" )
a__ = processor(images=a__ ,return_tensors="np" )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1e-2 )
def lowerCAmelCase_ ( self : Dict ):
a__ = self.get_image_processor()
a__ = self.get_tokenizer()
a__ = BlipProcessor(tokenizer=a__ ,image_processor=a__ )
a__ = "lower newer"
a__ = processor(text=a__ )
a__ = tokenizer(a__ ,return_token_type_ids=a__ )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] ,encoded_processor[key] )
def lowerCAmelCase_ ( self : int ):
a__ = self.get_image_processor()
a__ = self.get_tokenizer()
a__ = BlipProcessor(tokenizer=a__ ,image_processor=a__ )
a__ = "lower newer"
a__ = self.prepare_image_inputs()
a__ = processor(text=a__ ,images=a__ )
self.assertListEqual(list(inputs.keys() ) ,["pixel_values", "input_ids", "attention_mask"] )
# test if it raises when no input is passed
with pytest.raises(a__ ):
processor()
def lowerCAmelCase_ ( self : str ):
a__ = self.get_image_processor()
a__ = self.get_tokenizer()
a__ = BlipProcessor(tokenizer=a__ ,image_processor=a__ )
a__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
a__ = processor.batch_decode(a__ )
a__ = tokenizer.batch_decode(a__ )
self.assertListEqual(a__ ,a__ )
def lowerCAmelCase_ ( self : Union[str, Any] ):
a__ = self.get_image_processor()
a__ = self.get_tokenizer()
a__ = BlipProcessor(tokenizer=a__ ,image_processor=a__ )
a__ = "lower newer"
a__ = self.prepare_image_inputs()
a__ = processor(text=a__ ,images=a__ )
# For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
self.assertListEqual(list(inputs.keys() ) ,["pixel_values", "input_ids", "attention_mask"] )
| 394 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowercase : Dict = logging.get_logger(__name__)
lowercase : Union[str, Any] = {}
class a__ ( __SCREAMING_SNAKE_CASE ):
_A = "llama"
_A = ["past_key_values"]
def __init__( self : Optional[int] , A_ : Optional[int]=3_20_00 , A_ : Union[str, Any]=40_96 , A_ : Optional[int]=1_10_08 , A_ : int=32 , A_ : int=32 , A_ : Tuple=None , A_ : str="silu" , A_ : Union[str, Any]=20_48 , A_ : List[str]=0.02 , A_ : Union[str, Any]=1e-6 , A_ : Dict=True , A_ : Union[str, Any]=0 , A_ : str=1 , A_ : Tuple=2 , A_ : List[str]=1 , A_ : Dict=False , A_ : List[str]=None , **A_ : Tuple , ) -> List[Any]:
"""simple docstring"""
lowerCamelCase_: List[str] = vocab_size
lowerCamelCase_: List[str] = max_position_embeddings
lowerCamelCase_: Union[str, Any] = hidden_size
lowerCamelCase_: Optional[Any] = intermediate_size
lowerCamelCase_: Any = num_hidden_layers
lowerCamelCase_: Dict = num_attention_heads
# for backward compatibility
if num_key_value_heads is None:
lowerCamelCase_: str = num_attention_heads
lowerCamelCase_: str = num_key_value_heads
lowerCamelCase_: str = hidden_act
lowerCamelCase_: List[str] = initializer_range
lowerCamelCase_: Any = rms_norm_eps
lowerCamelCase_: int = pretraining_tp
lowerCamelCase_: Optional[Any] = use_cache
lowerCamelCase_: Any = rope_scaling
self._rope_scaling_validation()
super().__init__(
pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , tie_word_embeddings=A_ , **A_ , )
def lowerCAmelCase ( self : Dict ) -> int:
"""simple docstring"""
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , A_ ) or len(self.rope_scaling ) != 2:
raise ValueError(
"""`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, """
f"""got {self.rope_scaling}""" )
lowerCamelCase_: str = self.rope_scaling.get("""type""" , A_ )
lowerCamelCase_: Optional[int] = self.rope_scaling.get("""factor""" , A_ )
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
f"""`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}""" )
if rope_scaling_factor is None or not isinstance(A_ , A_ ) or rope_scaling_factor <= 1.0:
raise ValueError(f"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
| 423 | import torch
from diffusers import KDPMaDiscreteScheduler
from diffusers.utils import torch_device
from .test_schedulers import SchedulerCommonTest
class a__ ( __SCREAMING_SNAKE_CASE ):
_A = (KDPMaDiscreteScheduler,)
_A = 10
def lowerCAmelCase ( self : List[str] , **A_ : List[str] ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase_: str = {
"""num_train_timesteps""": 11_00,
"""beta_start""": 0.0001,
"""beta_end""": 0.02,
"""beta_schedule""": """linear""",
}
config.update(**A_ )
return config
def lowerCAmelCase ( self : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
for timesteps in [10, 50, 1_00, 10_00]:
self.check_over_configs(num_train_timesteps=A_ )
def lowerCAmelCase ( self : Optional[int] ) -> Any:
"""simple docstring"""
for beta_start, beta_end in zip([0.00001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ):
self.check_over_configs(beta_start=A_ , beta_end=A_ )
def lowerCAmelCase ( self : List[Any] ) -> str:
"""simple docstring"""
for schedule in ["linear", "scaled_linear"]:
self.check_over_configs(beta_schedule=A_ )
def lowerCAmelCase ( self : List[Any] ) -> Optional[Any]:
"""simple docstring"""
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(prediction_type=A_ )
def lowerCAmelCase ( self : Tuple ) -> str:
"""simple docstring"""
lowerCamelCase_: int = self.scheduler_classes[0]
lowerCamelCase_: List[str] = self.get_scheduler_config(prediction_type="""v_prediction""" )
lowerCamelCase_: List[str] = scheduler_class(**A_ )
scheduler.set_timesteps(self.num_inference_steps )
lowerCamelCase_: Dict = self.dummy_model()
lowerCamelCase_: Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma
lowerCamelCase_: Optional[int] = sample.to(A_ )
for i, t in enumerate(scheduler.timesteps ):
lowerCamelCase_: str = scheduler.scale_model_input(A_ , A_ )
lowerCamelCase_: str = model(A_ , A_ )
lowerCamelCase_: Union[str, Any] = scheduler.step(A_ , A_ , A_ )
lowerCamelCase_: List[str] = output.prev_sample
lowerCamelCase_: List[Any] = torch.sum(torch.abs(A_ ) )
lowerCamelCase_: Dict = torch.mean(torch.abs(A_ ) )
if torch_device in ["cpu", "mps"]:
assert abs(result_sum.item() - 4.69_34e-07 ) < 1e-2
assert abs(result_mean.item() - 6.11_12e-10 ) < 1e-3
else:
# CUDA
assert abs(result_sum.item() - 4.6_93_42_86_50_17_09_72e-07 ) < 1e-2
assert abs(result_mean.item() - 0.0002 ) < 1e-3
def lowerCAmelCase ( self : Optional[Any] ) -> List[Any]:
"""simple docstring"""
if torch_device == "mps":
return
lowerCamelCase_: Optional[Any] = self.scheduler_classes[0]
lowerCamelCase_: List[Any] = self.get_scheduler_config()
lowerCamelCase_: Optional[Any] = scheduler_class(**A_ )
scheduler.set_timesteps(self.num_inference_steps )
lowerCamelCase_: str = self.dummy_model()
lowerCamelCase_: Union[str, Any] = self.dummy_sample_deter * scheduler.init_noise_sigma
lowerCamelCase_: int = sample.to(A_ )
for i, t in enumerate(scheduler.timesteps ):
lowerCamelCase_: Dict = scheduler.scale_model_input(A_ , A_ )
lowerCamelCase_: Union[str, Any] = model(A_ , A_ )
lowerCamelCase_: Tuple = scheduler.step(A_ , A_ , A_ )
lowerCamelCase_: List[str] = output.prev_sample
lowerCamelCase_: Union[str, Any] = torch.sum(torch.abs(A_ ) )
lowerCamelCase_: Dict = torch.mean(torch.abs(A_ ) )
if torch_device in ["cpu", "mps"]:
assert abs(result_sum.item() - 20.4125 ) < 1e-2
assert abs(result_mean.item() - 0.0266 ) < 1e-3
else:
# CUDA
assert abs(result_sum.item() - 20.4125 ) < 1e-2
assert abs(result_mean.item() - 0.0266 ) < 1e-3
def lowerCAmelCase ( self : List[str] ) -> Union[str, Any]:
"""simple docstring"""
if torch_device == "mps":
return
lowerCamelCase_: List[Any] = self.scheduler_classes[0]
lowerCamelCase_: str = self.get_scheduler_config()
lowerCamelCase_: List[Any] = scheduler_class(**A_ )
scheduler.set_timesteps(self.num_inference_steps , device=A_ )
lowerCamelCase_: Union[str, Any] = self.dummy_model()
lowerCamelCase_: Tuple = self.dummy_sample_deter.to(A_ ) * scheduler.init_noise_sigma
for t in scheduler.timesteps:
lowerCamelCase_: Optional[Any] = scheduler.scale_model_input(A_ , A_ )
lowerCamelCase_: Optional[Any] = model(A_ , A_ )
lowerCamelCase_: Optional[int] = scheduler.step(A_ , A_ , A_ )
lowerCamelCase_: Optional[int] = output.prev_sample
lowerCamelCase_: List[str] = torch.sum(torch.abs(A_ ) )
lowerCamelCase_: Optional[int] = torch.mean(torch.abs(A_ ) )
if str(A_ ).startswith("""cpu""" ):
# The following sum varies between 148 and 156 on mps. Why?
assert abs(result_sum.item() - 20.4125 ) < 1e-2
assert abs(result_mean.item() - 0.0266 ) < 1e-3
else:
# CUDA
assert abs(result_sum.item() - 20.4125 ) < 1e-2
assert abs(result_mean.item() - 0.0266 ) < 1e-3
| 423 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available
A_ : str ={"tokenization_herbert": ["HerbertTokenizer"]}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A_ : Tuple =["HerbertTokenizerFast"]
if TYPE_CHECKING:
from .tokenization_herbert import HerbertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_herbert_fast import HerbertTokenizerFast
else:
import sys
A_ : Union[str, Any] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 707 | '''simple docstring'''
import argparse
import os
from pathlib import Path
from typing import Dict
import tensorflow as tf
import torch
from tqdm import tqdm
from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer
from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params
A_ : Tuple =[
# replace left string with right string to get the relevant state_dict key (identical state dict to bart)
['''memory_attention''', '''encoder_attn'''],
['''attention''', '''attn'''],
['''/''', '''.'''],
['''.LayerNorm.gamma''', '''_layer_norm.weight'''],
['''.LayerNorm.beta''', '''_layer_norm.bias'''],
['''r.layer_''', '''r.layers.'''],
['''output_proj''', '''out_proj'''],
['''ffn.dense_1.''', '''fc2.'''],
['''ffn.dense.''', '''fc1.'''],
['''ffn_layer_norm''', '''final_layer_norm'''],
['''kernel''', '''weight'''],
['''encoder_layer_norm.''', '''encoder.layer_norm.'''],
['''decoder_layer_norm.''', '''decoder.layer_norm.'''],
['''embeddings.weights''', '''shared.weight'''],
]
def snake_case_ ( __snake_case : Union[str, Any]) -> Optional[Any]:
for pegasus_name, hf_name in PATTERNS:
lowerCAmelCase_ = k.replace(__snake_case , __snake_case)
return k
def snake_case_ ( __snake_case : dict , __snake_case : dict) -> PegasusForConditionalGeneration:
lowerCAmelCase_ = DEFAULTS.copy()
cfg_kwargs.update(__snake_case)
lowerCAmelCase_ = PegasusConfig(**__snake_case)
lowerCAmelCase_ = PegasusForConditionalGeneration(__snake_case)
lowerCAmelCase_ = torch_model.model.state_dict()
lowerCAmelCase_ = {}
for k, v in tf_weights.items():
lowerCAmelCase_ = rename_state_dict_key(__snake_case)
if new_k not in sd:
raise ValueError(F'''could not find new key {new_k} in state dict. (converted from {k})''')
if "dense" in k or "proj" in new_k:
lowerCAmelCase_ = v.T
lowerCAmelCase_ = torch.tensor(__snake_case , dtype=sd[new_k].dtype)
assert v.shape == sd[new_k].shape, F'''{new_k}, {k}, {v.shape}, {sd[new_k].shape}'''
# make sure embedding.padding_idx is respected
lowerCAmelCase_ = torch.zeros_like(mapping['''shared.weight'''][cfg.pad_token_id + 1])
lowerCAmelCase_ = mapping['''shared.weight''']
lowerCAmelCase_ = mapping['''shared.weight''']
lowerCAmelCase_ = {k: torch.zeros_like(__snake_case) for k, v in sd.items() if k.endswith('''bias''') and k not in mapping}
mapping.update(**__snake_case)
lowerCAmelCase_ ,lowerCAmelCase_ = torch_model.model.load_state_dict(__snake_case , strict=__snake_case)
lowerCAmelCase_ = [
k for k in missing if k not in ['''encoder.embed_positions.weight''', '''decoder.embed_positions.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 snake_case_ ( __snake_case : Optional[int]="./ckpt/aeslc/model.ckpt-32000") -> Dict:
lowerCAmelCase_ = tf.train.list_variables(__snake_case)
lowerCAmelCase_ = {}
lowerCAmelCase_ = ['''Adafactor''', '''global_step''']
for name, shape in tqdm(__snake_case , desc='''converting tf checkpoint to dict'''):
lowerCAmelCase_ = any(pat in name for pat in ignore_name)
if skip_key:
continue
lowerCAmelCase_ = tf.train.load_variable(__snake_case , __snake_case)
lowerCAmelCase_ = array
return tf_weights
def snake_case_ ( __snake_case : str , __snake_case : str) -> Optional[int]:
# save tokenizer first
lowerCAmelCase_ = Path(__snake_case).parent.name
lowerCAmelCase_ = task_specific_params[F'''summarization_{dataset}''']['''max_position_embeddings''']
lowerCAmelCase_ = PegasusTokenizer.from_pretrained('''sshleifer/pegasus''' , model_max_length=__snake_case)
assert tok.model_max_length == desired_max_model_length
tok.save_pretrained(__snake_case)
# convert model
lowerCAmelCase_ = get_tf_weights_as_numpy(__snake_case)
lowerCAmelCase_ = task_specific_params[F'''summarization_{dataset}''']
if dataset == "large":
lowerCAmelCase_ = task_specific_params
lowerCAmelCase_ = convert_pegasus(__snake_case , __snake_case)
torch_model.save_pretrained(__snake_case)
lowerCAmelCase_ = torch_model.state_dict()
sd.pop('''model.decoder.embed_positions.weight''')
sd.pop('''model.encoder.embed_positions.weight''')
torch.save(__snake_case , Path(__snake_case) / '''pytorch_model.bin''')
if __name__ == "__main__":
A_ : str =argparse.ArgumentParser()
# Required parameters
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_ : Union[str, Any] =parser.parse_args()
if args.save_dir is None:
A_ : List[Any] =Path(args.tf_ckpt_path).parent.name
A_ : Optional[int] =os.path.join('''pegasus''', dataset)
convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
| 606 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_a : int = {
'configuration_clap': [
'CLAP_PRETRAINED_MODEL_ARCHIVE_LIST',
'ClapAudioConfig',
'ClapConfig',
'ClapTextConfig',
],
'processing_clap': ['ClapProcessor'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a : Dict = [
'CLAP_PRETRAINED_MODEL_ARCHIVE_LIST',
'ClapModel',
'ClapPreTrainedModel',
'ClapTextModel',
'ClapTextModelWithProjection',
'ClapAudioModel',
'ClapAudioModelWithProjection',
]
_a : Optional[Any] = ['ClapFeatureExtractor']
if TYPE_CHECKING:
from .configuration_clap import (
CLAP_PRETRAINED_MODEL_ARCHIVE_LIST,
ClapAudioConfig,
ClapConfig,
ClapTextConfig,
)
from .processing_clap import ClapProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_clap import ClapFeatureExtractor
from .modeling_clap import (
CLAP_PRETRAINED_MODEL_ARCHIVE_LIST,
ClapAudioModel,
ClapAudioModelWithProjection,
ClapModel,
ClapPreTrainedModel,
ClapTextModel,
ClapTextModelWithProjection,
)
else:
import sys
_a : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 598 |
import importlib
import os
import fsspec
import pytest
from fsspec import register_implementation
from fsspec.registry import _registry as _fsspec_registry
from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem
from .utils import require_lza, require_zstandard
def a_ ( __magic_name__ ) -> Any:
"""simple docstring"""
assert "mock" in _fsspec_registry
assert "bz2" in _fsspec_registry
def a_ ( ) -> List[str]:
"""simple docstring"""
assert "mock" not in _fsspec_registry
assert "bz2" in _fsspec_registry
def a_ ( ) -> Union[str, Any]:
"""simple docstring"""
snake_case : Optional[Any] = '''mock-s3-bucket'''
snake_case : Optional[Any] = F"s3://{mock_bucket}"
snake_case : Tuple = extract_path_from_uri(__magic_name__ )
assert dataset_path.startswith('''s3://''' ) is False
snake_case : List[Any] = '''./local/path'''
snake_case : Any = extract_path_from_uri(__magic_name__ )
assert dataset_path == new_dataset_path
def a_ ( __magic_name__ ) -> List[str]:
"""simple docstring"""
snake_case : Any = is_remote_filesystem(__magic_name__ )
assert is_remote is True
snake_case : Dict = fsspec.filesystem('''file''' )
snake_case : List[Any] = is_remote_filesystem(__magic_name__ )
assert is_remote is False
@pytest.mark.parametrize('''compression_fs_class''' , __magic_name__ )
def a_ ( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> Any:
"""simple docstring"""
snake_case : Tuple = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_file, '''bz2''': bza_file, '''lz4''': lza_file}
snake_case : Optional[int] = input_paths[compression_fs_class.protocol]
if input_path is None:
snake_case : Any = F"for '{compression_fs_class.protocol}' compression protocol, "
if compression_fs_class.protocol == "lz4":
reason += require_lza.kwargs["reason"]
elif compression_fs_class.protocol == "zstd":
reason += require_zstandard.kwargs["reason"]
pytest.skip(__magic_name__ )
snake_case : Optional[Any] = fsspec.filesystem(compression_fs_class.protocol , fo=__magic_name__ )
assert isinstance(__magic_name__ , __magic_name__ )
snake_case : List[Any] = os.path.basename(__magic_name__ )
snake_case : Optional[int] = expected_filename[: expected_filename.rindex('''.''' )]
assert fs.glob('''*''' ) == [expected_filename]
with fs.open(__magic_name__ , '''r''' , encoding='''utf-8''' ) as f, open(__magic_name__ , encoding='''utf-8''' ) as expected_file:
assert f.read() == expected_file.read()
@pytest.mark.parametrize('''protocol''' , ['''zip''', '''gzip'''] )
def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> Optional[int]:
"""simple docstring"""
snake_case : Tuple = {'''zip''': zip_jsonl_path, '''gzip''': jsonl_gz_path}
snake_case : Optional[int] = compressed_file_paths[protocol]
snake_case : str = '''dataset.jsonl'''
snake_case : List[Any] = F"{protocol}://{member_file_path}::{compressed_file_path}"
snake_case , *snake_case : str = fsspec.get_fs_token_paths(__magic_name__ )
assert fs.isfile(__magic_name__ )
assert not fs.isfile('''non_existing_''' + member_file_path )
@pytest.mark.integration
def a_ ( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[Any]:
"""simple docstring"""
snake_case : List[Any] = hf_api.dataset_info(__magic_name__ , token=__magic_name__ )
snake_case : List[str] = HfFileSystem(repo_info=__magic_name__ , token=__magic_name__ )
assert sorted(hffs.glob('''*''' ) ) == [".gitattributes", "data"]
assert hffs.isdir('''data''' )
assert hffs.isfile('''.gitattributes''' ) and hffs.isfile('''data/text_data.txt''' )
with open(__magic_name__ ) as f:
assert hffs.open('''data/text_data.txt''' , '''r''' ).read() == f.read()
def a_ ( ) -> List[Any]:
"""simple docstring"""
snake_case : List[str] = '''bz2'''
# Import module
import datasets.filesystems
# Overwrite protocol and reload
register_implementation(__magic_name__ , __magic_name__ , clobber=__magic_name__ )
with pytest.warns(__magic_name__ ) as warning_info:
importlib.reload(datasets.filesystems )
assert len(__magic_name__ ) == 1
assert (
str(warning_info[0].message )
== F"A filesystem protocol was already set for {protocol} and will be overwritten."
)
| 598 | 1 |
from __future__ import annotations
def UpperCamelCase ( _a , _a , _a ) -> int | float:
'''simple docstring'''
if len(_a ) == 0:
raise ValueError('''find_max() arg is an empty sequence''' )
if (
left >= len(_a )
or left < -len(_a )
or right >= len(_a )
or right < -len(_a )
):
raise IndexError('''list index out of range''' )
if left == right:
return nums[left]
lowercase_ :str = (left + right) >> 1 # the middle
lowercase_ :Union[str, Any] = find_max(_a , _a , _a ) # find max in range[left, mid]
lowercase_ :int = find_max(_a , mid + 1 , _a ) # find max in range[mid + 1, right]
return left_max if left_max >= right_max else right_max
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
| 706 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
SCREAMING_SNAKE_CASE : str = {
"configuration_tapas": ["TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP", "TapasConfig"],
"tokenization_tapas": ["TapasTokenizer"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE : Dict = [
"TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST",
"TapasForMaskedLM",
"TapasForQuestionAnswering",
"TapasForSequenceClassification",
"TapasModel",
"TapasPreTrainedModel",
"load_tf_weights_in_tapas",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE : str = [
"TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFTapasForMaskedLM",
"TFTapasForQuestionAnswering",
"TFTapasForSequenceClassification",
"TFTapasModel",
"TFTapasPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig
from .tokenization_tapas import TapasTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tapas import (
TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST,
TapasForMaskedLM,
TapasForQuestionAnswering,
TapasForSequenceClassification,
TapasModel,
TapasPreTrainedModel,
load_tf_weights_in_tapas,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_tapas import (
TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST,
TFTapasForMaskedLM,
TFTapasForQuestionAnswering,
TFTapasForSequenceClassification,
TFTapasModel,
TFTapasPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 441 | 0 |
from __future__ import annotations
import os
import tempfile
import unittest
import numpy as np
from huggingface_hub import hf_hub_download
from transformers import is_tensorflow_text_available, is_tf_available
from transformers.testing_utils import require_tensorflow_text, require_tf, slow
from ..test_modeling_tf_common import floats_tensor
from .test_framework_agnostic import GenerationIntegrationTestsMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
AutoTokenizer,
TFAutoModelForCausalLM,
TFAutoModelForSeqaSeqLM,
TFAutoModelForSpeechSeqaSeq,
TFAutoModelForVisionaSeq,
TFBartForConditionalGeneration,
TFLogitsProcessorList,
TFMinLengthLogitsProcessor,
tf_top_k_top_p_filtering,
)
if is_tensorflow_text_available():
import tensorflow_text as text
@require_tf
class _a ( unittest.TestCase ):
def lowerCamelCase_ ( self: List[Any] ) -> Dict:
"""simple docstring"""
lowercase__ = tf.convert_to_tensor(
[
[
8.2220991, # 3rd highest value; idx. 0
-0.5620044,
5.23229752,
4.0386393,
-6.8798378,
-0.54785802,
-3.2012153,
2.92777176,
1.88171953,
7.35341276, # 5th highest value; idx. 9
8.43207833, # 2nd highest value; idx. 10
-9.85711836,
-5.96209236,
-1.13039161,
-7.1115294,
-0.8369633,
-5.3186408,
7.06427407,
0.81369344,
-0.82023817,
-5.9179796,
0.58813443,
-6.99778438,
4.71551189,
-0.18771637,
7.44020759, # 4th highest value; idx. 25
9.38450987, # 1st highest value; idx. 26
2.12662941,
-9.32562038,
2.35652522,
], # cummulative prob of 5 highest values <= 0.6
[
0.58425518,
4.53139238,
-5.57510464,
-6.28030699,
-7.19529503,
-4.02122551,
1.39337037,
-6.06707057,
1.59480517,
-9.643119,
0.03907799,
0.67231762,
-8.88206726,
6.27115922, # 4th highest value; idx. 13
2.28520723,
4.82767506,
4.30421368,
8.8275313, # 2nd highest value; idx. 17
5.44029958, # 5th highest value; idx. 18
-4.4735794,
7.38579536, # 3rd highest value; idx. 20
-2.91051663,
2.61946077,
-2.5674762,
-9.48959302,
-4.02922645,
-1.35416918,
9.67702323, # 1st highest value; idx. 27
-5.89478553,
1.85370467,
], # cummulative prob of 5 highest values <= 0.6
] , dtype=tf.floataa , )
lowercase__ = tf.convert_to_tensor(
[[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]] , dtype=tf.intaa , ) # expected non filtered idx as noted above
lowercase__ = tf.convert_to_tensor(
[8.222099, 7.3534126, 8.432078, 7.4402075, 9.38451, 6.271159, 8.827531, 5.4402995, 7.3857956, 9.677023] , dtype=tf.floataa , ) # expected non filtered values as noted above
lowercase__ = tf_top_k_top_p_filtering(UpperCamelCase_ , top_k=10 , top_p=0.6 , min_tokens_to_keep=4 )
lowercase__ = output[output != -float('''inf''' )]
lowercase__ = tf.cast(
tf.where(tf.not_equal(UpperCamelCase_ , tf.constant(-float('''inf''' ) , dtype=tf.floataa ) ) ) , dtype=tf.intaa , )
tf.debugging.assert_near(UpperCamelCase_ , UpperCamelCase_ , rtol=1E-1_2 )
tf.debugging.assert_equal(UpperCamelCase_ , UpperCamelCase_ )
@require_tf
class _a ( unittest.TestCase , UpperCamelCase__ ):
# setting framework_dependent_parameters needs to be gated, just like its contents' imports
if is_tf_available():
_lowercase : List[Any] = {
'''AutoModelForCausalLM''': TFAutoModelForCausalLM,
'''AutoModelForSpeechSeq2Seq''': TFAutoModelForSpeechSeqaSeq,
'''AutoModelForSeq2SeqLM''': TFAutoModelForSeqaSeqLM,
'''AutoModelForVision2Seq''': TFAutoModelForVisionaSeq,
'''LogitsProcessorList''': TFLogitsProcessorList,
'''MinLengthLogitsProcessor''': TFMinLengthLogitsProcessor,
'''create_tensor_fn''': tf.convert_to_tensor,
'''floats_tensor''': floats_tensor,
'''return_tensors''': '''tf''',
}
@slow
def lowerCamelCase_ ( self: Optional[int] ) -> Optional[int]:
"""simple docstring"""
lowercase__ = TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' )
lowercase__ = 2
lowercase__ = 2
class _a ( tf.Module ):
def __init__( self: List[Any] , UpperCamelCase_: List[str] ) -> Optional[int]:
"""simple docstring"""
super(UpperCamelCase_ , self ).__init__()
lowercase__ = model
@tf.function(
input_signature=(
tf.TensorSpec((None, input_length) , tf.intaa , name='''input_ids''' ),
tf.TensorSpec((None, input_length) , tf.intaa , name='''attention_mask''' ),
) , jit_compile=UpperCamelCase_ , )
def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase_: List[Any] , UpperCamelCase_: Dict ) -> Optional[Any]:
"""simple docstring"""
lowercase__ = self.model.generate(
input_ids=UpperCamelCase_ , attention_mask=UpperCamelCase_ , max_new_tokens=UpperCamelCase_ , return_dict_in_generate=UpperCamelCase_ , )
return {"sequences": outputs["sequences"]}
lowercase__ = [[2, 0], [102, 103]]
lowercase__ = [[1, 0], [1, 1]]
lowercase__ = DummyModel(model=UpperCamelCase_ )
with tempfile.TemporaryDirectory() as tmp_dir:
tf.saved_model.save(UpperCamelCase_ , UpperCamelCase_ , signatures={'''serving_default''': dummy_model.serving} )
lowercase__ = tf.saved_model.load(UpperCamelCase_ ).signatures['''serving_default''']
for batch_size in range(1 , len(UpperCamelCase_ ) + 1 ):
lowercase__ = {
'''input_ids''': tf.constant(dummy_input_ids[:batch_size] ),
'''attention_mask''': tf.constant(dummy_attention_masks[:batch_size] ),
}
lowercase__ = serving_func(**UpperCamelCase_ )['''sequences''']
lowercase__ = test_model.generate(**UpperCamelCase_ , max_new_tokens=UpperCamelCase_ )
tf.debugging.assert_equal(UpperCamelCase_ , UpperCamelCase_ )
@slow
def lowerCamelCase_ ( self: Tuple ) -> Tuple:
"""simple docstring"""
lowercase__ = TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' )
lowercase__ = 1
lowercase__ = 2
class _a ( tf.Module ):
def __init__( self: Tuple , UpperCamelCase_: Dict ) -> Tuple:
"""simple docstring"""
super(UpperCamelCase_ , self ).__init__()
lowercase__ = model
@tf.function(
input_signature=(
tf.TensorSpec((batch_size, None) , tf.intaa , name='''input_ids''' ),
tf.TensorSpec((batch_size, None) , tf.intaa , name='''attention_mask''' ),
) , jit_compile=UpperCamelCase_ , )
def lowerCamelCase_ ( self: Any , UpperCamelCase_: Dict , UpperCamelCase_: List[str] ) -> Any:
"""simple docstring"""
lowercase__ = self.model.generate(
input_ids=UpperCamelCase_ , attention_mask=UpperCamelCase_ , max_new_tokens=UpperCamelCase_ , return_dict_in_generate=UpperCamelCase_ , )
return {"sequences": outputs["sequences"]}
lowercase__ = [[2], [102, 103]]
lowercase__ = [[1], [1, 1]]
lowercase__ = DummyModel(model=UpperCamelCase_ )
with tempfile.TemporaryDirectory() as tmp_dir:
tf.saved_model.save(UpperCamelCase_ , UpperCamelCase_ , signatures={'''serving_default''': dummy_model.serving} )
lowercase__ = tf.saved_model.load(UpperCamelCase_ ).signatures['''serving_default''']
for input_row in range(len(UpperCamelCase_ ) ):
lowercase__ = {
'''input_ids''': tf.constant([dummy_input_ids[input_row]] ),
'''attention_mask''': tf.constant([dummy_attention_masks[input_row]] ),
}
lowercase__ = serving_func(**UpperCamelCase_ )['''sequences''']
lowercase__ = test_model.generate(**UpperCamelCase_ , max_new_tokens=UpperCamelCase_ )
tf.debugging.assert_equal(UpperCamelCase_ , UpperCamelCase_ )
@slow
@require_tensorflow_text
def lowerCamelCase_ ( self: Dict ) -> List[str]:
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
# file needed to load the TF tokenizer
hf_hub_download(repo_id='''google/flan-t5-small''' , filename='''spiece.model''' , local_dir=UpperCamelCase_ )
class _a ( tf.keras.layers.Layer ):
def __init__( self: str ) -> Tuple:
"""simple docstring"""
super().__init__()
lowercase__ = text.SentencepieceTokenizer(
model=tf.io.gfile.GFile(os.path.join(UpperCamelCase_ , '''spiece.model''' ) , '''rb''' ).read() )
lowercase__ = TFAutoModelForSeqaSeqLM.from_pretrained('''hf-internal-testing/tiny-random-t5''' )
def lowerCamelCase_ ( self: int , UpperCamelCase_: int , *UpperCamelCase_: List[Any] , **UpperCamelCase_: Dict ) -> Dict:
"""simple docstring"""
lowercase__ = self.tokenizer.tokenize(UpperCamelCase_ )
lowercase__ , lowercase__ = text.pad_model_inputs(
UpperCamelCase_ , max_seq_length=64 , pad_value=self.model.config.pad_token_id )
lowercase__ = self.model.generate(input_ids=UpperCamelCase_ , attention_mask=UpperCamelCase_ )
return self.tokenizer.detokenize(UpperCamelCase_ )
lowercase__ = CompleteSentenceTransformer()
lowercase__ = tf.keras.layers.Input(shape=(1,) , dtype=tf.string , name='''inputs''' )
lowercase__ = complete_model(UpperCamelCase_ )
lowercase__ = tf.keras.Model(UpperCamelCase_ , UpperCamelCase_ )
keras_model.save(UpperCamelCase_ )
def lowerCamelCase_ ( self: Dict ) -> Tuple:
"""simple docstring"""
lowercase__ = {
'''do_sample''': True,
'''num_beams''': 1,
'''top_p''': 0.7,
'''top_k''': 10,
'''temperature''': 0.7,
}
lowercase__ = 14
lowercase__ = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' )
lowercase__ = '''Hello, my dog is cute and'''
lowercase__ = tokenizer(UpperCamelCase_ , return_tensors='''tf''' )
lowercase__ = TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' )
lowercase__ = 638
# forces the generation to happen on CPU, to avoid GPU-related quirks
with tf.device(''':/CPU:0''' ):
tf.random.set_seed(0 )
lowercase__ = model.generate(**UpperCamelCase_ , eos_token_id=UpperCamelCase_ , **UpperCamelCase_ )
self.assertTrue(expectation == len(generated_tokens[0] ) )
lowercase__ = [638, 198]
with tf.device(''':/CPU:0''' ):
tf.random.set_seed(0 )
lowercase__ = model.generate(**UpperCamelCase_ , eos_token_id=UpperCamelCase_ , **UpperCamelCase_ )
self.assertTrue(expectation == len(generated_tokens[0] ) )
def lowerCamelCase_ ( self: Optional[int] ) -> Dict:
"""simple docstring"""
lowercase__ = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bart''' )
lowercase__ = '''Hugging Face is a technology company based in New York and Paris.'''
lowercase__ = bart_tokenizer(UpperCamelCase_ , return_tensors='''tf''' ).input_ids
lowercase__ = TFBartForConditionalGeneration.from_pretrained('''hf-internal-testing/tiny-random-bart''' )
lowercase__ = bart_model.generate(UpperCamelCase_ ).numpy()
class _a ( UpperCamelCase__ ):
def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase_: Optional[int] , UpperCamelCase_: List[Any]=None , **UpperCamelCase_: Optional[int] ) -> List[Any]:
"""simple docstring"""
return super().call(UpperCamelCase_ , **UpperCamelCase_ )
lowercase__ = FakeBart.from_pretrained('''hf-internal-testing/tiny-random-bart''' )
lowercase__ = bart_model.generate(UpperCamelCase_ , foo='''bar''' ).numpy()
self.assertTrue(np.array_equal(UpperCamelCase_ , UpperCamelCase_ ) )
class _a ( bart_model.model.encoder.__class__ ):
def lowerCamelCase_ ( self: List[Any] , UpperCamelCase_: Tuple , **UpperCamelCase_: int ) -> List[Any]:
"""simple docstring"""
return super().call(UpperCamelCase_ , **UpperCamelCase_ )
lowercase__ = FakeEncoder(bart_model.config , bart_model.model.shared )
lowercase__ = fake_encoder
# Normal generation still works (the output will be different because the encoder weights are different)
lowercase__ = bart_model.generate(UpperCamelCase_ ).numpy()
with self.assertRaises(UpperCamelCase_ ):
# FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo"
bart_model.generate(UpperCamelCase_ , foo='''bar''' )
| 43 |
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 , __magic_name__ , __magic_name__=7 , __magic_name__=3 , __magic_name__=1_8 , __magic_name__=3_0 , __magic_name__=4_0_0 , __magic_name__=True , __magic_name__=None , __magic_name__=True , __magic_name__=None , __magic_name__=True , __magic_name__=[0.48_145_466, 0.4_578_275, 0.40_821_073] , __magic_name__=[0.26_862_954, 0.26_130_258, 0.27_577_711] , __magic_name__=True , ):
lowerCamelCase : Union[str, Any] = size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4}
lowerCamelCase : str = crop_size if crop_size is not None else {"""height""": 1_8, """width""": 1_8}
lowerCamelCase : Optional[int] = parent
lowerCamelCase : Union[str, Any] = batch_size
lowerCamelCase : str = num_channels
lowerCamelCase : Any = image_size
lowerCamelCase : Optional[int] = min_resolution
lowerCamelCase : Union[str, Any] = max_resolution
lowerCamelCase : Union[str, Any] = do_resize
lowerCamelCase : int = size
lowerCamelCase : int = do_center_crop
lowerCamelCase : Union[str, Any] = crop_size
lowerCamelCase : Union[str, Any] = do_normalize
lowerCamelCase : Dict = image_mean
lowerCamelCase : Optional[Any] = image_std
lowerCamelCase : Union[str, Any] = do_convert_rgb
def UpperCamelCase__ ( self ):
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 UpperCamelCase__ ( self , __magic_name__=False , __magic_name__=False , __magic_name__=False ):
assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"
if equal_resolution:
lowerCamelCase : Tuple = []
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:
lowerCamelCase : Dict = []
for i in range(self.batch_size ):
lowerCamelCase , lowerCamelCase : int = 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
lowerCamelCase : int = [Image.fromarray(np.moveaxis(__magic_name__ , 0 , -1 ) ) for x in image_inputs]
if torchify:
lowerCamelCase : int = [torch.from_numpy(__magic_name__ ) for x in image_inputs]
return image_inputs
@require_torch
@require_vision
class A__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase):
_UpperCAmelCase : Any = ChineseCLIPImageProcessor if is_vision_available() else None
def UpperCamelCase__ ( self ):
lowerCamelCase : List[str] = ChineseCLIPImageProcessingTester(self , do_center_crop=__magic_name__ )
@property
def UpperCamelCase__ ( self ):
return self.image_processor_tester.prepare_image_processor_dict()
def UpperCamelCase__ ( self ):
lowerCamelCase : Tuple = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__magic_name__ , """do_resize""" ) )
self.assertTrue(hasattr(__magic_name__ , """size""" ) )
self.assertTrue(hasattr(__magic_name__ , """do_center_crop""" ) )
self.assertTrue(hasattr(__magic_name__ , """center_crop""" ) )
self.assertTrue(hasattr(__magic_name__ , """do_normalize""" ) )
self.assertTrue(hasattr(__magic_name__ , """image_mean""" ) )
self.assertTrue(hasattr(__magic_name__ , """image_std""" ) )
self.assertTrue(hasattr(__magic_name__ , """do_convert_rgb""" ) )
def UpperCamelCase__ ( self ):
lowerCamelCase : Tuple = 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} )
lowerCamelCase : 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 UpperCamelCase__ ( self ):
pass
def UpperCamelCase__ ( self ):
# Initialize image_processing
lowerCamelCase : str = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
lowerCamelCase : Dict = self.image_processor_tester.prepare_inputs(equal_resolution=__magic_name__ )
for image in image_inputs:
self.assertIsInstance(__magic_name__ , Image.Image )
# Test not batched input
lowerCamelCase : Optional[int] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["""height"""],
self.image_processor_tester.crop_size["""width"""],
) , )
# Test batched
lowerCamelCase : Optional[Any] = image_processing(__magic_name__ , 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 UpperCamelCase__ ( self ):
# Initialize image_processing
lowerCamelCase : List[str] = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
lowerCamelCase : Dict = self.image_processor_tester.prepare_inputs(equal_resolution=__magic_name__ , numpify=__magic_name__ )
for image in image_inputs:
self.assertIsInstance(__magic_name__ , np.ndarray )
# Test not batched input
lowerCamelCase : int = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["""height"""],
self.image_processor_tester.crop_size["""width"""],
) , )
# Test batched
lowerCamelCase : Tuple = image_processing(__magic_name__ , 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 UpperCamelCase__ ( self ):
# Initialize image_processing
lowerCamelCase : str = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
lowerCamelCase : Any = self.image_processor_tester.prepare_inputs(equal_resolution=__magic_name__ , torchify=__magic_name__ )
for image in image_inputs:
self.assertIsInstance(__magic_name__ , torch.Tensor )
# Test not batched input
lowerCamelCase : Optional[int] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["""height"""],
self.image_processor_tester.crop_size["""width"""],
) , )
# Test batched
lowerCamelCase : str = image_processing(__magic_name__ , 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__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase):
_UpperCAmelCase : Tuple = ChineseCLIPImageProcessor if is_vision_available() else None
def UpperCamelCase__ ( self ):
lowerCamelCase : Union[str, Any] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=__magic_name__ )
lowerCamelCase : Any = 3
@property
def UpperCamelCase__ ( self ):
return self.image_processor_tester.prepare_image_processor_dict()
def UpperCamelCase__ ( self ):
lowerCamelCase : int = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__magic_name__ , """do_resize""" ) )
self.assertTrue(hasattr(__magic_name__ , """size""" ) )
self.assertTrue(hasattr(__magic_name__ , """do_center_crop""" ) )
self.assertTrue(hasattr(__magic_name__ , """center_crop""" ) )
self.assertTrue(hasattr(__magic_name__ , """do_normalize""" ) )
self.assertTrue(hasattr(__magic_name__ , """image_mean""" ) )
self.assertTrue(hasattr(__magic_name__ , """image_std""" ) )
self.assertTrue(hasattr(__magic_name__ , """do_convert_rgb""" ) )
def UpperCamelCase__ ( self ):
pass
def UpperCamelCase__ ( self ):
# Initialize image_processing
lowerCamelCase : str = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
lowerCamelCase : Dict = self.image_processor_tester.prepare_inputs(equal_resolution=__magic_name__ )
for image in image_inputs:
self.assertIsInstance(__magic_name__ , Image.Image )
# Test not batched input
lowerCamelCase : 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
lowerCamelCase : Optional[Any] = image_processing(__magic_name__ , 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"""],
) , )
| 681 | 0 |
from pathlib import Path
import fire
def _a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> List[str]:
lowerCamelCase_ : List[Any] = Path(_snake_case )
lowerCamelCase_ : Union[str, Any] = Path(_snake_case )
dest_dir.mkdir(exist_ok=_snake_case )
for path in src_dir.iterdir():
lowerCamelCase_ : Optional[Any] = [x.rstrip() for x in list(path.open().readlines() )][:n]
lowerCamelCase_ : Optional[Any] = dest_dir.joinpath(path.name )
print(_snake_case )
dest_path.open('w' ).write('\n'.join(_snake_case ) )
if __name__ == "__main__":
fire.Fire(minify)
| 708 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase = logging.get_logger(__name__)
UpperCamelCase = {
'''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json''',
# See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox
}
class lowerCamelCase__ ( UpperCAmelCase ):
lowerCamelCase_ : List[str] = 'gpt_neox'
def __init__(self : int , _snake_case : List[str]=5_0432 , _snake_case : List[Any]=6144 , _snake_case : Optional[Any]=44 , _snake_case : Dict=64 , _snake_case : Optional[Any]=2_4576 , _snake_case : str="gelu" , _snake_case : Optional[Any]=0.25 , _snake_case : int=1_0000 , _snake_case : int=0.0 , _snake_case : Any=0.0 , _snake_case : List[str]=0.1 , _snake_case : str=2048 , _snake_case : str=0.02 , _snake_case : Dict=1e-5 , _snake_case : int=True , _snake_case : str=0 , _snake_case : Tuple=2 , _snake_case : Tuple=False , _snake_case : int=True , _snake_case : List[str]=None , **_snake_case : List[str] , ) -> Tuple:
"""simple docstring"""
super().__init__(bos_token_id=_snake_case , eos_token_id=_snake_case , **_snake_case )
lowerCamelCase_ : Optional[int] = vocab_size
lowerCamelCase_ : Tuple = max_position_embeddings
lowerCamelCase_ : List[str] = hidden_size
lowerCamelCase_ : Optional[Any] = num_hidden_layers
lowerCamelCase_ : Union[str, Any] = num_attention_heads
lowerCamelCase_ : Union[str, Any] = intermediate_size
lowerCamelCase_ : Any = hidden_act
lowerCamelCase_ : Optional[Any] = rotary_pct
lowerCamelCase_ : Tuple = rotary_emb_base
lowerCamelCase_ : List[Any] = attention_dropout
lowerCamelCase_ : int = hidden_dropout
lowerCamelCase_ : List[Any] = classifier_dropout
lowerCamelCase_ : int = initializer_range
lowerCamelCase_ : Dict = layer_norm_eps
lowerCamelCase_ : List[str] = use_cache
lowerCamelCase_ : Dict = tie_word_embeddings
lowerCamelCase_ : int = use_parallel_residual
lowerCamelCase_ : Dict = rope_scaling
self._rope_scaling_validation()
if self.hidden_size % self.num_attention_heads != 0:
raise ValueError(
'The hidden size is not divisble by the number of attention heads! Make sure to update them!' )
def UpperCAmelCase_ (self : Any ) -> Optional[int]:
"""simple docstring"""
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , _snake_case ) or len(self.rope_scaling ) != 2:
raise ValueError(
'`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '
f'got {self.rope_scaling}' )
lowerCamelCase_ : List[str] = self.rope_scaling.get('type' , _snake_case )
lowerCamelCase_ : Any = self.rope_scaling.get('factor' , _snake_case )
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' )
if rope_scaling_factor is None or not isinstance(_snake_case , _snake_case ) or rope_scaling_factor <= 1.0:
raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
| 144 | 0 |
from collections.abc import Generator
def __a ( ):
a__ , a__ = 0, 1
while True:
a__ , a__ = b, a + b
yield b
def __a ( __UpperCAmelCase = 1000 ):
a__ = 1
a__ = fibonacci_generator()
while len(str(next(__UpperCAmelCase ) ) ) < n:
answer += 1
return answer + 1
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
| 194 |
a_ : str = 6_55_21
def __a ( __UpperCAmelCase ):
a__ = 1
a__ = 0
for plain_chr in plain_text:
a__ = (a + ord(__UpperCAmelCase )) % MOD_ADLER
a__ = (b + a) % MOD_ADLER
return (b << 16) | a
| 194 | 1 |
import json
import os
import unittest
from transformers import DebertaTokenizer, DebertaTokenizerFast
from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES
from transformers.testing_utils import slow
from ...test_tokenization_common import TokenizerTesterMixin
class a ( UpperCAmelCase , unittest.TestCase ):
_lowercase = DebertaTokenizer
_lowercase = True
_lowercase = DebertaTokenizerFast
def _UpperCAmelCase ( self ):
'''simple docstring'''
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
_UpperCAmelCase : Any = [
"l",
"o",
"w",
"e",
"r",
"s",
"t",
"i",
"d",
"n",
"\u0120",
"\u0120l",
"\u0120n",
"\u0120lo",
"\u0120low",
"er",
"\u0120lowest",
"\u0120newer",
"\u0120wider",
"[UNK]",
]
_UpperCAmelCase : Optional[int] = dict(zip(A_ , range(len(A_ ) ) ) )
_UpperCAmelCase : List[str] = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
_UpperCAmelCase : Any = {"unk_token": "[UNK]"}
_UpperCAmelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
_UpperCAmelCase : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as fp:
fp.write(json.dumps(A_ ) + "\n" )
with open(self.merges_file , "w" , encoding="utf-8" ) as fp:
fp.write("\n".join(A_ ) )
def _UpperCAmelCase ( self , **A_ ):
'''simple docstring'''
kwargs.update(self.special_tokens_map )
return self.tokenizer_class.from_pretrained(self.tmpdirname , **A_ )
def _UpperCAmelCase ( self , A_ ):
'''simple docstring'''
_UpperCAmelCase : int = "lower newer"
_UpperCAmelCase : str = "lower newer"
return input_text, output_text
def _UpperCAmelCase ( self ):
'''simple docstring'''
_UpperCAmelCase : Tuple = self.get_tokenizer()
_UpperCAmelCase : Optional[int] = "lower newer"
_UpperCAmelCase : Any = ["l", "o", "w", "er", "\u0120", "n", "e", "w", "er"]
_UpperCAmelCase : Union[str, Any] = tokenizer.tokenize(A_ )
self.assertListEqual(A_ , A_ )
_UpperCAmelCase : Union[str, Any] = tokens + [tokenizer.unk_token]
_UpperCAmelCase : Union[str, Any] = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ )
def _UpperCAmelCase ( self ):
'''simple docstring'''
_UpperCAmelCase : List[Any] = self.get_tokenizer()
_UpperCAmelCase : Any = tokenizer("Hello" , "World" )
_UpperCAmelCase : int = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
self.assertListEqual(tokd["token_type_ids"] , A_ )
@slow
def _UpperCAmelCase ( self ):
'''simple docstring'''
_UpperCAmelCase : str = self.tokenizer_class.from_pretrained("microsoft/deberta-base" )
_UpperCAmelCase : Union[str, Any] = tokenizer.encode("sequence builders" , add_special_tokens=A_ )
_UpperCAmelCase : Any = tokenizer.encode("multi-sequence build" , add_special_tokens=A_ )
_UpperCAmelCase : List[Any] = tokenizer.encode(
"sequence builders" , add_special_tokens=A_ , add_prefix_space=A_ )
_UpperCAmelCase : str = tokenizer.encode(
"sequence builders" , "multi-sequence build" , add_special_tokens=A_ , add_prefix_space=A_ )
_UpperCAmelCase : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(A_ )
_UpperCAmelCase : Any = tokenizer.build_inputs_with_special_tokens(A_ , A_ )
assert encoded_sentence == encoded_text_from_decode
assert encoded_pair == encoded_pair_from_decode
@slow
def _UpperCAmelCase ( self ):
'''simple docstring'''
_UpperCAmelCase : List[Any] = [self.tokenizer_class]
if self.test_rust_tokenizer:
tokenizer_classes.append(self.rust_tokenizer_class )
for tokenizer_class in tokenizer_classes:
_UpperCAmelCase : Dict = tokenizer_class.from_pretrained("microsoft/deberta-base" )
_UpperCAmelCase : Optional[Any] = [
"ALBERT: A Lite BERT for Self-supervised Learning of Language Representations",
"ALBERT incorporates two parameter reduction techniques",
"The first one is a factorized embedding parameterization. By decomposing the large vocabulary"
" embedding matrix into two small matrices, we separate the size of the hidden layers from the size of"
" vocabulary embedding.",
]
_UpperCAmelCase : str = tokenizer(A_ , padding=A_ )
_UpperCAmelCase : Optional[Any] = [tokenizer.decode(A_ , skip_special_tokens=A_ ) for seq in encoding["input_ids"]]
# fmt: off
_UpperCAmelCase : Dict = {
"input_ids": [
[1, 2118, 11126, 565, 35, 83, 25191, 163, 18854, 13, 12156, 12, 16101, 25376, 13807, 9, 22205, 27893, 1635, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 2118, 11126, 565, 24536, 80, 43797, 4878, 7373, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 133, 78, 65, 16, 10, 3724, 1538, 33183, 11303, 43797, 1938, 4, 870, 24165, 29105, 5, 739, 32644, 33183, 11303, 36173, 88, 80, 650, 7821, 45940, 6, 52, 2559, 5, 1836, 9, 5, 7397, 13171, 31, 5, 1836, 9, 32644, 33183, 11303, 4, 2]
],
"token_type_ids": [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
],
"attention_mask": [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
}
# fmt: on
_UpperCAmelCase : Any = [
"ALBERT: A Lite BERT for Self-supervised Learning of Language Representations",
"ALBERT incorporates two parameter reduction techniques",
"The first one is a factorized embedding parameterization. By decomposing the large vocabulary"
" embedding matrix into two small matrices, we separate the size of the hidden layers from the size of"
" vocabulary embedding.",
]
self.assertDictEqual(encoding.data , A_ )
for expected, decoded in zip(A_ , A_ ):
self.assertEqual(A_ , A_ )
| 467 |
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional
from packaging import version
if TYPE_CHECKING:
from ... import PreTrainedTokenizer, TensorType
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging
SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE_ = {
'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/resolve/main/config.json',
'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/config.json',
'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json',
'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json',
'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/config.json',
'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json',
}
class a ( UpperCAmelCase ):
_lowercase = "bloom"
_lowercase = ["past_key_values"]
_lowercase = {
"num_hidden_layers": "n_layer",
"num_attention_heads": "n_head",
}
def __init__( self , A_=250880 , A_=64 , A_=2 , A_=8 , A_=1e-5 , A_=0.02 , A_=True , A_=1 , A_=2 , A_=False , A_=0.0 , A_=0.0 , A_=1 , A_=False , **A_ , ):
'''simple docstring'''
_UpperCAmelCase : List[str] = vocab_size
# Backward compatibility with n_embed kwarg
_UpperCAmelCase : str = kwargs.pop("n_embed" , A_ )
_UpperCAmelCase : List[Any] = hidden_size if n_embed is None else n_embed
_UpperCAmelCase : Dict = n_layer
_UpperCAmelCase : Optional[Any] = n_head
_UpperCAmelCase : Optional[Any] = layer_norm_epsilon
_UpperCAmelCase : List[Any] = initializer_range
_UpperCAmelCase : Union[str, Any] = use_cache
_UpperCAmelCase : List[str] = pretraining_tp
_UpperCAmelCase : List[Any] = apply_residual_connection_post_layernorm
_UpperCAmelCase : int = hidden_dropout
_UpperCAmelCase : List[str] = attention_dropout
_UpperCAmelCase : int = bos_token_id
_UpperCAmelCase : str = eos_token_id
_UpperCAmelCase : Optional[Any] = slow_but_exact
super().__init__(bos_token_id=A_ , eos_token_id=A_ , **A_ )
class a ( UpperCAmelCase ):
_lowercase = version.parse("1.12" )
def __init__( self , A_ , A_ = "default" , A_ = None , A_ = False , ):
'''simple docstring'''
super().__init__(A_ , task=A_ , patching_specs=A_ , use_past=A_ )
if not getattr(self._config , "pad_token_id" , A_ ):
# TODO: how to do that better?
_UpperCAmelCase : str = 0
@property
def _UpperCAmelCase ( self ):
'''simple docstring'''
_UpperCAmelCase : List[Any] = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} )
if self.use_past:
# BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
self.fill_with_past_key_values_(A_ , direction="inputs" , inverted_values_shape=A_ )
_UpperCAmelCase : Optional[int] = {0: "batch", 1: "past_sequence + sequence"}
else:
_UpperCAmelCase : Union[str, Any] = {0: "batch", 1: "sequence"}
return common_inputs
@property
def _UpperCAmelCase ( self ):
'''simple docstring'''
return self._config.n_layer
@property
def _UpperCAmelCase ( self ):
'''simple docstring'''
return self._config.n_head
@property
def _UpperCAmelCase ( self ):
'''simple docstring'''
return 1e-3
def _UpperCAmelCase ( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ):
'''simple docstring'''
_UpperCAmelCase : 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()
_UpperCAmelCase : Tuple = 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
_UpperCAmelCase , _UpperCAmelCase : Union[str, Any] = common_inputs["input_ids"].shape
# Not using the same length for past_key_values
_UpperCAmelCase : List[Any] = seqlen + 2
_UpperCAmelCase : Dict = self._config.hidden_size // self.num_attention_heads
_UpperCAmelCase : List[Any] = (
batch * self.num_attention_heads,
head_dim,
past_key_values_length,
)
_UpperCAmelCase : Optional[Any] = (
batch * self.num_attention_heads,
past_key_values_length,
head_dim,
)
_UpperCAmelCase : Tuple = [
(torch.zeros(A_ ), torch.zeros(A_ )) for _ in range(self.num_layers )
]
_UpperCAmelCase : int = common_inputs["attention_mask"]
if self.use_past:
_UpperCAmelCase : str = ordered_inputs["attention_mask"].dtype
_UpperCAmelCase : Optional[int] = torch.cat(
[ordered_inputs["attention_mask"], torch.ones(A_ , A_ , dtype=A_ )] , dim=1 )
return ordered_inputs
@property
def _UpperCAmelCase ( self ):
'''simple docstring'''
return 13
| 467 | 1 |
import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional
import datasets
import numpy as np
import tensorflow as tf
from transformers import (
AutoConfig,
AutoTokenizer,
EvalPrediction,
HfArgumentParser,
PreTrainedTokenizer,
TFAutoModelForSequenceClassification,
TFTrainer,
TFTrainingArguments,
)
from transformers.utils import logging as hf_logging
hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : str , _lowerCamelCase : str , _lowerCamelCase : str , _lowerCamelCase : PreTrainedTokenizer , _lowerCamelCase : int , _lowerCamelCase : Optional[int] = None , ) -> str:
'''simple docstring'''
__UpperCamelCase : Optional[int] = {}
if train_file is not None:
__UpperCamelCase : List[Any] = [train_file]
if eval_file is not None:
__UpperCamelCase : Optional[Any] = [eval_file]
if test_file is not None:
__UpperCamelCase : Optional[int] = [test_file]
__UpperCamelCase : Dict = datasets.load_dataset("csv" , data_files=_lowerCamelCase)
__UpperCamelCase : List[Any] = list(ds[list(files.keys())[0]].features.keys())
__UpperCamelCase : List[str] = features_name.pop(_lowerCamelCase)
__UpperCamelCase : Optional[Any] = list(set(ds[list(files.keys())[0]][label_name]))
__UpperCamelCase : Union[str, Any] = {label: i for i, label in enumerate(_lowerCamelCase)}
__UpperCamelCase : Dict = tokenizer.model_input_names
__UpperCamelCase : List[Any] = {}
if len(_lowerCamelCase) == 1:
for k in files.keys():
__UpperCamelCase : Dict = ds[k].map(
lambda _lowerCamelCase: tokenizer.batch_encode_plus(
example[features_name[0]] , truncation=_lowerCamelCase , max_length=_lowerCamelCase , padding="max_length") , batched=_lowerCamelCase , )
elif len(_lowerCamelCase) == 2:
for k in files.keys():
__UpperCamelCase : str = ds[k].map(
lambda _lowerCamelCase: tokenizer.batch_encode_plus(
(example[features_name[0]], example[features_name[1]]) , truncation=_lowerCamelCase , max_length=_lowerCamelCase , padding="max_length" , ) , batched=_lowerCamelCase , )
def gen_train():
for ex in transformed_ds[datasets.Split.TRAIN]:
__UpperCamelCase : int = {k: v for k, v in ex.items() if k in input_names}
__UpperCamelCase : List[Any] = labelaid[ex[label_name]]
yield (d, label)
def gen_val():
for ex in transformed_ds[datasets.Split.VALIDATION]:
__UpperCamelCase : Tuple = {k: v for k, v in ex.items() if k in input_names}
__UpperCamelCase : Tuple = labelaid[ex[label_name]]
yield (d, label)
def gen_test():
for ex in transformed_ds[datasets.Split.TEST]:
__UpperCamelCase : str = {k: v for k, v in ex.items() if k in input_names}
__UpperCamelCase : Optional[Any] = labelaid[ex[label_name]]
yield (d, label)
__UpperCamelCase : Tuple = (
tf.data.Dataset.from_generator(
_lowerCamelCase , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None]) for k in input_names}, tf.TensorShape([])) , )
if datasets.Split.TRAIN in transformed_ds
else None
)
if train_ds is not None:
__UpperCamelCase : List[Any] = train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN])))
__UpperCamelCase : int = (
tf.data.Dataset.from_generator(
_lowerCamelCase , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None]) for k in input_names}, tf.TensorShape([])) , )
if datasets.Split.VALIDATION in transformed_ds
else None
)
if val_ds is not None:
__UpperCamelCase : Dict = val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION])))
__UpperCamelCase : List[Any] = (
tf.data.Dataset.from_generator(
_lowerCamelCase , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None]) for k in input_names}, tf.TensorShape([])) , )
if datasets.Split.TEST in transformed_ds
else None
)
if test_ds is not None:
__UpperCamelCase : Optional[Any] = test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST])))
return train_ds, val_ds, test_ds, labelaid
lowercase : Optional[Any] = logging.getLogger(__name__)
@dataclass
class lowerCamelCase__ :
'''simple docstring'''
_A = field(metadata={'help': 'Which column contains the label'})
_A = field(default=__lowercase , metadata={'help': 'The path of the training file'})
_A = field(default=__lowercase , metadata={'help': 'The path of the development file'})
_A = field(default=__lowercase , metadata={'help': 'The path of the test file'})
_A = field(
default=1_2_8 , metadata={
'help': (
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
_A = field(
default=__lowercase , metadata={'help': 'Overwrite the cached training and evaluation sets'})
@dataclass
class lowerCamelCase__ :
'''simple docstring'''
_A = field(
metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'})
_A = field(
default=__lowercase , metadata={'help': 'Pretrained config name or path if not the same as model_name'})
_A = field(
default=__lowercase , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'})
_A = field(default=__lowercase , 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.
_A = field(
default=__lowercase , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , )
def _SCREAMING_SNAKE_CASE ( ) -> Tuple:
'''simple docstring'''
__UpperCamelCase : int = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
__UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Optional[Any] = 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.")
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , )
logger.info(
F'n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1)}, '
F'16-bits training: {training_args.fpaa}')
logger.info(F'Training/evaluation parameters {training_args}')
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
__UpperCamelCase : Dict = 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 , )
__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : str = get_tfds(
train_file=data_args.train_file , eval_file=data_args.dev_file , test_file=data_args.test_file , tokenizer=_lowerCamelCase , label_column_id=data_args.label_column_id , max_seq_length=data_args.max_seq_length , )
__UpperCamelCase : Tuple = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=len(_lowerCamelCase) , labelaid=_lowerCamelCase , idalabel={id: label for label, id in labelaid.items()} , finetuning_task="text-classification" , cache_dir=model_args.cache_dir , )
with training_args.strategy.scope():
__UpperCamelCase : int = TFAutoModelForSequenceClassification.from_pretrained(
model_args.model_name_or_path , from_pt=bool(".bin" in model_args.model_name_or_path) , config=_lowerCamelCase , cache_dir=model_args.cache_dir , )
def compute_metrics(_lowerCamelCase : EvalPrediction) -> Dict:
__UpperCamelCase : Union[str, Any] = np.argmax(p.predictions , axis=1)
return {"acc": (preds == p.label_ids).mean()}
# Initialize our Trainer
__UpperCamelCase : Dict = TFTrainer(
model=_lowerCamelCase , args=_lowerCamelCase , train_dataset=_lowerCamelCase , eval_dataset=_lowerCamelCase , compute_metrics=_lowerCamelCase , )
# Training
if training_args.do_train:
trainer.train()
trainer.save_model()
tokenizer.save_pretrained(training_args.output_dir)
# Evaluation
__UpperCamelCase : str = {}
if training_args.do_eval:
logger.info("*** Evaluate ***")
__UpperCamelCase : Optional[Any] = trainer.evaluate()
__UpperCamelCase : Union[str, Any] = os.path.join(training_args.output_dir , "eval_results.txt")
with open(_lowerCamelCase , "w") as writer:
logger.info("***** Eval results *****")
for key, value in result.items():
logger.info(F' {key} = {value}')
writer.write(F'{key} = {value}\n')
results.update(_lowerCamelCase)
return results
if __name__ == "__main__":
main() | 557 |
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 10**9) -> int:
'''simple docstring'''
__UpperCamelCase : int = 1
__UpperCamelCase : Any = 2
__UpperCamelCase : Dict = 0
__UpperCamelCase : Any = 0
__UpperCamelCase : List[Any] = 0
while perimeter <= max_perimeter:
perimeters_sum += perimeter
prev_value += 2 * value
value += prev_value
__UpperCamelCase : Optional[int] = 2 * value + 2 if i % 2 == 0 else 2 * value - 2
i += 1
return perimeters_sum
if __name__ == "__main__":
print(f"{solution() = }") | 557 | 1 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
_lowercase : Tuple = {
'configuration_electra': ['ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ElectraConfig', 'ElectraOnnxConfig'],
'tokenization_electra': ['ElectraTokenizer'],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase : Optional[Any] = ['ElectraTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase : Optional[Any] = [
'ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST',
'ElectraForCausalLM',
'ElectraForMaskedLM',
'ElectraForMultipleChoice',
'ElectraForPreTraining',
'ElectraForQuestionAnswering',
'ElectraForSequenceClassification',
'ElectraForTokenClassification',
'ElectraModel',
'ElectraPreTrainedModel',
'load_tf_weights_in_electra',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase : str = [
'TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFElectraForMaskedLM',
'TFElectraForMultipleChoice',
'TFElectraForPreTraining',
'TFElectraForQuestionAnswering',
'TFElectraForSequenceClassification',
'TFElectraForTokenClassification',
'TFElectraModel',
'TFElectraPreTrainedModel',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase : Optional[int] = [
'FlaxElectraForCausalLM',
'FlaxElectraForMaskedLM',
'FlaxElectraForMultipleChoice',
'FlaxElectraForPreTraining',
'FlaxElectraForQuestionAnswering',
'FlaxElectraForSequenceClassification',
'FlaxElectraForTokenClassification',
'FlaxElectraModel',
'FlaxElectraPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig
from .tokenization_electra import ElectraTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_electra_fast import ElectraTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_electra import (
ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST,
ElectraForCausalLM,
ElectraForMaskedLM,
ElectraForMultipleChoice,
ElectraForPreTraining,
ElectraForQuestionAnswering,
ElectraForSequenceClassification,
ElectraForTokenClassification,
ElectraModel,
ElectraPreTrainedModel,
load_tf_weights_in_electra,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_electra import (
TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST,
TFElectraForMaskedLM,
TFElectraForMultipleChoice,
TFElectraForPreTraining,
TFElectraForQuestionAnswering,
TFElectraForSequenceClassification,
TFElectraForTokenClassification,
TFElectraModel,
TFElectraPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_electra import (
FlaxElectraForCausalLM,
FlaxElectraForMaskedLM,
FlaxElectraForMultipleChoice,
FlaxElectraForPreTraining,
FlaxElectraForQuestionAnswering,
FlaxElectraForSequenceClassification,
FlaxElectraForTokenClassification,
FlaxElectraModel,
FlaxElectraPreTrainedModel,
)
else:
import sys
_lowercase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 397 |
"""simple docstring"""
def lowercase__ ( snake_case_ :List[Any] , snake_case_ :str , snake_case_ :Tuple , snake_case_ :Any , snake_case_ :Union[str, Any] , snake_case_ :List[Any] ):
if index == r:
for j in range(snake_case_ ):
print(data[j] , end=''' ''' )
print(''' ''' )
return
# When no more elements are there to put in data[]
if i >= n:
return
# current is included, put next at next location
__UpperCAmelCase = arr[i]
combination_util(snake_case_ , snake_case_ , snake_case_ , index + 1 , snake_case_ , i + 1 )
# current is excluded, replace it with
# next (Note that i+1 is passed, but
# index is not changed)
combination_util(snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , i + 1 )
# The main function that prints all combinations
# of size r in arr[] of size n. This function
# mainly uses combinationUtil()
def lowercase__ ( snake_case_ :Optional[int] , snake_case_ :str , snake_case_ :List[str] ):
# A temporary array to store all combination one by one
__UpperCAmelCase = [0] * r
# Print all combination using temporary array 'data[]'
combination_util(snake_case_ , snake_case_ , snake_case_ , 0 , snake_case_ , 0 )
if __name__ == "__main__":
# Driver code to check the function above
_lowercase : List[str] = [10, 20, 30, 40, 50]
print_combination(arr, len(arr), 3)
# This code is contributed by Ambuj sahu
| 397 | 1 |
from __future__ import annotations
def lowercase ( _a ,_a ) -> list[int]:
UpperCAmelCase_: List[Any] = 0
UpperCAmelCase_: Dict = len(_a ) - 1
while i < j:
if nums[i] + nums[j] == target:
return [i, j]
elif nums[i] + nums[j] < target:
UpperCAmelCase_: Dict = i + 1
else:
UpperCAmelCase_: Union[str, Any] = j - 1
return []
if __name__ == "__main__":
import doctest
doctest.testmod()
print(F"""{two_pointer([2, 7, 11, 15], 9) = }""") | 137 |
from __future__ import annotations
from fractions import Fraction
def lowercase ( _a ,_a ) -> bool:
return (
num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den
)
def lowercase ( _a ) -> list[str]:
UpperCAmelCase_: int = []
UpperCAmelCase_: Any = 11
UpperCAmelCase_: Union[str, Any] = int("1" + "0" * digit_len )
for num in range(_a ,_a ):
while den <= 99:
if (num != den) and (num % 10 == den // 10) and (den % 10 != 0):
if is_digit_cancelling(_a ,_a ):
solutions.append(f"{num}/{den}" )
den += 1
num += 1
UpperCAmelCase_: Any = 10
return solutions
def lowercase ( _a = 2 ) -> int:
UpperCAmelCase_: Dict = 1.0
for fraction in fraction_list(_a ):
UpperCAmelCase_: int = Fraction(_a )
result *= frac.denominator / frac.numerator
return int(_a )
if __name__ == "__main__":
print(solution()) | 137 | 1 |
"""simple docstring"""
import math
import unittest
def _lowercase ( __lowerCAmelCase ) -> bool:
assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (
number >= 0
), "'number' must been an int and positive"
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(math.sqrt(__lowerCAmelCase ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
class __a (unittest.TestCase):
'''simple docstring'''
def _a ( self ) -> Any:
"""simple docstring"""
self.assertTrue(is_prime(2 ) )
self.assertTrue(is_prime(3 ) )
self.assertTrue(is_prime(5 ) )
self.assertTrue(is_prime(7 ) )
self.assertTrue(is_prime(11 ) )
self.assertTrue(is_prime(13 ) )
self.assertTrue(is_prime(17 ) )
self.assertTrue(is_prime(19 ) )
self.assertTrue(is_prime(23 ) )
self.assertTrue(is_prime(29 ) )
def _a ( self ) -> Union[str, Any]:
"""simple docstring"""
with self.assertRaises(_a ):
is_prime(-19 )
self.assertFalse(
is_prime(0 ) , """Zero doesn't have any positive factors, primes must have exactly two.""" , )
self.assertFalse(
is_prime(1 ) , """One only has 1 positive factor, primes must have exactly two.""" , )
self.assertFalse(is_prime(2 * 2 ) )
self.assertFalse(is_prime(2 * 3 ) )
self.assertFalse(is_prime(3 * 3 ) )
self.assertFalse(is_prime(3 * 5 ) )
self.assertFalse(is_prime(3 * 5 * 7 ) )
if __name__ == "__main__":
unittest.main()
| 12 |
"""simple docstring"""
import tempfile
import unittest
from transformers import TaConfig, is_torch_available
from transformers.testing_utils import (
require_sentencepiece,
require_tokenizers,
require_torch,
slow,
torch_device,
)
from ...generation.test_utils import GenerationTesterMixin
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel
class __a :
'''simple docstring'''
def __init__( self , _a , _a=99 , _a=13 , _a=7 , _a=9 , _a=True , _a=True , _a=False , _a=32 , _a=5 , _a=4 , _a=37 , _a=8 , _a=0.1 , _a=0.002 , _a=1 , _a=0 , _a=0 , _a=None , _a=None , ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Dict = parent
SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size
SCREAMING_SNAKE_CASE__ : Tuple = encoder_seq_length
SCREAMING_SNAKE_CASE__ : str = decoder_seq_length
# For common tests
SCREAMING_SNAKE_CASE__ : Optional[int] = self.decoder_seq_length
SCREAMING_SNAKE_CASE__ : Tuple = is_training
SCREAMING_SNAKE_CASE__ : Dict = use_attention_mask
SCREAMING_SNAKE_CASE__ : List[str] = use_labels
SCREAMING_SNAKE_CASE__ : str = vocab_size
SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size
SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers
SCREAMING_SNAKE_CASE__ : Any = num_attention_heads
SCREAMING_SNAKE_CASE__ : Any = d_ff
SCREAMING_SNAKE_CASE__ : Any = relative_attention_num_buckets
SCREAMING_SNAKE_CASE__ : Union[str, Any] = dropout_rate
SCREAMING_SNAKE_CASE__ : List[str] = initializer_factor
SCREAMING_SNAKE_CASE__ : List[Any] = eos_token_id
SCREAMING_SNAKE_CASE__ : List[str] = pad_token_id
SCREAMING_SNAKE_CASE__ : Any = decoder_start_token_id
SCREAMING_SNAKE_CASE__ : Any = None
SCREAMING_SNAKE_CASE__ : str = decoder_layers
def _a ( self ) -> Tuple:
"""simple docstring"""
return TaConfig.from_pretrained("""google/umt5-base""" )
def _a ( self , _a , _a , _a , _a=None , _a=None , _a=None , _a=None , _a=None , ) -> Any:
"""simple docstring"""
if attention_mask is None:
SCREAMING_SNAKE_CASE__ : List[str] = input_ids.ne(config.pad_token_id )
if decoder_attention_mask is None:
SCREAMING_SNAKE_CASE__ : int = decoder_input_ids.ne(config.pad_token_id )
if head_mask is None:
SCREAMING_SNAKE_CASE__ : str = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=_a )
if decoder_head_mask is None:
SCREAMING_SNAKE_CASE__ : List[str] = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=_a )
if cross_attn_head_mask is None:
SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.ones(
config.num_decoder_layers , config.num_attention_heads , device=_a )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
def _a ( self ) -> Tuple:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size )
SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size )
# we need to clamp the input ids here to avoid having pad token in between
# this is because for NllbMoe the position_ids are prepared such that
# all pad tokens have pos id = 2 and rest are between 2..seq_length
# and the seq_length here is seq_length - num_pad_tokens
# but when using past, there is no way of knowing if the past input ids had
# pad tokens in them, which results in incorrect seq_lenth and which in turn results in
# position_ids being off by num_pad_tokens in past input
SCREAMING_SNAKE_CASE__ : Tuple = input_ids.clamp(self.pad_token_id + 1 )
SCREAMING_SNAKE_CASE__ : Optional[int] = decoder_input_ids.clamp(self.pad_token_id + 1 )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_config()
SCREAMING_SNAKE_CASE__ : List[str] = config.num_attention_heads
SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_inputs_dict(_a , _a , _a )
return config, input_dict
def _a ( self ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs()
return config, inputs_dict
def _a ( self ) -> List[str]:
"""simple docstring"""
return TaConfig(
vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , )
def _a ( self ) -> List[Any]:
"""simple docstring"""
return TaConfig(
vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , )
def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : str = UMTaModel(config=_a )
model.to(_a )
model.eval()
SCREAMING_SNAKE_CASE__ : Dict = model(
input_ids=_a , decoder_input_ids=_a , attention_mask=_a , decoder_attention_mask=_a , )
SCREAMING_SNAKE_CASE__ : Optional[Any] = model(input_ids=_a , decoder_input_ids=_a )
SCREAMING_SNAKE_CASE__ : Optional[Any] = result.last_hidden_state
SCREAMING_SNAKE_CASE__ : Dict = result.past_key_values
SCREAMING_SNAKE_CASE__ : Any = result.encoder_last_hidden_state
self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) )
self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) )
# There should be `num_layers` key value embeddings stored in decoder_past
self.parent.assertEqual(len(_a ) , config.num_layers )
# There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple
self.parent.assertEqual(len(decoder_past[0] ) , 4 )
def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).get_decoder().to(_a ).eval()
# first forward pass
SCREAMING_SNAKE_CASE__ : str = model(_a , use_cache=_a )
SCREAMING_SNAKE_CASE__ : str = model(_a )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , use_cache=_a )
self.parent.assertTrue(len(_a ) == len(_a ) )
self.parent.assertTrue(len(_a ) == len(_a ) + 1 )
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor((self.batch_size, 1) , config.vocab_size )
# append to next input_ids and
SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a )["""last_hidden_state"""]
SCREAMING_SNAKE_CASE__ : Tuple = model(_a , past_key_values=_a )["""last_hidden_state"""]
# select random slice
SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor((1,) , output_from_past.shape[-1] ).item()
SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_no_past[:, -1, random_slice_idx].detach()
SCREAMING_SNAKE_CASE__ : List[Any] = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(_a , _a , atol=1E-3 ) )
def _a ( self , _a , _a , ) -> List[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).to(_a ).half().eval()
SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**_a )["""last_hidden_state"""]
self.parent.assertFalse(torch.isnan(_a ).any().item() )
@require_torch
class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase):
'''simple docstring'''
_SCREAMING_SNAKE_CASE :Union[str, Any] = (
(UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else ()
)
_SCREAMING_SNAKE_CASE :Optional[int] = (UMTaForConditionalGeneration,) if is_torch_available() else ()
_SCREAMING_SNAKE_CASE :List[str] = (
{
"""conversational""": UMTaForConditionalGeneration,
"""feature-extraction""": UMTaModel,
"""summarization""": UMTaForConditionalGeneration,
"""text2text-generation""": UMTaForConditionalGeneration,
"""translation""": UMTaForConditionalGeneration,
"""question-answering""": UMTaForQuestionAnswering,
}
if is_torch_available()
else {}
)
_SCREAMING_SNAKE_CASE :Union[str, Any] = True
_SCREAMING_SNAKE_CASE :Tuple = False
_SCREAMING_SNAKE_CASE :Optional[Any] = False
_SCREAMING_SNAKE_CASE :List[Any] = True
_SCREAMING_SNAKE_CASE :List[str] = True
# The small UMT5 model needs higher percentages for CPU/MP tests
_SCREAMING_SNAKE_CASE :Union[str, Any] = [0.8, 0.9]
def _a ( self ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Union[str, Any] = UMTaModelTester(self )
@unittest.skip("""Test has a segmentation fault on torch 1.8.0""" )
def _a ( self ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ : Dict = UMTaModel(config_and_inputs[0] ).to(_a )
with tempfile.TemporaryDirectory() as tmpdirname:
torch.onnx.export(
_a , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'''{tmpdirname}/t5_test.onnx''' , export_params=_a , opset_version=9 , input_names=["""input_ids""", """decoder_input_ids"""] , )
@unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" )
def _a ( self ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model_fpaa_forward(*_a )
def _a ( self ) -> List[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : int = ["""encoder_attentions""", """decoder_attentions""", """cross_attentions"""]
SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ : List[Any] = config_and_inputs[0]
SCREAMING_SNAKE_CASE__ : Tuple = UMTaForConditionalGeneration(_a ).eval()
model.to(_a )
SCREAMING_SNAKE_CASE__ : List[str] = {
"""head_mask""": torch.zeros(config.num_layers , config.num_heads , device=_a ),
"""decoder_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ),
"""cross_attn_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ),
}
for attn_name, (name, mask) in zip(_a , head_masking.items() ):
SCREAMING_SNAKE_CASE__ : List[str] = {name: mask}
# Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified
if name == "head_mask":
SCREAMING_SNAKE_CASE__ : str = torch.ones(
config.num_decoder_layers , config.num_heads , device=_a )
SCREAMING_SNAKE_CASE__ : Optional[Any] = model.generate(
config_and_inputs[1]["""input_ids"""] , num_beams=1 , max_length=3 , output_attentions=_a , return_dict_in_generate=_a , **_a , )
# We check the state of decoder_attentions and cross_attentions just from the last step
SCREAMING_SNAKE_CASE__ : List[str] = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1]
self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 )
@unittest.skip("""Does not work on the tiny model as we keep hitting edge cases.""" )
def _a ( self ) -> Dict:
"""simple docstring"""
pass
@require_torch
@require_sentencepiece
@require_tokenizers
class __a (unittest.TestCase):
'''simple docstring'''
@slow
@unittest.skip(
"""Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged""" )
def _a ( self ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Optional[Any] = UMTaForConditionalGeneration.from_pretrained("""google/umt5-small""" , return_dict=_a ).to(_a )
SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("""google/umt5-small""" , use_fast=_a , legacy=_a )
SCREAMING_SNAKE_CASE__ : Optional[Any] = [
"""Bonjour monsieur <extra_id_0> bien <extra_id_1>.""",
"""No se como puedo <extra_id_0>.""",
"""This is the reason why we <extra_id_0> them.""",
"""The <extra_id_0> walks in <extra_id_1>, seats""",
"""A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""",
]
SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_a , return_tensors="""pt""" , padding=_a ).input_ids
# fmt: off
SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor(
[
[ 38_530, 210_703, 256_299, 1_410, 256_298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0],
[ 826, 321, 671, 25_922, 256_299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0],
[ 1_460, 339, 312, 19_014, 10_620, 758, 256_299, 2_355,274, 1, 0, 0, 0, 0, 0, 0,0, 0],
[ 517, 256_299, 14_869, 281, 301, 256_298, 275, 119_983,1, 0, 0, 0, 0, 0, 0, 0,0, 0],
[ 320, 256_299, 14_869, 281, 2_234, 289, 2_275, 333,61_391, 289, 256_298, 543, 256_297, 168_714, 329, 256_296,274, 1],
] )
# fmt: on
torch.testing.assert_allclose(_a , _a )
SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids.to(_a ) )
SCREAMING_SNAKE_CASE__ : int = [
"""<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>""",
"""<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""",
"""<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""",
"""<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""",
"""<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""",
]
SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.batch_decode(_a )
self.assertEqual(_a , _a )
| 12 | 1 |
"""simple docstring"""
import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union
import sentencepiece
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
_snake_case = logging.get_logger(__name__)
_snake_case = '''▁'''
_snake_case = {
'''vocab_file''': '''vocab.json''',
'''spm_file''': '''sentencepiece.bpe.model''',
}
_snake_case = {
'''vocab_file''': {
'''facebook/s2t-small-librispeech-asr''': (
'''https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json'''
),
},
'''spm_file''': {
'''facebook/s2t-small-librispeech-asr''': (
'''https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model'''
)
},
}
_snake_case = {
'''facebook/s2t-small-librispeech-asr''': 1_0_2_4,
}
_snake_case = ['''pt''', '''fr''', '''ru''', '''nl''', '''ro''', '''it''', '''es''', '''de''']
_snake_case = {'''mustc''': MUSTC_LANGS}
class _SCREAMING_SNAKE_CASE ( UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: Optional[int] = VOCAB_FILES_NAMES
SCREAMING_SNAKE_CASE_: List[Any] = PRETRAINED_VOCAB_FILES_MAP
SCREAMING_SNAKE_CASE_: List[Any] = MAX_MODEL_INPUT_SIZES
SCREAMING_SNAKE_CASE_: Dict = ["input_ids", "attention_mask"]
SCREAMING_SNAKE_CASE_: Optional[int] = []
def __init__( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[str]="<s>" , UpperCAmelCase_ : Optional[Any]="</s>" , UpperCAmelCase_ : Optional[int]="<pad>" , UpperCAmelCase_ : int="<unk>" , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : int=False , UpperCAmelCase_ : int=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Union[str, Any] = None , **UpperCAmelCase_ : Any , ) -> int:
"""simple docstring"""
_lowerCAmelCase = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , do_upper_case=UpperCAmelCase_ , do_lower_case=UpperCAmelCase_ , tgt_lang=UpperCAmelCase_ , lang_codes=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , )
_lowerCAmelCase = do_upper_case
_lowerCAmelCase = do_lower_case
_lowerCAmelCase = load_json(UpperCAmelCase_ )
_lowerCAmelCase = {v: k for k, v in self.encoder.items()}
_lowerCAmelCase = spm_file
_lowerCAmelCase = load_spm(UpperCAmelCase_ , self.sp_model_kwargs )
if lang_codes is not None:
_lowerCAmelCase = lang_codes
_lowerCAmelCase = LANGUAGES[lang_codes]
_lowerCAmelCase = [F"""<lang:{lang}>""" for lang in self.langs]
_lowerCAmelCase = {lang: self.sp_model.PieceToId(F"""<lang:{lang}>""" ) for lang in self.langs}
_lowerCAmelCase = self.lang_tokens
_lowerCAmelCase = tgt_lang if tgt_lang is not None else self.langs[0]
self.set_tgt_lang_special_tokens(self._tgt_lang )
else:
_lowerCAmelCase = {}
@property
def __lowerCamelCase ( self : Any ) -> Tuple:
"""simple docstring"""
return len(self.encoder )
@property
def __lowerCamelCase ( self : Any ) -> Tuple:
"""simple docstring"""
return self._tgt_lang
@tgt_lang.setter
def __lowerCamelCase ( self : Any , UpperCAmelCase_ : str ) -> Any:
"""simple docstring"""
_lowerCAmelCase = new_tgt_lang
self.set_tgt_lang_special_tokens(UpperCAmelCase_ )
def __lowerCamelCase ( self : List[str] , UpperCAmelCase_ : int ) -> int:
"""simple docstring"""
_lowerCAmelCase = self.lang_code_to_id[tgt_lang]
_lowerCAmelCase = [lang_code_id]
def __lowerCamelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) -> List[Any]:
"""simple docstring"""
return self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ )
def __lowerCamelCase ( self : List[str] , UpperCAmelCase_ : int ) -> Union[str, Any]:
"""simple docstring"""
return self.encoder.get(UpperCAmelCase_ , self.encoder[self.unk_token] )
def __lowerCamelCase ( self : List[Any] , UpperCAmelCase_ : List[str] ) -> Union[str, Any]:
"""simple docstring"""
return self.decoder.get(UpperCAmelCase_ , self.unk_token )
def __lowerCamelCase ( self : Any , UpperCAmelCase_ : Dict ) -> Optional[int]:
"""simple docstring"""
_lowerCAmelCase = []
_lowerCAmelCase = ''
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
_lowerCAmelCase = self.sp_model.decode(UpperCAmelCase_ )
out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " "
_lowerCAmelCase = []
else:
current_sub_tokens.append(UpperCAmelCase_ )
_lowerCAmelCase = self.sp_model.decode(UpperCAmelCase_ )
out_string += decoded.upper() if self.do_upper_case else decoded
return out_string.strip()
def __lowerCamelCase ( self : Union[str, Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int]=None ) -> str:
"""simple docstring"""
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + [self.eos_token_id]
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id]
def __lowerCamelCase ( self : Any , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any] = None , UpperCAmelCase_ : Any = False ) -> List[str]:
"""simple docstring"""
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ )
_lowerCAmelCase = [1] * len(self.prefix_tokens )
_lowerCAmelCase = [1]
if token_ids_a is None:
return prefix_ones + ([0] * len(UpperCAmelCase_ )) + suffix_ones
return prefix_ones + ([0] * len(UpperCAmelCase_ )) + ([0] * len(UpperCAmelCase_ )) + suffix_ones
def __lowerCamelCase ( self : int ) -> Dict:
"""simple docstring"""
_lowerCAmelCase = self.encoder.copy()
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : Optional[Any] ) -> Dict:
"""simple docstring"""
_lowerCAmelCase = self.__dict__.copy()
_lowerCAmelCase = None
return state
def __setstate__( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] ) -> str:
"""simple docstring"""
_lowerCAmelCase = d
# for backward compatibility
if not hasattr(self , 'sp_model_kwargs' ):
_lowerCAmelCase = {}
_lowerCAmelCase = load_spm(self.spm_file , self.sp_model_kwargs )
def __lowerCamelCase ( self : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] = None ) -> List[Any]:
"""simple docstring"""
_lowerCAmelCase = Path(UpperCAmelCase_ )
assert save_dir.is_dir(), F"""{save_directory} should be a directory"""
_lowerCAmelCase = save_dir / (
(filename_prefix + '-' if filename_prefix else '') + self.vocab_files_names['vocab_file']
)
_lowerCAmelCase = save_dir / (
(filename_prefix + '-' if filename_prefix else '') + self.vocab_files_names['spm_file']
)
save_json(self.encoder , UpperCAmelCase_ )
if os.path.abspath(self.spm_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.spm_file ):
copyfile(self.spm_file , UpperCAmelCase_ )
elif not os.path.isfile(self.spm_file ):
with open(UpperCAmelCase_ , 'wb' ) as fi:
_lowerCAmelCase = self.sp_model.serialized_model_proto()
fi.write(UpperCAmelCase_ )
return (str(UpperCAmelCase_ ), str(UpperCAmelCase_ ))
def __snake_case ( SCREAMING_SNAKE_CASE: Union[str, Any] , SCREAMING_SNAKE_CASE: str ):
"""simple docstring"""
_lowerCAmelCase = sentencepiece.SentencePieceProcessor(**lowercase__ )
spm.Load(str(lowercase__ ) )
return spm
def __snake_case ( SCREAMING_SNAKE_CASE: List[Any] ):
"""simple docstring"""
with open(lowercase__ , 'r' ) as f:
return json.load(lowercase__ )
def __snake_case ( SCREAMING_SNAKE_CASE: Dict , SCREAMING_SNAKE_CASE: int ):
"""simple docstring"""
with open(lowercase__ , 'w' ) as f:
json.dump(lowercase__ , lowercase__ , indent=2 )
| 580 |
"""simple docstring"""
import gc
import unittest
import numpy as np
import torch
from diffusers import (
AudioDiffusionPipeline,
AutoencoderKL,
DDIMScheduler,
DDPMScheduler,
DiffusionPipeline,
Mel,
UNetaDConditionModel,
UNetaDModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
enable_full_determinism()
class lowerCAmelCase__ ( unittest.TestCase ):
'''simple docstring'''
def A_ ( self ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@property
def A_ ( self ):
torch.manual_seed(0 )
_lowerCamelCase : Union[str, Any] = UNetaDModel(
sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , )
return model
@property
def A_ ( self ):
torch.manual_seed(0 )
_lowerCamelCase : Dict = UNetaDConditionModel(
sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , cross_attention_dim=10 , )
return model
@property
def A_ ( self ):
torch.manual_seed(0 )
_lowerCamelCase : List[str] = AutoencoderKL(
sample_size=(128, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , )
_lowerCamelCase : int = UNetaDModel(
sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , )
return vqvae, unet
@slow
def A_ ( self ):
_lowerCamelCase : str = 'cpu' # ensure determinism for the device-dependent torch.Generator
_lowerCamelCase : Optional[int] = Mel(
x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , )
_lowerCamelCase : List[str] = DDPMScheduler()
_lowerCamelCase : List[Any] = AudioDiffusionPipeline(vqvae=lowercase , unet=self.dummy_unet , mel=lowercase , scheduler=lowercase )
_lowerCamelCase : List[Any] = pipe.to(lowercase )
pipe.set_progress_bar_config(disable=lowercase )
_lowerCamelCase : Union[str, Any] = torch.Generator(device=lowercase ).manual_seed(42 )
_lowerCamelCase : Union[str, Any] = pipe(generator=lowercase , steps=4 )
_lowerCamelCase : Optional[Any] = output.audios[0]
_lowerCamelCase : int = output.images[0]
_lowerCamelCase : Dict = torch.Generator(device=lowercase ).manual_seed(42 )
_lowerCamelCase : Dict = pipe(generator=lowercase , steps=4 , return_dict=lowercase )
_lowerCamelCase : List[str] = output[0][0]
assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length)
assert (
image.height == self.dummy_unet.config.sample_size[0]
and image.width == self.dummy_unet.config.sample_size[1]
)
_lowerCamelCase : Optional[Any] = np.frombuffer(image.tobytes() , dtype='uint8' )[:10]
_lowerCamelCase : Dict = np.frombuffer(image_from_tuple.tobytes() , dtype='uint8' )[:10]
_lowerCamelCase : List[str] = np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127] )
assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0
_lowerCamelCase : List[Any] = Mel(
x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , )
_lowerCamelCase : Dict = DDIMScheduler()
_lowerCamelCase : Tuple = self.dummy_vqvae_and_unet
_lowerCamelCase : List[str] = AudioDiffusionPipeline(
vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=lowercase , scheduler=lowercase )
_lowerCamelCase : Tuple = pipe.to(lowercase )
pipe.set_progress_bar_config(disable=lowercase )
np.random.seed(0 )
_lowerCamelCase : Any = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) )
_lowerCamelCase : Optional[int] = torch.Generator(device=lowercase ).manual_seed(42 )
_lowerCamelCase : Dict = pipe(raw_audio=lowercase , generator=lowercase , start_step=5 , steps=10 )
_lowerCamelCase : str = output.images[0]
assert (
image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0]
and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1]
)
_lowerCamelCase : Dict = np.frombuffer(image.tobytes() , dtype='uint8' )[:10]
_lowerCamelCase : Union[str, Any] = np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121] )
assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
_lowerCamelCase : Dict = self.dummy_unet_condition
_lowerCamelCase : Optional[int] = AudioDiffusionPipeline(
vqvae=self.dummy_vqvae_and_unet[0] , unet=lowercase , mel=lowercase , scheduler=lowercase )
_lowerCamelCase : Dict = pipe.to(lowercase )
pipe.set_progress_bar_config(disable=lowercase )
np.random.seed(0 )
_lowerCamelCase : Optional[int] = torch.rand((1, 1, 10) )
_lowerCamelCase : Optional[Any] = pipe(generator=lowercase , encoding=lowercase )
_lowerCamelCase : Dict = output.images[0]
_lowerCamelCase : Tuple = np.frombuffer(image.tobytes() , dtype='uint8' )[:10]
_lowerCamelCase : List[str] = np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111] )
assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
@slow
@require_torch_gpu
class lowerCAmelCase__ ( unittest.TestCase ):
'''simple docstring'''
def A_ ( self ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def A_ ( self ):
_lowerCamelCase : Optional[Any] = torch_device
_lowerCamelCase : Dict = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256' )
_lowerCamelCase : List[str] = pipe.to(lowercase )
pipe.set_progress_bar_config(disable=lowercase )
_lowerCamelCase : int = torch.Generator(device=lowercase ).manual_seed(42 )
_lowerCamelCase : Tuple = pipe(generator=lowercase )
_lowerCamelCase : Dict = output.audios[0]
_lowerCamelCase : Dict = output.images[0]
assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length)
assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1]
_lowerCamelCase : Optional[int] = np.frombuffer(image.tobytes() , dtype='uint8' )[:10]
_lowerCamelCase : int = np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26] )
assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 | 630 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
SCREAMING_SNAKE_CASE_ = {
'configuration_clip': [
'CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP',
'CLIPConfig',
'CLIPOnnxConfig',
'CLIPTextConfig',
'CLIPVisionConfig',
],
'processing_clip': ['CLIPProcessor'],
'tokenization_clip': ['CLIPTokenizer'],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = ['CLIPTokenizerFast']
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = ['CLIPFeatureExtractor']
SCREAMING_SNAKE_CASE_ = ['CLIPImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = [
'CLIP_PRETRAINED_MODEL_ARCHIVE_LIST',
'CLIPModel',
'CLIPPreTrainedModel',
'CLIPTextModel',
'CLIPTextModelWithProjection',
'CLIPVisionModel',
'CLIPVisionModelWithProjection',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = [
'TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFCLIPModel',
'TFCLIPPreTrainedModel',
'TFCLIPTextModel',
'TFCLIPVisionModel',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = [
'FlaxCLIPModel',
'FlaxCLIPPreTrainedModel',
'FlaxCLIPTextModel',
'FlaxCLIPTextPreTrainedModel',
'FlaxCLIPVisionModel',
'FlaxCLIPVisionPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_clip import (
CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
CLIPConfig,
CLIPOnnxConfig,
CLIPTextConfig,
CLIPVisionConfig,
)
from .processing_clip import CLIPProcessor
from .tokenization_clip import CLIPTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_clip_fast import CLIPTokenizerFast
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_clip import CLIPFeatureExtractor
from .image_processing_clip import CLIPImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_clip import (
CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
CLIPModel,
CLIPPreTrainedModel,
CLIPTextModel,
CLIPTextModelWithProjection,
CLIPVisionModel,
CLIPVisionModelWithProjection,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_clip import (
TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
TFCLIPModel,
TFCLIPPreTrainedModel,
TFCLIPTextModel,
TFCLIPVisionModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_clip import (
FlaxCLIPModel,
FlaxCLIPPreTrainedModel,
FlaxCLIPTextModel,
FlaxCLIPTextPreTrainedModel,
FlaxCLIPVisionModel,
FlaxCLIPVisionPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 201 |
'''simple docstring'''
SCREAMING_SNAKE_CASE_ = 0 # The first color of the flag.
SCREAMING_SNAKE_CASE_ = 1 # The second color of the flag.
SCREAMING_SNAKE_CASE_ = 2 # The third color of the flag.
SCREAMING_SNAKE_CASE_ = (red, white, blue)
def __lowercase ( __SCREAMING_SNAKE_CASE ) -> list:
"""simple docstring"""
if not sequence:
return []
if len(__SCREAMING_SNAKE_CASE ) == 1:
return list(__SCREAMING_SNAKE_CASE )
__a = 0
__a = len(__SCREAMING_SNAKE_CASE ) - 1
__a = 0
while mid <= high:
if sequence[mid] == colors[0]:
__a , __a = sequence[mid], sequence[low]
low += 1
mid += 1
elif sequence[mid] == colors[1]:
mid += 1
elif sequence[mid] == colors[2]:
__a , __a = sequence[high], sequence[mid]
high -= 1
else:
__a = F'''The elements inside the sequence must contains only {colors} values'''
raise ValueError(__SCREAMING_SNAKE_CASE )
return sequence
if __name__ == "__main__":
import doctest
doctest.testmod()
SCREAMING_SNAKE_CASE_ = input('Enter numbers separated by commas:\n').strip()
SCREAMING_SNAKE_CASE_ = [int(item.strip()) for item in user_input.split(',')]
print(f"""{dutch_national_flag_sort(unsorted)}""")
| 201 | 1 |
import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile
import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load
try:
import torch
A : Union[str, Any] = True
except ImportError:
A : Optional[int] = False
try:
from torch.hub import _get_torch_home
A : Dict = _get_torch_home()
except ImportError:
A : Union[str, Any] = os.path.expanduser(
os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch'))
)
A : List[str] = os.path.join(torch_cache_home, 'transformers')
A : str = 'https://cdn.huggingface.co'
A : int = 'https://s3.amazonaws.com/models.huggingface.co/bert'
A : Dict = '/'.join(str(Path(__file__).resolve()).split('/')[:-1])
A : Any = os.path.join(PATH, 'config.yaml')
A : Dict = os.path.join(PATH, 'attributes.txt')
A : Any = os.path.join(PATH, 'objects.txt')
A : List[Any] = os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path)
A : int = os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE)
A : Optional[Any] = os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE)
A : List[Any] = 'pytorch_model.bin'
A : Tuple = 'config.yaml'
def __lowerCAmelCase ( a__=OBJECTS , a__=ATTRIBUTES ) -> str:
__a = []
with open(a__ ) as f:
for object in f.readlines():
vg_classes.append(object.split(''',''' )[0].lower().strip() )
__a = []
with open(a__ ) as f:
for object in f.readlines():
vg_attrs.append(object.split(''',''' )[0].lower().strip() )
return vg_classes, vg_attrs
def __lowerCAmelCase ( a__ ) -> Union[str, Any]:
__a = OrderedDict()
with open(a__ , '''rb''' ) as f:
__a = pkl.load(a__ )['''model''']
for k in copy.deepcopy(list(ckp.keys() ) ):
__a = ckp.pop(a__ )
if isinstance(a__ , np.ndarray ):
__a = torch.tensor(a__ )
else:
assert isinstance(a__ , torch.tensor ), type(a__ )
__a = v
return r
class __A:
snake_case_ = {}
def __init__( self , _snake_case , _snake_case = "root" , _snake_case=0 ) -> List[str]:
'''simple docstring'''
__a = name
__a = level
__a = {}
for k, v in dictionary.items():
if v is None:
raise ValueError()
__a = copy.deepcopy(_snake_case )
__a = copy.deepcopy(_snake_case )
if isinstance(_snake_case , _snake_case ):
__a = Config(_snake_case , name=_snake_case , level=level + 1 )
__a = v
setattr(self , _snake_case , _snake_case )
__a = d
def __repr__( self ) -> int:
'''simple docstring'''
return str(list((self._pointer.keys()) ) )
def __setattr__( self , _snake_case , _snake_case ) -> Union[str, Any]:
'''simple docstring'''
__a = val
__a = val
__a = key.split('''.''' )
__a = len(_snake_case ) - 1
__a = self._pointer
if len(_snake_case ) > 1:
for i, l in enumerate(_snake_case ):
if hasattr(self , _snake_case ) and isinstance(getattr(self , _snake_case ) , _snake_case ):
setattr(getattr(self , _snake_case ) , '''.'''.join(levels[i:] ) , _snake_case )
if l == last_level:
__a = val
else:
__a = pointer[l]
def SCREAMING_SNAKE_CASE_ ( self ) -> List[Any]:
'''simple docstring'''
return self._pointer
def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case ) -> str:
'''simple docstring'''
with open(F"""{file_name}""" , '''w''' ) as stream:
dump(_snake_case , _snake_case )
def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case ) -> Optional[Any]:
'''simple docstring'''
with open(F"""{file_name}""" , '''w''' ) as stream:
json.dump(_snake_case , _snake_case )
@staticmethod
def SCREAMING_SNAKE_CASE_ ( _snake_case ) -> List[Any]:
'''simple docstring'''
with open(_snake_case ) as stream:
__a = load(_snake_case , Loader=_snake_case )
return data
def __str__( self ) -> List[Any]:
'''simple docstring'''
__a = ''' '''
if self._name != "root":
__a = F"""{t * (self._level-1)}{self._name}:\n"""
else:
__a = ''''''
__a = self._level
for i, (k, v) in enumerate(self._pointer.items() ):
if isinstance(_snake_case , _snake_case ):
r += F"""{t * (self._level)}{v}\n"""
self._level += 1
else:
r += F"""{t * (self._level)}{k}: {v} ({type(_snake_case ).__name__})\n"""
__a = level
return r[:-1]
@classmethod
def SCREAMING_SNAKE_CASE_ ( cls , _snake_case , **_snake_case ) -> str:
'''simple docstring'''
__a , __a = cls.get_config_dict(_snake_case , **_snake_case )
return cls(_snake_case )
@classmethod
def SCREAMING_SNAKE_CASE_ ( cls , _snake_case , **_snake_case ) -> List[Any]:
'''simple docstring'''
__a = kwargs.pop('''cache_dir''' , _snake_case )
__a = kwargs.pop('''force_download''' , _snake_case )
__a = kwargs.pop('''resume_download''' , _snake_case )
__a = kwargs.pop('''proxies''' , _snake_case )
__a = kwargs.pop('''local_files_only''' , _snake_case )
if os.path.isdir(_snake_case ):
__a = os.path.join(_snake_case , _snake_case )
elif os.path.isfile(_snake_case ) or is_remote_url(_snake_case ):
__a = pretrained_model_name_or_path
else:
__a = hf_bucket_url(_snake_case , filename=_snake_case , use_cdn=_snake_case )
try:
# Load from URL or cache if already cached
__a = cached_path(
_snake_case , cache_dir=_snake_case , force_download=_snake_case , proxies=_snake_case , resume_download=_snake_case , local_files_only=_snake_case , )
# Load config dict
if resolved_config_file is None:
raise EnvironmentError
__a = Config.load_yaml(_snake_case )
except EnvironmentError:
__a = '''Can\'t load config for'''
raise EnvironmentError(_snake_case )
if resolved_config_file == config_file:
print('''loading configuration file from path''' )
else:
print('''loading configuration file cache''' )
return Config.load_yaml(_snake_case ), kwargs
def __lowerCAmelCase ( a__ ) -> List[str]:
__a = torch.load('''dump.pt''' , map_location=in_tensor.device )
__a = in_tensor.numpy()
__a = out_tensor.numpy()[0]
print(na.shape , na[0, 0, :5] )
print(na.shape , na[0, 0, :5] )
assert np.allclose(a__ , a__ , rtol=0.01 , atol=0.1 ), (
F"""{sum([1 for x in np.isclose(a__ , a__ , rtol=0.01 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %"""
" element-wise mismatch"
)
raise Exception('''tensors are all good''' )
# Hugging face functions below
def __lowerCAmelCase ( a__ ) -> List[Any]:
__a = urlparse(a__ )
return parsed.scheme in ("http", "https")
def __lowerCAmelCase ( a__ , a__ , a__=True ) -> str:
__a = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
__a = '''/''' not in model_id
if legacy_format:
return F"""{endpoint}/{model_id}-{filename}"""
else:
return F"""{endpoint}/{model_id}/{filename}"""
def __lowerCAmelCase ( a__ , a__ , a__=None , a__=0 , a__=None , ) -> List[Any]:
__a = '''python/{}'''.format(sys.version.split()[0] )
if _torch_available:
ua += "; torch/{}".format(torch.__version__ )
if isinstance(a__ , a__ ):
ua += "; " + "; ".join('''{}/{}'''.format(a__ , a__ ) for k, v in user_agent.items() )
elif isinstance(a__ , a__ ):
ua += "; " + user_agent
__a = {'''user-agent''': ua}
if resume_size > 0:
__a = '''bytes=%d-''' % (resume_size,)
__a = requests.get(a__ , stream=a__ , proxies=a__ , headers=a__ )
if response.status_code == 416: # Range not satisfiable
return
__a = response.headers.get('''Content-Length''' )
__a = resume_size + int(a__ ) if content_length is not None else None
__a = tqdm(
unit='''B''' , unit_scale=a__ , total=a__ , initial=a__ , desc='''Downloading''' , )
for chunk in response.iter_content(chunk_size=1024 ):
if chunk: # filter out keep-alive new chunks
progress.update(len(a__ ) )
temp_file.write(a__ )
progress.close()
def __lowerCAmelCase ( a__ , a__=None , a__=False , a__=None , a__=10 , a__=False , a__=None , a__=False , ) -> Optional[Any]:
if cache_dir is None:
__a = TRANSFORMERS_CACHE
if isinstance(a__ , a__ ):
__a = str(a__ )
os.makedirs(a__ , exist_ok=a__ )
__a = None
if not local_files_only:
try:
__a = requests.head(a__ , allow_redirects=a__ , proxies=a__ , timeout=a__ )
if response.status_code == 200:
__a = response.headers.get('''ETag''' )
except (EnvironmentError, requests.exceptions.Timeout):
# etag is already None
pass
__a = url_to_filename(a__ , a__ )
# get cache path to put the file
__a = os.path.join(a__ , a__ )
# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
# try to get the last downloaded one
if etag is None:
if os.path.exists(a__ ):
return cache_path
else:
__a = [
file
for file in fnmatch.filter(os.listdir(a__ ) , filename + '''.*''' )
if not file.endswith('''.json''' ) and not file.endswith('''.lock''' )
]
if len(a__ ) > 0:
return os.path.join(a__ , matching_files[-1] )
else:
# If files cannot be found and local_files_only=True,
# the models might've been found if local_files_only=False
# Notify the user about that
if local_files_only:
raise ValueError(
'''Cannot find the requested files in the cached path and outgoing traffic has been'''
''' disabled. To enable model look-ups and downloads online, set \'local_files_only\''''
''' to False.''' )
return None
# From now on, etag is not None.
if os.path.exists(a__ ) and not force_download:
return cache_path
# Prevent parallel downloads of the same file with a lock.
__a = cache_path + '''.lock'''
with FileLock(a__ ):
# If the download just completed while the lock was activated.
if os.path.exists(a__ ) and not force_download:
# Even if returning early like here, the lock will be released.
return cache_path
if resume_download:
__a = cache_path + '''.incomplete'''
@contextmanager
def _resumable_file_manager():
with open(a__ , '''a+b''' ) as f:
yield f
__a = _resumable_file_manager
if os.path.exists(a__ ):
__a = os.stat(a__ ).st_size
else:
__a = 0
else:
__a = partial(tempfile.NamedTemporaryFile , dir=a__ , delete=a__ )
__a = 0
# Download to temporary file, then copy to cache dir once finished.
# Otherwise you get corrupt cache entries if the download gets interrupted.
with temp_file_manager() as temp_file:
print(
'''%s not found in cache or force_download set to True, downloading to %s''' , a__ , temp_file.name , )
http_get(
a__ , a__ , proxies=a__ , resume_size=a__ , user_agent=a__ , )
os.replace(temp_file.name , a__ )
__a = {'''url''': url, '''etag''': etag}
__a = cache_path + '''.json'''
with open(a__ , '''w''' ) as meta_file:
json.dump(a__ , a__ )
return cache_path
def __lowerCAmelCase ( a__ , a__=None ) -> Tuple:
__a = url.encode('''utf-8''' )
__a = shaaaa(a__ )
__a = url_hash.hexdigest()
if etag:
__a = etag.encode('''utf-8''' )
__a = shaaaa(a__ )
filename += "." + etag_hash.hexdigest()
if url.endswith('''.h5''' ):
filename += ".h5"
return filename
def __lowerCAmelCase ( a__ , a__=None , a__=False , a__=None , a__=False , a__=None , a__=False , a__=False , a__=False , ) -> Tuple:
if cache_dir is None:
__a = TRANSFORMERS_CACHE
if isinstance(a__ , a__ ):
__a = str(a__ )
if isinstance(a__ , a__ ):
__a = str(a__ )
if is_remote_url(a__ ):
# URL, so get it from the cache (downloading if necessary)
__a = get_from_cache(
a__ , cache_dir=a__ , force_download=a__ , proxies=a__ , resume_download=a__ , user_agent=a__ , local_files_only=a__ , )
elif os.path.exists(a__ ):
# File, and it exists.
__a = url_or_filename
elif urlparse(a__ ).scheme == "":
# File, but it doesn't exist.
raise EnvironmentError('''file {} not found'''.format(a__ ) )
else:
# Something unknown
raise ValueError('''unable to parse {} as a URL or as a local path'''.format(a__ ) )
if extract_compressed_file:
if not is_zipfile(a__ ) and not tarfile.is_tarfile(a__ ):
return output_path
# Path where we extract compressed archives
# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
__a , __a = os.path.split(a__ )
__a = output_file.replace('''.''' , '''-''' ) + '''-extracted'''
__a = os.path.join(a__ , a__ )
if os.path.isdir(a__ ) and os.listdir(a__ ) and not force_extract:
return output_path_extracted
# Prevent parallel extractions
__a = output_path + '''.lock'''
with FileLock(a__ ):
shutil.rmtree(a__ , ignore_errors=a__ )
os.makedirs(a__ )
if is_zipfile(a__ ):
with ZipFile(a__ , '''r''' ) as zip_file:
zip_file.extractall(a__ )
zip_file.close()
elif tarfile.is_tarfile(a__ ):
__a = tarfile.open(a__ )
tar_file.extractall(a__ )
tar_file.close()
else:
raise EnvironmentError('''Archive format of {} could not be identified'''.format(a__ ) )
return output_path_extracted
return output_path
def __lowerCAmelCase ( a__ , a__="," ) -> Optional[int]:
assert isinstance(a__ , a__ )
if os.path.isfile(a__ ):
with open(a__ ) as f:
__a = eval(f.read() )
else:
__a = requests.get(a__ )
try:
__a = requests.json()
except Exception:
__a = req.content.decode()
assert data is not None, "could not connect"
try:
__a = eval(a__ )
except Exception:
__a = data.split('''\n''' )
req.close()
return data
def __lowerCAmelCase ( a__ ) -> List[Any]:
__a = requests.get(a__ )
__a = np.array(Image.open(BytesIO(response.content ) ) )
return img
def __lowerCAmelCase ( a__ ) -> Any:
__a = url.split('''/''' )[-1]
if fn not in os.listdir(os.getcwd() ):
wget.download(a__ )
with open(a__ , '''rb''' ) as stream:
__a = pkl.load(a__ )
__a = weights.pop('''model''' )
__a = {}
for k, v in model.items():
__a = torch.from_numpy(a__ )
if "running_var" in k:
__a = torch.tensor([0] )
__a = k.replace('''running_var''' , '''num_batches_tracked''' )
__a = zero
return new
def __lowerCAmelCase ( ) -> Optional[int]:
print(F"""{os.path.abspath(os.path.join(a__ , os.pardir ) )}/demo.ipynb""" )
def __lowerCAmelCase ( a__ , a__="RGB" ) -> List[Any]:
assert isinstance(a__ , a__ )
if os.path.isfile(a__ ):
__a = cva.imread(a__ )
else:
__a = get_image_from_url(a__ )
assert img is not None, F"""could not connect to: {im}"""
__a = cva.cvtColor(a__ , cva.COLOR_BGR2RGB )
if input_format == "RGB":
__a = img[:, :, ::-1]
return img
def __lowerCAmelCase ( a__ , a__=1 ) -> Optional[Any]:
return (images[i : i + batch] for i in range(0 , len(a__ ) , a__ )) | 219 |
import os
import unittest
from tempfile import TemporaryDirectory
import torch
import torch.nn as nn
from accelerate.utils import (
OffloadedWeightsLoader,
extract_submodules_state_dict,
load_offloaded_weight,
offload_state_dict,
offload_weight,
)
class __A( nn.Module ):
def __init__( self ) -> int:
'''simple docstring'''
super().__init__()
__a = nn.Linear(3 , 4 )
__a = nn.BatchNormad(4 )
__a = nn.Linear(4 , 5 )
def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> int:
'''simple docstring'''
return self.lineara(self.batchnorm(self.lineara(_snake_case ) ) )
class __A( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[Any]:
'''simple docstring'''
__a = ModelForTest()
with TemporaryDirectory() as tmp_dir:
offload_state_dict(_snake_case , model.state_dict() )
__a = os.path.join(_snake_case , '''index.json''' )
self.assertTrue(os.path.isfile(_snake_case ) )
# TODO: add tests on what is inside the index
for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]:
__a = os.path.join(_snake_case , F"""{key}.dat""" )
self.assertTrue(os.path.isfile(_snake_case ) )
# TODO: add tests on the fact weights are properly loaded
def SCREAMING_SNAKE_CASE_ ( self ) -> Any:
'''simple docstring'''
__a = [torch.floataa, torch.floataa, torch.bfloataa]
for dtype in dtypes:
__a = torch.randn(2 , 3 , dtype=_snake_case )
with TemporaryDirectory() as tmp_dir:
__a = offload_weight(_snake_case , '''weight''' , _snake_case , {} )
__a = os.path.join(_snake_case , '''weight.dat''' )
self.assertTrue(os.path.isfile(_snake_case ) )
self.assertDictEqual(_snake_case , {'''weight''': {'''shape''': [2, 3], '''dtype''': str(_snake_case ).split('''.''' )[1]}} )
__a = load_offloaded_weight(_snake_case , index['''weight'''] )
self.assertTrue(torch.equal(_snake_case , _snake_case ) )
def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[int]:
'''simple docstring'''
__a = ModelForTest()
__a = model.state_dict()
__a = {k: v for k, v in state_dict.items() if '''linear2''' not in k}
__a = {k: v for k, v in state_dict.items() if '''linear2''' in k}
with TemporaryDirectory() as tmp_dir:
offload_state_dict(_snake_case , _snake_case )
__a = OffloadedWeightsLoader(state_dict=_snake_case , save_folder=_snake_case )
# Every key is there with the right value
self.assertEqual(sorted(_snake_case ) , sorted(state_dict.keys() ) )
for key, param in state_dict.items():
self.assertTrue(torch.allclose(_snake_case , weight_map[key] ) )
__a = {k: v for k, v in state_dict.items() if '''weight''' in k}
__a = {k: v for k, v in state_dict.items() if '''weight''' not in k}
with TemporaryDirectory() as tmp_dir:
offload_state_dict(_snake_case , _snake_case )
__a = OffloadedWeightsLoader(state_dict=_snake_case , save_folder=_snake_case )
# Every key is there with the right value
self.assertEqual(sorted(_snake_case ) , sorted(state_dict.keys() ) )
for key, param in state_dict.items():
self.assertTrue(torch.allclose(_snake_case , weight_map[key] ) )
with TemporaryDirectory() as tmp_dir:
offload_state_dict(_snake_case , _snake_case )
# Duplicates are removed
__a = OffloadedWeightsLoader(state_dict=_snake_case , save_folder=_snake_case )
# Every key is there with the right value
self.assertEqual(sorted(_snake_case ) , sorted(state_dict.keys() ) )
for key, param in state_dict.items():
self.assertTrue(torch.allclose(_snake_case , weight_map[key] ) )
def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple:
'''simple docstring'''
__a = {'''a.1''': 0, '''a.10''': 1, '''a.2''': 2}
__a = extract_submodules_state_dict(_snake_case , ['''a.1''', '''a.2'''] )
self.assertDictEqual(_snake_case , {'''a.1''': 0, '''a.2''': 2} )
__a = {'''a.1.a''': 0, '''a.10.a''': 1, '''a.2.a''': 2}
__a = extract_submodules_state_dict(_snake_case , ['''a.1''', '''a.2'''] )
self.assertDictEqual(_snake_case , {'''a.1.a''': 0, '''a.2.a''': 2} ) | 219 | 1 |
'''simple docstring'''
lowercase : Dict = [0, 2, 4, 6, 8]
lowercase : List[Any] = [1, 3, 5, 7, 9]
def __a ( A__ , A__ , A__ , A__ ) -> int:
if remaining_length == 0:
if digits[0] == 0 or digits[-1] == 0:
return 0
for i in range(length // 2 - 1 , -1 , -1 ):
remainder += digits[i] + digits[length - i - 1]
if remainder % 2 == 0:
return 0
remainder //= 10
return 1
if remaining_length == 1:
if remainder % 2 == 0:
return 0
lowerCAmelCase = 0
for digit in range(10 ):
lowerCAmelCase = digit
result += reversible_numbers(
0 , (remainder + 2 * digit) // 10 , A__ , A__ )
return result
lowerCAmelCase = 0
for digita in range(10 ):
lowerCAmelCase = digita
if (remainder + digita) % 2 == 0:
lowerCAmelCase = ODD_DIGITS
else:
lowerCAmelCase = EVEN_DIGITS
for digita in other_parity_digits:
lowerCAmelCase = digita
result += reversible_numbers(
remaining_length - 2 , (remainder + digita + digita) // 10 , A__ , A__ , )
return result
def __a ( A__ = 9 ) -> int:
lowerCAmelCase = 0
for length in range(1 , max_power + 1 ):
result += reversible_numbers(A__ , 0 , [0] * length , A__ )
return result
if __name__ == "__main__":
print(f"{solution() = }")
| 159 |
'''simple docstring'''
import itertools
import random
import unittest
import numpy as np
from transformers import BatchFeature, SpeechTaFeatureExtractor
from transformers.testing_utils import require_torch
from transformers.utils.import_utils import is_torch_available
from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin
if is_torch_available():
import torch
lowercase : Optional[int] = random.Random()
def __a ( A__ , A__=1.0 , A__=None , A__=None ) -> Any:
if rng is None:
lowerCAmelCase = global_rng
lowerCAmelCase = []
for batch_idx in range(shape[0] ):
values.append([] )
for _ in range(shape[1] ):
values[-1].append(rng.random() * scale )
return values
@require_torch
class _lowerCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : int=7 , SCREAMING_SNAKE_CASE : Optional[Any]=4_0_0 , SCREAMING_SNAKE_CASE : Optional[Any]=2_0_0_0 , SCREAMING_SNAKE_CASE : Union[str, Any]=1 , SCREAMING_SNAKE_CASE : int=0.0 , SCREAMING_SNAKE_CASE : Optional[int]=1_6_0_0_0 , SCREAMING_SNAKE_CASE : Any=True , SCREAMING_SNAKE_CASE : Optional[Any]=8_0 , SCREAMING_SNAKE_CASE : int=1_6 , SCREAMING_SNAKE_CASE : Any=6_4 , SCREAMING_SNAKE_CASE : List[Any]="hann_window" , SCREAMING_SNAKE_CASE : Dict=8_0 , SCREAMING_SNAKE_CASE : Any=7_6_0_0 , SCREAMING_SNAKE_CASE : Optional[Any]=1E-10 , SCREAMING_SNAKE_CASE : Union[str, Any]=True , ) -> Any:
"""simple docstring"""
lowerCAmelCase = parent
lowerCAmelCase = batch_size
lowerCAmelCase = min_seq_length
lowerCAmelCase = max_seq_length
lowerCAmelCase = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
lowerCAmelCase = feature_size
lowerCAmelCase = padding_value
lowerCAmelCase = sampling_rate
lowerCAmelCase = do_normalize
lowerCAmelCase = num_mel_bins
lowerCAmelCase = hop_length
lowerCAmelCase = win_length
lowerCAmelCase = win_function
lowerCAmelCase = fmin
lowerCAmelCase = fmax
lowerCAmelCase = mel_floor
lowerCAmelCase = return_attention_mask
def __A ( self : Union[str, Any] ) -> List[str]:
"""simple docstring"""
return {
"feature_size": self.feature_size,
"padding_value": self.padding_value,
"sampling_rate": self.sampling_rate,
"do_normalize": self.do_normalize,
"num_mel_bins": self.num_mel_bins,
"hop_length": self.hop_length,
"win_length": self.win_length,
"win_function": self.win_function,
"fmin": self.fmin,
"fmax": self.fmax,
"mel_floor": self.mel_floor,
"return_attention_mask": self.return_attention_mask,
}
def __A ( self : List[str] , SCREAMING_SNAKE_CASE : int=False , SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> str:
"""simple docstring"""
def _flatten(SCREAMING_SNAKE_CASE : List[Any] ):
return list(itertools.chain(*SCREAMING_SNAKE_CASE ) )
if equal_length:
lowerCAmelCase = floats_list((self.batch_size, self.max_seq_length) )
else:
# make sure that inputs increase in size
lowerCAmelCase = [
_flatten(floats_list((x, self.feature_size) ) )
for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff )
]
if numpify:
lowerCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE ) for x in speech_inputs]
return speech_inputs
def __A ( self : List[str] , SCREAMING_SNAKE_CASE : Tuple=False , SCREAMING_SNAKE_CASE : Optional[int]=False ) -> str:
"""simple docstring"""
if equal_length:
lowerCAmelCase = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )]
else:
# make sure that inputs increase in size
lowerCAmelCase = [
floats_list((x, self.num_mel_bins) )
for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff )
]
if numpify:
lowerCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE ) for x in speech_inputs]
return speech_inputs
@require_torch
class _lowerCAmelCase ( UpperCamelCase_ , unittest.TestCase ):
"""simple docstring"""
lowerCAmelCase = SpeechTaFeatureExtractor
def __A ( self : Optional[int] ) -> Dict:
"""simple docstring"""
lowerCAmelCase = SpeechTaFeatureExtractionTester(self )
def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]:
"""simple docstring"""
self.assertTrue(np.all(np.mean(SCREAMING_SNAKE_CASE , axis=0 ) < 1E-3 ) )
self.assertTrue(np.all(np.abs(np.var(SCREAMING_SNAKE_CASE , axis=0 ) - 1 ) < 1E-3 ) )
def __A ( self : int ) -> Union[str, Any]:
"""simple docstring"""
lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
# create three inputs of length 800, 1000, and 1200
lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
lowerCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs]
# Test not batched input
lowerCAmelCase = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values
lowerCAmelCase = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values
self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) )
# Test batched
lowerCAmelCase = feat_extract(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values
lowerCAmelCase = feat_extract(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values
for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) )
def __A ( self : Any ) -> Union[str, Any]:
"""simple docstring"""
lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
lowerCAmelCase = ["longest", "max_length", "do_not_pad"]
lowerCAmelCase = [None, 1_6_0_0, None]
for max_length, padding in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
lowerCAmelCase = feat_extract(SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , return_tensors="np" )
lowerCAmelCase = processed.input_values
self._check_zero_mean_unit_variance(input_values[0][:8_0_0] )
self.assertTrue(input_values[0][8_0_0:].sum() < 1E-6 )
self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] )
self.assertTrue(input_values[0][1_0_0_0:].sum() < 1E-6 )
self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] )
def __A ( self : Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
lowerCAmelCase = range(8_0_0 , 1_4_0_0 , 2_0_0 )
lowerCAmelCase = [floats_list((1, x) )[0] for x in lengths]
lowerCAmelCase = ["longest", "max_length", "do_not_pad"]
lowerCAmelCase = [None, 1_6_0_0, None]
for max_length, padding in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
lowerCAmelCase = feat_extract(SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE )
lowerCAmelCase = processed.input_values
self._check_zero_mean_unit_variance(input_values[0][:8_0_0] )
self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] )
self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] )
def __A ( self : str ) -> Any:
"""simple docstring"""
lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
lowerCAmelCase = feat_extract(
SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=1_0_0_0 , padding="max_length" , return_tensors="np" )
lowerCAmelCase = processed.input_values
self._check_zero_mean_unit_variance(input_values[0, :8_0_0] )
self._check_zero_mean_unit_variance(input_values[1] )
self._check_zero_mean_unit_variance(input_values[2] )
def __A ( self : int ) -> Optional[int]:
"""simple docstring"""
lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
lowerCAmelCase = feat_extract(
SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=1_0_0_0 , padding="longest" , return_tensors="np" )
lowerCAmelCase = processed.input_values
self._check_zero_mean_unit_variance(input_values[0, :8_0_0] )
self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] )
self._check_zero_mean_unit_variance(input_values[2] )
# make sure that if max_length < longest -> then pad to max_length
self.assertTrue(input_values.shape == (3, 1_0_0_0) )
lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
lowerCAmelCase = feat_extract(
SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=2_0_0_0 , padding="longest" , return_tensors="np" )
lowerCAmelCase = processed.input_values
self._check_zero_mean_unit_variance(input_values[0, :8_0_0] )
self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] )
self._check_zero_mean_unit_variance(input_values[2] )
# make sure that if max_length > longest -> then pad to longest
self.assertTrue(input_values.shape == (3, 1_2_0_0) )
def __A ( self : Optional[int] ) -> Any:
"""simple docstring"""
lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
lowerCAmelCase = np.random.rand(1_0_0 ).astype(np.floataa )
lowerCAmelCase = np_speech_inputs.tolist()
for inputs in [py_speech_inputs, np_speech_inputs]:
lowerCAmelCase = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" )
self.assertTrue(np_processed.input_values.dtype == np.floataa )
lowerCAmelCase = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" )
self.assertTrue(pt_processed.input_values.dtype == torch.floataa )
def __A ( self : int ) -> Optional[int]:
"""simple docstring"""
lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
# create three inputs of length 800, 1000, and 1200
lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
lowerCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs]
# Test feature size
lowerCAmelCase = feature_extractor(audio_target=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values
self.assertTrue(input_values.ndim == 3 )
self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins )
# Test not batched input
lowerCAmelCase = feature_extractor(speech_inputs[0] , return_tensors="np" ).input_values
lowerCAmelCase = feature_extractor(np_speech_inputs[0] , return_tensors="np" ).input_values
self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) )
# Test batched
lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values
lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values
for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) )
# Test 2-D numpy arrays are batched.
lowerCAmelCase = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
lowerCAmelCase = np.asarray(SCREAMING_SNAKE_CASE )
lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values
lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values
for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) )
def __A ( self : Dict ) -> Optional[Any]:
"""simple docstring"""
lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target()
lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_dict )
lowerCAmelCase = feat_extract.model_input_names[0]
lowerCAmelCase = BatchFeature({input_name: speech_inputs} )
self.assertTrue(all(len(SCREAMING_SNAKE_CASE ) == len(SCREAMING_SNAKE_CASE ) for x, y in zip(SCREAMING_SNAKE_CASE , processed_features[input_name] ) ) )
lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target(equal_length=SCREAMING_SNAKE_CASE )
lowerCAmelCase = BatchFeature({input_name: speech_inputs} , tensor_type="np" )
lowerCAmelCase = processed_features[input_name]
if len(batch_features_input.shape ) < 3:
lowerCAmelCase = batch_features_input[:, :, None]
self.assertTrue(
batch_features_input.shape
== (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) )
@require_torch
def __A ( self : List[str] ) -> Optional[int]:
"""simple docstring"""
lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target(equal_length=SCREAMING_SNAKE_CASE )
lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_dict )
lowerCAmelCase = feat_extract.model_input_names[0]
lowerCAmelCase = BatchFeature({input_name: speech_inputs} , tensor_type="pt" )
lowerCAmelCase = processed_features[input_name]
if len(batch_features_input.shape ) < 3:
lowerCAmelCase = batch_features_input[:, :, None]
self.assertTrue(
batch_features_input.shape
== (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) )
@require_torch
def __A ( self : Optional[int] ) -> Dict:
"""simple docstring"""
lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_dict )
lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target()
lowerCAmelCase = feat_extract.model_input_names[0]
lowerCAmelCase = BatchFeature({input_name: speech_inputs} )
lowerCAmelCase = feat_extract.num_mel_bins # hack!
lowerCAmelCase = feat_extract.pad(SCREAMING_SNAKE_CASE , padding="longest" , return_tensors="np" )[input_name]
lowerCAmelCase = feat_extract.pad(SCREAMING_SNAKE_CASE , padding="longest" , return_tensors="pt" )[input_name]
self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 )
def __A ( self : Optional[Any] ) -> Union[str, Any]:
"""simple docstring"""
lowerCAmelCase = self.feat_extract_dict
lowerCAmelCase = True
lowerCAmelCase = self.feature_extraction_class(**SCREAMING_SNAKE_CASE )
lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target()
lowerCAmelCase = [len(SCREAMING_SNAKE_CASE ) for x in speech_inputs]
lowerCAmelCase = feat_extract.model_input_names[0]
lowerCAmelCase = BatchFeature({input_name: speech_inputs} )
lowerCAmelCase = feat_extract.num_mel_bins # hack!
lowerCAmelCase = feat_extract.pad(SCREAMING_SNAKE_CASE , padding="longest" , return_tensors="np" )
self.assertIn("attention_mask" , SCREAMING_SNAKE_CASE )
self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) )
self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , SCREAMING_SNAKE_CASE )
def __A ( self : Tuple ) -> List[Any]:
"""simple docstring"""
lowerCAmelCase = self.feat_extract_dict
lowerCAmelCase = True
lowerCAmelCase = self.feature_extraction_class(**SCREAMING_SNAKE_CASE )
lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target()
lowerCAmelCase = [len(SCREAMING_SNAKE_CASE ) for x in speech_inputs]
lowerCAmelCase = feat_extract.model_input_names[0]
lowerCAmelCase = BatchFeature({input_name: speech_inputs} )
lowerCAmelCase = min(SCREAMING_SNAKE_CASE )
lowerCAmelCase = feat_extract.num_mel_bins # hack!
lowerCAmelCase = feat_extract.pad(
SCREAMING_SNAKE_CASE , padding="max_length" , max_length=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , return_tensors="np" )
self.assertIn("attention_mask" , SCREAMING_SNAKE_CASE )
self.assertListEqual(
list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] )
self.assertListEqual(
processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] )
def __A ( self : Tuple , SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]:
"""simple docstring"""
from datasets import load_dataset
lowerCAmelCase = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" )
# automatic decoding with librispeech
lowerCAmelCase = ds.sort("id" ).select(range(SCREAMING_SNAKE_CASE ) )[:num_samples]["audio"]
return [x["array"] for x in speech_samples]
def __A ( self : List[Any] ) -> int:
"""simple docstring"""
lowerCAmelCase = torch.tensor(
[2.38_04E-03, 2.07_52E-03, 1.98_36E-03, 2.10_57E-03, 1.61_74E-03,
3.05_18E-04, 9.15_53E-05, 3.35_69E-04, 9.76_56E-04, 1.83_11E-03,
2.01_42E-03, 2.10_57E-03, 1.73_95E-03, 4.57_76E-04, -3.96_73E-04,
4.57_76E-04, 1.00_71E-03, 9.15_53E-05, 4.88_28E-04, 1.15_97E-03,
7.32_42E-04, 9.46_04E-04, 1.80_05E-03, 1.83_11E-03, 8.85_01E-04,
4.27_25E-04, 4.88_28E-04, 7.32_42E-04, 1.09_86E-03, 2.10_57E-03] )
# fmt: on
lowerCAmelCase = self._load_datasamples(1 )
lowerCAmelCase = SpeechTaFeatureExtractor()
lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="pt" ).input_values
self.assertEquals(input_values.shape , (1, 9_3_6_8_0) )
self.assertTrue(torch.allclose(input_values[0, :3_0] , SCREAMING_SNAKE_CASE , atol=1E-6 ) )
def __A ( self : Optional[Any] ) -> Optional[int]:
"""simple docstring"""
lowerCAmelCase = torch.tensor(
[-2.6_8_7_0, -3.0_1_0_4, -3.1_3_5_6, -3.5_3_5_2, -3.0_0_4_4, -3.0_3_5_3, -3.4_7_1_9, -3.6_7_7_7,
-3.1_5_2_0, -2.9_4_3_5, -2.6_5_5_3, -2.8_7_9_5, -2.9_9_4_4, -2.5_9_2_1, -3.0_2_7_9, -3.0_3_8_6,
-3.0_8_6_4, -3.1_2_9_1, -3.2_3_5_3, -2.7_4_4_4, -2.6_8_3_1, -2.7_2_8_7, -3.1_7_6_1, -3.1_5_7_1,
-3.2_7_2_6, -3.0_5_8_2, -3.1_0_0_7, -3.4_5_3_3, -3.4_6_9_5, -3.0_9_9_8] )
# fmt: on
lowerCAmelCase = self._load_datasamples(1 )
lowerCAmelCase = SpeechTaFeatureExtractor()
lowerCAmelCase = feature_extractor(audio_target=SCREAMING_SNAKE_CASE , return_tensors="pt" ).input_values
self.assertEquals(input_values.shape , (1, 3_6_6, 8_0) )
self.assertTrue(torch.allclose(input_values[0, 0, :3_0] , SCREAMING_SNAKE_CASE , atol=1E-4 ) )
| 159 | 1 |
'''simple docstring'''
import os
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_doctest_list.py
__lowerCAmelCase = "."
if __name__ == "__main__":
__lowerCAmelCase = os.path.join(REPO_PATH, "utils/documentation_tests.txt")
__lowerCAmelCase = []
__lowerCAmelCase = []
with open(doctest_file_path) as fp:
for line in fp:
__lowerCAmelCase = line.strip()
__lowerCAmelCase = os.path.join(REPO_PATH, line)
if not (os.path.isfile(path) or os.path.isdir(path)):
non_existent_paths.append(line)
all_paths.append(path)
if len(non_existent_paths) > 0:
__lowerCAmelCase = "\n".join(non_existent_paths)
raise ValueError(f"""`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}""")
if all_paths != sorted(all_paths):
raise ValueError("Files in `utils/documentation_tests.txt` are not in alphabetical order.")
| 536 |
'''simple docstring'''
import argparse
import os
import re
__lowerCAmelCase = "src/diffusers"
# Pattern that looks at the indentation in a line.
__lowerCAmelCase = re.compile(R"^(\s*)\S")
# Pattern that matches `"key":" and puts `key` in group 0.
__lowerCAmelCase = re.compile(R"^\s*\"([^\"]+)\":")
# Pattern that matches `_import_structure["key"]` and puts `key` in group 0.
__lowerCAmelCase = re.compile(R"^\s*_import_structure\[\"([^\"]+)\"\]")
# Pattern that matches `"key",` and puts `key` in group 0.
__lowerCAmelCase = re.compile(R"^\s*\"([^\"]+)\",\s*$")
# Pattern that matches any `[stuff]` and puts `stuff` in group 0.
__lowerCAmelCase = re.compile(R"\[([^\]]+)\]")
def __UpperCamelCase ( lowercase_ : Any ):
"""simple docstring"""
a_ = _re_indent.search(lowercase_ )
return "" if search is None else search.groups()[0]
def __UpperCamelCase ( lowercase_ : Union[str, Any] , lowercase_ : int="" , lowercase_ : Union[str, Any]=None , lowercase_ : str=None ):
"""simple docstring"""
a_ = 0
a_ = code.split('\n' )
if start_prompt is not None:
while not lines[index].startswith(lowercase_ ):
index += 1
a_ = ['\n'.join(lines[:index] )]
else:
a_ = []
# We split into blocks until we get to the `end_prompt` (or the end of the block).
a_ = [lines[index]]
index += 1
while index < len(lowercase_ ) and (end_prompt is None or not lines[index].startswith(lowercase_ )):
if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level:
if len(lowercase_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ' ' ):
current_block.append(lines[index] )
blocks.append('\n'.join(lowercase_ ) )
if index < len(lowercase_ ) - 1:
a_ = [lines[index + 1]]
index += 1
else:
a_ = []
else:
blocks.append('\n'.join(lowercase_ ) )
a_ = [lines[index]]
else:
current_block.append(lines[index] )
index += 1
# Adds current block if it's nonempty.
if len(lowercase_ ) > 0:
blocks.append('\n'.join(lowercase_ ) )
# Add final block after end_prompt if provided.
if end_prompt is not None and index < len(lowercase_ ):
blocks.append('\n'.join(lines[index:] ) )
return blocks
def __UpperCamelCase ( lowercase_ : Optional[int] ):
"""simple docstring"""
def _inner(lowercase_ : Union[str, Any] ):
return key(lowercase_ ).lower().replace('_' , '' )
return _inner
def __UpperCamelCase ( lowercase_ : List[Any] , lowercase_ : int=None ):
"""simple docstring"""
def noop(lowercase_ : str ):
return x
if key is None:
a_ = noop
# Constants are all uppercase, they go first.
a_ = [obj for obj in objects if key(lowercase_ ).isupper()]
# Classes are not all uppercase but start with a capital, they go second.
a_ = [obj for obj in objects if key(lowercase_ )[0].isupper() and not key(lowercase_ ).isupper()]
# Functions begin with a lowercase, they go last.
a_ = [obj for obj in objects if not key(lowercase_ )[0].isupper()]
a_ = ignore_underscore(lowercase_ )
return sorted(lowercase_ , key=lowercase_ ) + sorted(lowercase_ , key=lowercase_ ) + sorted(lowercase_ , key=lowercase_ )
def __UpperCamelCase ( lowercase_ : Optional[Any] ):
"""simple docstring"""
def _replace(lowercase_ : List[Any] ):
a_ = match.groups()[0]
if "," not in imports:
return F'[{imports}]'
a_ = [part.strip().replace('"' , '' ) for part in imports.split(',' )]
# We will have a final empty element if the line finished with a comma.
if len(keys[-1] ) == 0:
a_ = keys[:-1]
return "[" + ", ".join([F'"{k}"' for k in sort_objects(lowercase_ )] ) + "]"
a_ = import_statement.split('\n' )
if len(lowercase_ ) > 3:
# Here we have to sort internal imports that are on several lines (one per name):
# key: [
# "object1",
# "object2",
# ...
# ]
# We may have to ignore one or two lines on each side.
a_ = 2 if lines[1].strip() == '[' else 1
a_ = [(i, _re_strip_line.search(lowercase_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )]
a_ = sort_objects(lowercase_ , key=lambda lowercase_ : x[1] )
a_ = [lines[x[0] + idx] for x in sorted_indices]
return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] )
elif len(lowercase_ ) == 3:
# Here we have to sort internal imports that are on one separate line:
# key: [
# "object1", "object2", ...
# ]
if _re_bracket_content.search(lines[1] ) is not None:
a_ = _re_bracket_content.sub(_replace , lines[1] )
else:
a_ = [part.strip().replace('"' , '' ) for part in lines[1].split(',' )]
# We will have a final empty element if the line finished with a comma.
if len(keys[-1] ) == 0:
a_ = keys[:-1]
a_ = get_indent(lines[1] ) + ', '.join([F'"{k}"' for k in sort_objects(lowercase_ )] )
return "\n".join(lowercase_ )
else:
# Finally we have to deal with imports fitting on one line
a_ = _re_bracket_content.sub(_replace , lowercase_ )
return import_statement
def __UpperCamelCase ( lowercase_ : Dict , lowercase_ : List[Any]=True ):
"""simple docstring"""
with open(lowercase_ , 'r' ) as f:
a_ = f.read()
if "_import_structure" not in code:
return
# Blocks of indent level 0
a_ = split_code_in_indented_blocks(
lowercase_ , start_prompt='_import_structure = {' , end_prompt='if TYPE_CHECKING:' )
# We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt).
for block_idx in range(1 , len(lowercase_ ) - 1 ):
# Check if the block contains some `_import_structure`s thingy to sort.
a_ = main_blocks[block_idx]
a_ = block.split('\n' )
# Get to the start of the imports.
a_ = 0
while line_idx < len(lowercase_ ) and "_import_structure" not in block_lines[line_idx]:
# Skip dummy import blocks
if "import dummy" in block_lines[line_idx]:
a_ = len(lowercase_ )
else:
line_idx += 1
if line_idx >= len(lowercase_ ):
continue
# Ignore beginning and last line: they don't contain anything.
a_ = '\n'.join(block_lines[line_idx:-1] )
a_ = get_indent(block_lines[1] )
# Slit the internal block into blocks of indent level 1.
a_ = split_code_in_indented_blocks(lowercase_ , indent_level=lowercase_ )
# We have two categories of import key: list or _import_structure[key].append/extend
a_ = _re_direct_key if '_import_structure' in block_lines[0] else _re_indirect_key
# Grab the keys, but there is a trap: some lines are empty or just comments.
a_ = [(pattern.search(lowercase_ ).groups()[0] if pattern.search(lowercase_ ) is not None else None) for b in internal_blocks]
# We only sort the lines with a key.
a_ = [(i, key) for i, key in enumerate(lowercase_ ) if key is not None]
a_ = [x[0] for x in sorted(lowercase_ , key=lambda lowercase_ : x[1] )]
# We reorder the blocks by leaving empty lines/comments as they were and reorder the rest.
a_ = 0
a_ = []
for i in range(len(lowercase_ ) ):
if keys[i] is None:
reordered_blocks.append(internal_blocks[i] )
else:
a_ = sort_objects_in_import(internal_blocks[sorted_indices[count]] )
reordered_blocks.append(lowercase_ )
count += 1
# And we put our main block back together with its first and last line.
a_ = '\n'.join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] )
if code != "\n".join(lowercase_ ):
if check_only:
return True
else:
print(F'Overwriting {file}.' )
with open(lowercase_ , 'w' ) as f:
f.write('\n'.join(lowercase_ ) )
def __UpperCamelCase ( lowercase_ : int=True ):
"""simple docstring"""
a_ = []
for root, _, files in os.walk(lowercase_ ):
if "__init__.py" in files:
a_ = sort_imports(os.path.join(lowercase_ , '__init__.py' ) , check_only=lowercase_ )
if result:
a_ = [os.path.join(lowercase_ , '__init__.py' )]
if len(lowercase_ ) > 0:
raise ValueError(F'Would overwrite {len(lowercase_ )} files, run `make style`.' )
if __name__ == "__main__":
__lowerCAmelCase = argparse.ArgumentParser()
parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.")
__lowerCAmelCase = parser.parse_args()
sort_imports_in_all_inits(check_only=args.check_only)
| 536 | 1 |
'''simple docstring'''
import os
def __UpperCamelCase ( _lowercase = "input.txt" ) -> int:
with open(os.path.join(os.path.dirname(_lowercase ), _lowercase ) ) as input_file:
_lowercase : Optional[Any] = [
[int(_lowercase ) for element in line.split(',' )]
for line in input_file.readlines()
]
_lowercase : Any = len(_lowercase )
_lowercase : Dict = len(matrix[0] )
_lowercase : Tuple = [[-1 for _ in range(_lowercase )] for _ in range(_lowercase )]
for i in range(_lowercase ):
_lowercase : Union[str, Any] = matrix[i][0]
for j in range(1, _lowercase ):
for i in range(_lowercase ):
_lowercase : Tuple = minimal_path_sums[i][j - 1] + matrix[i][j]
for i in range(1, _lowercase ):
_lowercase : List[str] = min(
minimal_path_sums[i][j], minimal_path_sums[i - 1][j] + matrix[i][j] )
for i in range(rows - 2, -1, -1 ):
_lowercase : Optional[Any] = min(
minimal_path_sums[i][j], minimal_path_sums[i + 1][j] + matrix[i][j] )
return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums )
if __name__ == "__main__":
print(F'''{solution() = }''')
| 704 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_A : Dict =logging.get_logger(__name__)
_A : Dict ={
# See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert
}
class lowerCamelCase__ ( A ):
'''simple docstring'''
A_ = """megatron-bert"""
def __init__( self : int , UpperCamelCase_ : int=2_9056 , UpperCamelCase_ : Optional[int]=1024 , UpperCamelCase_ : Optional[Any]=24 , UpperCamelCase_ : List[Any]=16 , UpperCamelCase_ : Optional[int]=4096 , UpperCamelCase_ : Optional[Any]="gelu" , UpperCamelCase_ : List[Any]=0.1 , UpperCamelCase_ : Union[str, Any]=0.1 , UpperCamelCase_ : int=512 , UpperCamelCase_ : Dict=2 , UpperCamelCase_ : Union[str, Any]=0.02 , UpperCamelCase_ : Any=1E-12 , UpperCamelCase_ : Tuple=0 , UpperCamelCase_ : Optional[int]="absolute" , UpperCamelCase_ : Optional[Any]=True , **UpperCamelCase_ : Any , ) -> List[Any]:
'''simple docstring'''
super().__init__(pad_token_id=UpperCamelCase_ , **UpperCamelCase_ )
_lowercase : Dict = vocab_size
_lowercase : Any = hidden_size
_lowercase : Union[str, Any] = num_hidden_layers
_lowercase : Dict = num_attention_heads
_lowercase : Dict = hidden_act
_lowercase : Optional[Any] = intermediate_size
_lowercase : Optional[int] = hidden_dropout_prob
_lowercase : Optional[Any] = attention_probs_dropout_prob
_lowercase : Any = max_position_embeddings
_lowercase : str = type_vocab_size
_lowercase : Optional[Any] = initializer_range
_lowercase : List[str] = layer_norm_eps
_lowercase : List[Any] = position_embedding_type
_lowercase : Optional[Any] = use_cache
| 4 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
UpperCamelCase_ : Tuple = {
'''configuration_clip''': [
'''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''CLIPConfig''',
'''CLIPOnnxConfig''',
'''CLIPTextConfig''',
'''CLIPVisionConfig''',
],
'''processing_clip''': ['''CLIPProcessor'''],
'''tokenization_clip''': ['''CLIPTokenizer'''],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ : List[Any] = ['''CLIPTokenizerFast''']
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ : Tuple = ['''CLIPFeatureExtractor''']
UpperCamelCase_ : Dict = ['''CLIPImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ : Optional[int] = [
'''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''CLIPModel''',
'''CLIPPreTrainedModel''',
'''CLIPTextModel''',
'''CLIPTextModelWithProjection''',
'''CLIPVisionModel''',
'''CLIPVisionModelWithProjection''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ : str = [
'''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFCLIPModel''',
'''TFCLIPPreTrainedModel''',
'''TFCLIPTextModel''',
'''TFCLIPVisionModel''',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ : Any = [
'''FlaxCLIPModel''',
'''FlaxCLIPPreTrainedModel''',
'''FlaxCLIPTextModel''',
'''FlaxCLIPTextPreTrainedModel''',
'''FlaxCLIPVisionModel''',
'''FlaxCLIPVisionPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_clip import (
CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
CLIPConfig,
CLIPOnnxConfig,
CLIPTextConfig,
CLIPVisionConfig,
)
from .processing_clip import CLIPProcessor
from .tokenization_clip import CLIPTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_clip_fast import CLIPTokenizerFast
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_clip import CLIPFeatureExtractor
from .image_processing_clip import CLIPImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_clip import (
CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
CLIPModel,
CLIPPreTrainedModel,
CLIPTextModel,
CLIPTextModelWithProjection,
CLIPVisionModel,
CLIPVisionModelWithProjection,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_clip import (
TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
TFCLIPModel,
TFCLIPPreTrainedModel,
TFCLIPTextModel,
TFCLIPVisionModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_clip import (
FlaxCLIPModel,
FlaxCLIPPreTrainedModel,
FlaxCLIPTextModel,
FlaxCLIPTextPreTrainedModel,
FlaxCLIPVisionModel,
FlaxCLIPVisionPreTrainedModel,
)
else:
import sys
UpperCamelCase_ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 115 |
import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union
import transformers
from transformers.testing_utils import require_tf, require_torch, slow
__A = logging.getLogger()
@unittest.skip('Temporarily disable the doc tests.' )
@require_torch
@require_tf
@slow
class _A ( unittest.TestCase ):
"""simple docstring"""
def _a ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Path , __SCREAMING_SNAKE_CASE : Union[str, None] = None , __SCREAMING_SNAKE_CASE : Union[List[str], None] = None , __SCREAMING_SNAKE_CASE : Union[str, List[str], None] = None , __SCREAMING_SNAKE_CASE : bool = True , ) -> List[str]:
__UpperCAmelCase =[file for file in os.listdir(__SCREAMING_SNAKE_CASE ) if os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) )]
if identifier is not None:
__UpperCAmelCase =[file for file in files if identifier in file]
if n_identifier is not None:
if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
for n_ in n_identifier:
__UpperCAmelCase =[file for file in files if n_ not in file]
else:
__UpperCAmelCase =[file for file in files if n_identifier not in file]
__UpperCAmelCase =ignore_files or []
ignore_files.append("""__init__.py""" )
__UpperCAmelCase =[file for file in files if file not in ignore_files]
for file in files:
# Open all files
print("""Testing""" , __SCREAMING_SNAKE_CASE )
if only_modules:
__UpperCAmelCase =file.split(""".""" )[0]
try:
__UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
__UpperCAmelCase =doctest.DocTestSuite(__SCREAMING_SNAKE_CASE )
__UpperCAmelCase =unittest.TextTestRunner().run(__SCREAMING_SNAKE_CASE )
self.assertIs(len(result.failures ) , 0 )
except AttributeError:
logger.info(f'''{module_identifier} is not a module.''' )
else:
__UpperCAmelCase =doctest.testfile(str("""..""" / directory / file ) , optionflags=doctest.ELLIPSIS )
self.assertIs(result.failed , 0 )
def _a ( self : Optional[Any] ) -> List[str]:
__UpperCAmelCase =Path("""src/transformers""" )
__UpperCAmelCase ="""modeling"""
__UpperCAmelCase =[
"""modeling_ctrl.py""",
"""modeling_tf_ctrl.py""",
]
self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE )
def _a ( self : Tuple ) -> Optional[int]:
__UpperCAmelCase =Path("""src/transformers""" )
__UpperCAmelCase ="""tokenization"""
self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE )
def _a ( self : Optional[Any] ) -> Optional[Any]:
__UpperCAmelCase =Path("""src/transformers""" )
__UpperCAmelCase ="""configuration"""
self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE )
def _a ( self : List[Any] ) -> Tuple:
__UpperCAmelCase =Path("""src/transformers""" )
__UpperCAmelCase =["""configuration""", """modeling""", """tokenization"""]
self.analyze_directory(__SCREAMING_SNAKE_CASE , n_identifier=__SCREAMING_SNAKE_CASE )
def _a ( self : Any ) -> Tuple:
__UpperCAmelCase =Path("""docs/source""" )
__UpperCAmelCase =["""favicon.ico"""]
self.analyze_directory(__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE , only_modules=__SCREAMING_SNAKE_CASE )
| 68 | 0 |
'''simple docstring'''
import numpy as np
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel
from ...utils import logging
_lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__)
class lowerCAmelCase ( SCREAMING_SNAKE_CASE_ ):
_lowerCamelCase : Tuple = CLIPConfig
_lowerCamelCase : List[Any] = ["""CLIPEncoderLayer"""]
def __init__( self , snake_case__ ):
super().__init__(UpperCamelCase__ )
lowerCAmelCase : str = CLIPVisionModelWithProjection(config.vision_config )
lowerCAmelCase : Dict = nn.Linear(config.vision_config.projection_dim , 1 )
lowerCAmelCase : str = nn.Linear(config.vision_config.projection_dim , 1 )
@torch.no_grad()
def lowercase ( self , snake_case__ , snake_case__ , snake_case__=0.5 , snake_case__=0.5 ):
lowerCAmelCase : Optional[Any] = self.vision_model(UpperCamelCase__ )[0]
lowerCAmelCase : int = self.p_head(UpperCamelCase__ )
lowerCAmelCase : int = nsfw_detected.flatten()
lowerCAmelCase : List[Any] = nsfw_detected > p_threshold
lowerCAmelCase : Dict = nsfw_detected.tolist()
if any(UpperCamelCase__ ):
logger.warning(
'Potential NSFW content was detected in one or more images. A black image will be returned instead.'
' Try again with a different prompt and/or seed.' )
for idx, nsfw_detected_ in enumerate(UpperCamelCase__ ):
if nsfw_detected_:
lowerCAmelCase : List[str] = np.zeros(images[idx].shape )
lowerCAmelCase : Union[str, Any] = self.w_head(UpperCamelCase__ )
lowerCAmelCase : List[Any] = watermark_detected.flatten()
lowerCAmelCase : Optional[int] = watermark_detected > w_threshold
lowerCAmelCase : Optional[int] = watermark_detected.tolist()
if any(UpperCamelCase__ ):
logger.warning(
'Potential watermarked content was detected in one or more images. A black image will be returned instead.'
' Try again with a different prompt and/or seed.' )
for idx, watermark_detected_ in enumerate(UpperCamelCase__ ):
if watermark_detected_:
lowerCAmelCase : int = np.zeros(images[idx].shape )
return images, nsfw_detected, watermark_detected | 711 |
'''simple docstring'''
import os
import pytest
import yaml
from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
'files' , [
['full:README.md', 'dataset_infos.json'],
['empty:README.md', 'dataset_infos.json'],
['dataset_infos.json'],
['full:README.md'],
] , )
def __UpperCamelCase ( _A : str , _A : List[Any] ) -> Union[str, Any]:
"""simple docstring"""
lowerCAmelCase : Optional[int] = tmp_path_factory.mktemp('dset_infos_dir' )
if "full:README.md" in files:
with open(dataset_infos_dir / 'README.md' , 'w' ) as f:
f.write('---\ndataset_info:\n dataset_size: 42\n---' )
if "empty:README.md" in files:
with open(dataset_infos_dir / 'README.md' , 'w' ) as f:
f.write('' )
# we want to support dataset_infos.json for backward compatibility
if "dataset_infos.json" in files:
with open(dataset_infos_dir / 'dataset_infos.json' , 'w' ) as f:
f.write('{"default": {"dataset_size": 42}}' )
lowerCAmelCase : Union[str, Any] = DatasetInfosDict.from_directory(_A )
assert dataset_infos
assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
'dataset_info' , [
DatasetInfo(),
DatasetInfo(
description='foo' , features=Features({'a': Value('int32' )} ) , builder_name='builder' , config_name='config' , version='1.0.0' , splits=[{'name': 'train'}] , download_size=42 , ),
] , )
def __UpperCamelCase ( _A : str , _A : DatasetInfo ) -> Optional[int]:
"""simple docstring"""
lowerCAmelCase : str = str(_A )
dataset_info.write_to_directory(_A )
lowerCAmelCase : List[str] = DatasetInfo.from_directory(_A )
assert dataset_info == reloaded
assert os.path.exists(os.path.join(_A , 'dataset_info.json' ) )
def __UpperCamelCase ( ) -> List[str]:
"""simple docstring"""
lowerCAmelCase : Tuple = DatasetInfo(
description='foo' , citation='bar' , homepage='https://foo.bar' , license='CC0' , features=Features({'a': Value('int32' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='builder' , config_name='config' , version='1.0.0' , splits=[{'name': 'train', 'num_examples': 42}] , download_checksums={} , download_size=13_37 , post_processing_size=4_42 , dataset_size=12_34 , size_in_bytes=13_37 + 4_42 + 12_34 , )
lowerCAmelCase : Optional[int] = dataset_info._to_yaml_dict()
assert sorted(_A ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML )
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
assert key in dataset_info_yaml_dict
assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) )
lowerCAmelCase : Any = yaml.safe_dump(_A )
lowerCAmelCase : int = yaml.safe_load(_A )
assert dataset_info_yaml_dict == reloaded
def __UpperCamelCase ( ) -> Dict:
"""simple docstring"""
lowerCAmelCase : Union[str, Any] = DatasetInfo()
lowerCAmelCase : List[Any] = dataset_info._to_yaml_dict()
assert dataset_info_yaml_dict == {}
@pytest.mark.parametrize(
'dataset_infos_dict' , [
DatasetInfosDict(),
DatasetInfosDict({'default': DatasetInfo()} ),
DatasetInfosDict({'my_config_name': DatasetInfo()} ),
DatasetInfosDict(
{
'default': DatasetInfo(
description='foo' , features=Features({'a': Value('int32' )} ) , builder_name='builder' , config_name='config' , version='1.0.0' , splits=[{'name': 'train'}] , download_size=42 , )
} ),
DatasetInfosDict(
{
'v1': DatasetInfo(dataset_size=42 ),
'v2': DatasetInfo(dataset_size=13_37 ),
} ),
] , )
def __UpperCamelCase ( _A : Tuple , _A : DatasetInfosDict ) -> List[Any]:
"""simple docstring"""
lowerCAmelCase : Tuple = str(_A )
dataset_infos_dict.write_to_directory(_A )
lowerCAmelCase : List[str] = DatasetInfosDict.from_directory(_A )
# the config_name of the dataset_infos_dict take over the attribute
for config_name, dataset_info in dataset_infos_dict.items():
lowerCAmelCase : Tuple = config_name
# the yaml representation doesn't include fields like description or citation
# so we just test that we can recover what we can from the yaml
lowerCAmelCase : Optional[Any] = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() )
assert dataset_infos_dict == reloaded
if dataset_infos_dict:
assert os.path.exists(os.path.join(_A , 'README.md' ) )
| 646 | 0 |
'''simple docstring'''
def _UpperCAmelCase ( _lowerCamelCase : int , _lowerCamelCase : float , _lowerCamelCase : float ) -> float:
return round(float(moles / volume ) * nfactor )
def _UpperCAmelCase ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ) -> float:
return round(float((moles * 0.0821 * temperature) / (volume) ) )
def _UpperCAmelCase ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ) -> float:
return round(float((moles * 0.0821 * temperature) / (pressure) ) )
def _UpperCAmelCase ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ) -> float:
return round(float((pressure * volume) / (0.0821 * moles) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 384 |
'''simple docstring'''
import inspect
import logging
import os
import random
import shutil
import tempfile
import unittest
import pytest
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_cuda
from accelerate.utils import ProjectConfiguration, set_seed
UpperCamelCase_ = logging.getLogger(__name__)
def _UpperCAmelCase ( _lowerCamelCase : str=2 , _lowerCamelCase : Union[str, Any]=3 , _lowerCamelCase : List[str]=16 , _lowerCamelCase : int = 10 , _lowerCamelCase : int = 2 ) -> Optional[int]:
def get_dataset(_lowerCamelCase : Union[str, Any] ):
_lowerCAmelCase : Tuple = torch.randn(batch_size * n_batches , 1 )
return TensorDataset(_lowerCamelCase , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) )
_lowerCAmelCase : str = get_dataset(_lowerCamelCase )
_lowerCAmelCase : Optional[int] = get_dataset(_lowerCamelCase )
_lowerCAmelCase : int = DataLoader(_lowerCamelCase , shuffle=_lowerCamelCase , batch_size=_lowerCamelCase , num_workers=4 )
_lowerCAmelCase : str = DataLoader(_lowerCamelCase , shuffle=_lowerCamelCase , batch_size=_lowerCamelCase , num_workers=4 )
return (train_dataloader, valid_dataloader)
def _UpperCAmelCase ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : str , _lowerCamelCase : Optional[int] , _lowerCamelCase : Any , _lowerCamelCase : str , _lowerCamelCase : Any=None ) -> List[str]:
_lowerCAmelCase : List[Any] = []
for epoch in range(_lowerCamelCase ):
# Train quickly
model.train()
for batch in dataloader:
_lowerCAmelCase , _lowerCAmelCase : Dict = batch
_lowerCAmelCase : List[str] = model(_lowerCamelCase )
_lowerCAmelCase : Optional[int] = torch.nn.functional.mse_loss(_lowerCamelCase , _lowerCamelCase )
accelerator.backward(_lowerCamelCase )
optimizer.step()
optimizer.zero_grad()
rands.append(random.random() ) # Introduce some randomness
if scheduler is not None:
scheduler.step()
return rands
class a_ (nn.Module ):
def __init__( self ):
super().__init__()
_lowerCAmelCase : str = nn.Parameter(torch.randn(1 ) )
_lowerCAmelCase : Optional[int] = nn.Parameter(torch.randn(1 ) )
def __UpperCamelCase ( self , snake_case_ ):
return x * self.a + self.b
class a_ (unittest.TestCase ):
def __UpperCamelCase ( self ):
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(4_2 )
_lowerCAmelCase : Tuple = DummyModel()
_lowerCAmelCase : int = torch.optim.Adam(params=model.parameters() , lr=1E-3 )
_lowerCAmelCase , _lowerCAmelCase : Optional[Any] = dummy_dataloaders()
_lowerCAmelCase : Union[str, Any] = ProjectConfiguration(total_limit=1 , project_dir=snake_case_ , automatic_checkpoint_naming=snake_case_ )
# Train baseline
_lowerCAmelCase : List[Any] = Accelerator(project_config=snake_case_ )
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : List[str] = accelerator.prepare(
snake_case_ , snake_case_ , snake_case_ , snake_case_ )
# Save initial
accelerator.save_state()
# Save second state
accelerator.save_state()
self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 )
def __UpperCamelCase ( self ):
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(4_2 )
_lowerCAmelCase : int = DummyModel()
_lowerCAmelCase : List[str] = torch.optim.Adam(params=model.parameters() , lr=1E-3 )
_lowerCAmelCase , _lowerCAmelCase : str = dummy_dataloaders()
# Train baseline
_lowerCAmelCase : Tuple = Accelerator()
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Tuple = accelerator.prepare(
snake_case_ , snake_case_ , snake_case_ , snake_case_ )
# Save initial
_lowerCAmelCase : Union[str, Any] = os.path.join(snake_case_ , """initial""" )
accelerator.save_state(snake_case_ )
((_lowerCAmelCase) , (_lowerCAmelCase)) : List[Any] = model.a.item(), model.b.item()
_lowerCAmelCase : Dict = optimizer.state_dict()
_lowerCAmelCase : Optional[int] = train(3 , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
((_lowerCAmelCase) , (_lowerCAmelCase)) : Optional[Any] = model.a.item(), model.b.item()
_lowerCAmelCase : Optional[int] = optimizer.state_dict()
# Train partially
set_seed(4_2 )
_lowerCAmelCase : List[str] = DummyModel()
_lowerCAmelCase : str = torch.optim.Adam(params=model.parameters() , lr=1E-3 )
_lowerCAmelCase , _lowerCAmelCase : Dict = dummy_dataloaders()
_lowerCAmelCase : Optional[Any] = Accelerator()
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Tuple = accelerator.prepare(
snake_case_ , snake_case_ , snake_case_ , snake_case_ )
accelerator.load_state(snake_case_ )
((_lowerCAmelCase) , (_lowerCAmelCase)) : Optional[Any] = model.a.item(), model.b.item()
_lowerCAmelCase : Optional[int] = optimizer.state_dict()
self.assertEqual(snake_case_ , snake_case_ )
self.assertEqual(snake_case_ , snake_case_ )
self.assertEqual(snake_case_ , snake_case_ )
_lowerCAmelCase : Any = train(2 , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
# Save everything
_lowerCAmelCase : str = os.path.join(snake_case_ , """checkpoint""" )
accelerator.save_state(snake_case_ )
# Load everything back in and make sure all states work
accelerator.load_state(snake_case_ )
test_rands += train(1 , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
((_lowerCAmelCase) , (_lowerCAmelCase)) : str = model.a.item(), model.b.item()
_lowerCAmelCase : Any = optimizer.state_dict()
self.assertEqual(snake_case_ , snake_case_ )
self.assertEqual(snake_case_ , snake_case_ )
self.assertEqual(snake_case_ , snake_case_ )
self.assertEqual(snake_case_ , snake_case_ )
def __UpperCamelCase ( self ):
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(4_2 )
_lowerCAmelCase : str = DummyModel()
_lowerCAmelCase : int = torch.optim.Adam(params=model.parameters() , lr=1E-3 )
_lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = dummy_dataloaders()
_lowerCAmelCase : Union[str, Any] = ProjectConfiguration(automatic_checkpoint_naming=snake_case_ )
# Train baseline
_lowerCAmelCase : List[Any] = Accelerator(project_dir=snake_case_ , project_config=snake_case_ )
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : List[Any] = accelerator.prepare(
snake_case_ , snake_case_ , snake_case_ , snake_case_ )
# Save initial
accelerator.save_state()
((_lowerCAmelCase) , (_lowerCAmelCase)) : Dict = model.a.item(), model.b.item()
_lowerCAmelCase : List[Any] = optimizer.state_dict()
_lowerCAmelCase : Optional[Any] = train(3 , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
((_lowerCAmelCase) , (_lowerCAmelCase)) : Dict = model.a.item(), model.b.item()
_lowerCAmelCase : str = optimizer.state_dict()
# Train partially
set_seed(4_2 )
_lowerCAmelCase : List[str] = DummyModel()
_lowerCAmelCase : Tuple = torch.optim.Adam(params=model.parameters() , lr=1E-3 )
_lowerCAmelCase , _lowerCAmelCase : Optional[Any] = dummy_dataloaders()
_lowerCAmelCase : List[str] = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=snake_case_ )
_lowerCAmelCase : Optional[int] = Accelerator(project_dir=snake_case_ , project_config=snake_case_ )
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = accelerator.prepare(
snake_case_ , snake_case_ , snake_case_ , snake_case_ )
accelerator.load_state(os.path.join(snake_case_ , """checkpoints""" , """checkpoint_0""" ) )
((_lowerCAmelCase) , (_lowerCAmelCase)) : Optional[Any] = model.a.item(), model.b.item()
_lowerCAmelCase : Union[str, Any] = optimizer.state_dict()
self.assertEqual(snake_case_ , snake_case_ )
self.assertEqual(snake_case_ , snake_case_ )
self.assertEqual(snake_case_ , snake_case_ )
_lowerCAmelCase : Optional[int] = train(2 , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
# Save everything
accelerator.save_state()
# Load everything back in and make sure all states work
accelerator.load_state(os.path.join(snake_case_ , """checkpoints""" , """checkpoint_1""" ) )
test_rands += train(1 , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
((_lowerCAmelCase) , (_lowerCAmelCase)) : Optional[int] = model.a.item(), model.b.item()
_lowerCAmelCase : str = optimizer.state_dict()
self.assertEqual(snake_case_ , snake_case_ )
self.assertEqual(snake_case_ , snake_case_ )
self.assertEqual(snake_case_ , snake_case_ )
self.assertEqual(snake_case_ , snake_case_ )
def __UpperCamelCase ( self ):
_lowerCAmelCase : Optional[int] = torch.tensor([1, 2, 3] )
_lowerCAmelCase : Optional[Any] = torch.tensor([2, 3, 4] )
_lowerCAmelCase : Union[str, Any] = DummyModel()
_lowerCAmelCase : Tuple = torch.optim.Adam(net.parameters() )
_lowerCAmelCase : str = Accelerator()
with self.assertRaises(snake_case_ ) as ve:
accelerator.register_for_checkpointing(snake_case_ , snake_case_ , snake_case_ , snake_case_ )
_lowerCAmelCase : str = str(ve.exception )
self.assertTrue("""Item at index 0""" in message )
self.assertTrue("""Item at index 1""" in message )
self.assertFalse("""Item at index 2""" in message )
self.assertFalse("""Item at index 3""" in message )
def __UpperCamelCase ( self ):
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(4_2 )
_lowerCAmelCase : List[str] = DummyModel()
_lowerCAmelCase : List[str] = torch.optim.Adam(params=model.parameters() , lr=1E-3 )
_lowerCAmelCase : Tuple = torch.optim.lr_scheduler.StepLR(snake_case_ , step_size=1 , gamma=0.99 )
_lowerCAmelCase , _lowerCAmelCase : int = dummy_dataloaders()
_lowerCAmelCase : Dict = ProjectConfiguration(automatic_checkpoint_naming=snake_case_ )
# Train baseline
_lowerCAmelCase : int = Accelerator(project_dir=snake_case_ , project_config=snake_case_ )
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Any = accelerator.prepare(
snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
# Save initial
accelerator.save_state()
_lowerCAmelCase : Union[str, Any] = scheduler.state_dict()
train(3 , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
self.assertNotEqual(snake_case_ , scheduler.state_dict() )
# Load everything back in and make sure all states work
accelerator.load_state(os.path.join(snake_case_ , """checkpoints""" , """checkpoint_0""" ) )
self.assertEqual(snake_case_ , scheduler.state_dict() )
def __UpperCamelCase ( self ):
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(4_2 )
_lowerCAmelCase : str = DummyModel()
_lowerCAmelCase : Optional[int] = ProjectConfiguration(automatic_checkpoint_naming=snake_case_ , total_limit=2 )
# Train baseline
_lowerCAmelCase : Optional[Any] = Accelerator(project_dir=snake_case_ , project_config=snake_case_ )
_lowerCAmelCase : Any = accelerator.prepare(snake_case_ )
# Save 3 states:
for _ in range(1_1 ):
accelerator.save_state()
self.assertTrue(not os.path.exists(os.path.join(snake_case_ , """checkpoints""" , """checkpoint_0""" ) ) )
self.assertTrue(os.path.exists(os.path.join(snake_case_ , """checkpoints""" , """checkpoint_9""" ) ) )
self.assertTrue(os.path.exists(os.path.join(snake_case_ , """checkpoints""" , """checkpoint_10""" ) ) )
@require_cuda
def __UpperCamelCase ( self ):
_lowerCAmelCase : Dict = ["""torchrun""", f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )]
execute_subprocess_async(snake_case_ , env=os.environ.copy() )
if __name__ == "__main__":
UpperCamelCase_ = """/tmp/accelerate/state_checkpointing"""
UpperCamelCase_ = DummyModel()
UpperCamelCase_ = torch.optim.Adam(params=model.parameters(), lr=1e-3)
UpperCamelCase_ = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.9_9)
UpperCamelCase_ , UpperCamelCase_ = dummy_dataloaders()
UpperCamelCase_ = ProjectConfiguration(automatic_checkpoint_naming=True)
# Train baseline
UpperCamelCase_ = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision="""no""")
if accelerator.process_index == 0:
if os.path.exists(savedir):
shutil.rmtree(savedir)
os.makedirs(savedir)
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = accelerator.prepare(
model, optimizer, train_dataloader, valid_dataloader, scheduler
)
UpperCamelCase_ , UpperCamelCase_ = accelerator.prepare(model, optimizer)
train(3, model, train_dataloader, optimizer, accelerator, scheduler)
# Check that the intial optimizer is loaded on the GPU
for group in optimizer.param_groups:
UpperCamelCase_ = group["""params"""][0].device
break
assert param_device.type == accelerator.device.type
UpperCamelCase_ = model.cpu()
accelerator.wait_for_everyone()
accelerator.save_state()
accelerator.wait_for_everyone()
# Check CPU state
accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""cpu""")
for group in optimizer.param_groups:
UpperCamelCase_ = group["""params"""][0].device
break
assert (
param_device.type == torch.device("""cpu""").type
), F"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"
# Check device state
model.to(accelerator.device)
accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""on_device""")
for group in optimizer.param_groups:
UpperCamelCase_ = group["""params"""][0].device
break
assert (
param_device.type == accelerator.device.type
), F"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"
# Check error
with pytest.raises(TypeError, match="""Unsupported optimizer map location passed"""):
accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""invalid""")
accelerator.wait_for_everyone()
if accelerator.process_index == 0:
shutil.rmtree(savedir)
accelerator.wait_for_everyone()
| 384 | 1 |
"""simple docstring"""
import tempfile
import unittest
from transformers import TaConfig, is_torch_available
from transformers.testing_utils import (
require_sentencepiece,
require_tokenizers,
require_torch,
slow,
torch_device,
)
from ...generation.test_utils import GenerationTesterMixin
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel
class __lowercase :
'''simple docstring'''
def __init__( self : Tuple ,A_ : Optional[int] ,A_ : Tuple=99 ,A_ : Any=13 ,A_ : List[str]=7 ,A_ : Any=9 ,A_ : Optional[int]=True ,A_ : Tuple=True ,A_ : List[Any]=False ,A_ : List[str]=32 ,A_ : List[Any]=5 ,A_ : Tuple=4 ,A_ : Optional[int]=37 ,A_ : List[str]=8 ,A_ : List[Any]=0.1 ,A_ : List[Any]=0.0_02 ,A_ : List[Any]=1 ,A_ : int=0 ,A_ : Optional[int]=0 ,A_ : Tuple=None ,A_ : Any=None ,) -> Union[str, Any]:
A = parent
A = batch_size
A = encoder_seq_length
A = decoder_seq_length
# For common tests
A = self.decoder_seq_length
A = is_training
A = use_attention_mask
A = use_labels
A = vocab_size
A = hidden_size
A = num_hidden_layers
A = num_attention_heads
A = d_ff
A = relative_attention_num_buckets
A = dropout_rate
A = initializer_factor
A = eos_token_id
A = pad_token_id
A = decoder_start_token_id
A = None
A = decoder_layers
def _SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]:
return TaConfig.from_pretrained('google/umt5-base' )
def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : List[Any] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Any=None ,A_ : Dict=None ,A_ : List[Any]=None ,A_ : int=None ,A_ : List[str]=None ,) -> Optional[Any]:
if attention_mask is None:
A = input_ids.ne(config.pad_token_id )
if decoder_attention_mask is None:
A = decoder_input_ids.ne(config.pad_token_id )
if head_mask is None:
A = torch.ones(config.num_hidden_layers ,config.num_attention_heads ,device=A_ )
if decoder_head_mask is None:
A = torch.ones(config.num_decoder_layers ,config.num_attention_heads ,device=A_ )
if cross_attn_head_mask is None:
A = torch.ones(
config.num_decoder_layers ,config.num_attention_heads ,device=A_ )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple:
A = ids_tensor([self.batch_size, self.encoder_seq_length] ,self.vocab_size )
A = ids_tensor([self.batch_size, self.decoder_seq_length] ,self.vocab_size )
# we need to clamp the input ids here to avoid having pad token in between
# this is because for NllbMoe the position_ids are prepared such that
# all pad tokens have pos id = 2 and rest are between 2..seq_length
# and the seq_length here is seq_length - num_pad_tokens
# but when using past, there is no way of knowing if the past input ids had
# pad tokens in them, which results in incorrect seq_lenth and which in turn results in
# position_ids being off by num_pad_tokens in past input
A = input_ids.clamp(self.pad_token_id + 1 )
A = decoder_input_ids.clamp(self.pad_token_id + 1 )
A = self.get_config()
A = config.num_attention_heads
A = self.prepare_inputs_dict(A_ ,A_ ,A_ )
return config, input_dict
def _SCREAMING_SNAKE_CASE ( self : int ) -> List[str]:
A , A = self.prepare_config_and_inputs()
return config, inputs_dict
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]:
return TaConfig(
vocab_size=166 ,d_model=self.hidden_size ,d_ff=self.d_ff ,d_kv=self.hidden_size // self.num_attention_heads ,num_layers=self.num_hidden_layers ,num_decoder_layers=self.decoder_layers ,num_heads=self.num_attention_heads ,relative_attention_num_buckets=self.relative_attention_num_buckets ,dropout_rate=self.dropout_rate ,initializer_factor=self.initializer_factor ,eos_token_id=self.eos_token_id ,bos_token_id=self.pad_token_id ,pad_token_id=self.pad_token_id ,decoder_start_token_id=self.decoder_start_token_id ,)
def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple:
return TaConfig(
vocab_size=self.vocab_size ,d_model=self.hidden_size ,d_ff=self.d_ff ,d_kv=self.hidden_size // self.num_attention_heads ,num_layers=self.num_hidden_layers ,num_decoder_layers=self.decoder_layers ,num_heads=self.num_attention_heads ,relative_attention_num_buckets=self.relative_attention_num_buckets ,dropout_rate=self.dropout_rate ,initializer_factor=self.initializer_factor ,eos_token_id=self.eos_token_id ,bos_token_id=self.pad_token_id ,pad_token_id=self.pad_token_id ,decoder_start_token_id=self.decoder_start_token_id ,)
def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : int ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[Any] ,A_ : int ,A_ : Dict ,) -> Any:
A = UMTaModel(config=A_ )
model.to(A_ )
model.eval()
A = model(
input_ids=A_ ,decoder_input_ids=A_ ,attention_mask=A_ ,decoder_attention_mask=A_ ,)
A = model(input_ids=A_ ,decoder_input_ids=A_ )
A = result.last_hidden_state
A = result.past_key_values
A = result.encoder_last_hidden_state
self.parent.assertEqual(encoder_output.size() ,(self.batch_size, self.encoder_seq_length, self.hidden_size) )
self.parent.assertEqual(decoder_output.size() ,(self.batch_size, self.decoder_seq_length, self.hidden_size) )
# There should be `num_layers` key value embeddings stored in decoder_past
self.parent.assertEqual(len(A_ ) ,config.num_layers )
# There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple
self.parent.assertEqual(len(decoder_past[0] ) ,4 )
def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : List[Any] ,A_ : List[str] ,A_ : str ,A_ : List[str] ,A_ : Tuple ,A_ : Union[str, Any] ,) -> Tuple:
A = UMTaModel(config=A_ ).get_decoder().to(A_ ).eval()
# first forward pass
A = model(A_ ,use_cache=A_ )
A = model(A_ )
A = model(A_ ,use_cache=A_ )
self.parent.assertTrue(len(A_ ) == len(A_ ) )
self.parent.assertTrue(len(A_ ) == len(A_ ) + 1 )
A , A = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
A = ids_tensor((self.batch_size, 1) ,config.vocab_size )
# append to next input_ids and
A = torch.cat([input_ids, next_tokens] ,dim=-1 )
A = model(A_ )['last_hidden_state']
A = model(A_ ,past_key_values=A_ )['last_hidden_state']
# select random slice
A = ids_tensor((1,) ,output_from_past.shape[-1] ).item()
A = output_from_no_past[:, -1, random_slice_idx].detach()
A = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(A_ ,A_ ,atol=1e-3 ) )
def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Tuple ,A_ : str ,) -> Optional[Any]:
A = UMTaModel(config=A_ ).to(A_ ).half().eval()
A = model(**A_ )['last_hidden_state']
self.parent.assertFalse(torch.isnan(A_ ).any().item() )
@require_torch
class __lowercase ( _lowercase , _lowercase , _lowercase , unittest.TestCase ):
'''simple docstring'''
_lowerCamelCase: int = (
(UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else ()
)
_lowerCamelCase: Optional[int] = (UMTaForConditionalGeneration,) if is_torch_available() else ()
_lowerCamelCase: List[str] = (
{
'''conversational''': UMTaForConditionalGeneration,
'''feature-extraction''': UMTaModel,
'''summarization''': UMTaForConditionalGeneration,
'''text2text-generation''': UMTaForConditionalGeneration,
'''translation''': UMTaForConditionalGeneration,
'''question-answering''': UMTaForQuestionAnswering,
}
if is_torch_available()
else {}
)
_lowerCamelCase: str = True
_lowerCamelCase: List[str] = False
_lowerCamelCase: str = False
_lowerCamelCase: Optional[int] = True
_lowerCamelCase: Optional[Any] = True
# The small UMT5 model needs higher percentages for CPU/MP tests
_lowerCamelCase: Tuple = [0.8, 0.9]
def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any:
A = UMTaModelTester(self )
@unittest.skip('Test has a segmentation fault on torch 1.8.0' )
def _SCREAMING_SNAKE_CASE ( self : str ) -> int:
A = self.model_tester.prepare_config_and_inputs()
A = UMTaModel(config_and_inputs[0] ).to(A_ )
with tempfile.TemporaryDirectory() as tmpdirname:
torch.onnx.export(
A_ ,(config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) ,F'{tmpdirname}/t5_test.onnx' ,export_params=A_ ,opset_version=9 ,input_names=['input_ids', 'decoder_input_ids'] ,)
@unittest.skipIf(torch_device == 'cpu' ,'Cant do half precision' )
def _SCREAMING_SNAKE_CASE ( self : int ) -> Union[str, Any]:
A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model_fpaa_forward(*A_ )
def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]:
A = ['encoder_attentions', 'decoder_attentions', 'cross_attentions']
A = self.model_tester.prepare_config_and_inputs()
A = config_and_inputs[0]
A = UMTaForConditionalGeneration(A_ ).eval()
model.to(A_ )
A = {
'head_mask': torch.zeros(config.num_layers ,config.num_heads ,device=A_ ),
'decoder_head_mask': torch.zeros(config.num_decoder_layers ,config.num_heads ,device=A_ ),
'cross_attn_head_mask': torch.zeros(config.num_decoder_layers ,config.num_heads ,device=A_ ),
}
for attn_name, (name, mask) in zip(A_ ,head_masking.items() ):
A = {name: mask}
# Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified
if name == "head_mask":
A = torch.ones(
config.num_decoder_layers ,config.num_heads ,device=A_ )
A = model.generate(
config_and_inputs[1]['input_ids'] ,num_beams=1 ,max_length=3 ,output_attentions=A_ ,return_dict_in_generate=A_ ,**A_ ,)
# We check the state of decoder_attentions and cross_attentions just from the last step
A = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1]
self.assertEqual(sum([w.sum().item() for w in attn_weights] ) ,0.0 )
@unittest.skip('Does not work on the tiny model as we keep hitting edge cases.' )
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str:
pass
@require_torch
@require_sentencepiece
@require_tokenizers
class __lowercase ( unittest.TestCase ):
'''simple docstring'''
@slow
@unittest.skip(
'Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged' )
def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict:
A = UMTaForConditionalGeneration.from_pretrained('google/umt5-small' ,return_dict=A_ ).to(A_ )
A = AutoTokenizer.from_pretrained('google/umt5-small' ,use_fast=A_ ,legacy=A_ )
A = [
'Bonjour monsieur <extra_id_0> bien <extra_id_1>.',
'No se como puedo <extra_id_0>.',
'This is the reason why we <extra_id_0> them.',
'The <extra_id_0> walks in <extra_id_1>, seats',
'A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.',
]
A = tokenizer(A_ ,return_tensors='pt' ,padding=A_ ).input_ids
# fmt: off
A = torch.tensor(
[
[ 3_8530, 21_0703, 25_6299, 1410, 25_6298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0],
[ 826, 321, 671, 2_5922, 25_6299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0],
[ 1460, 339, 312, 1_9014, 1_0620, 758, 25_6299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0],
[ 517, 25_6299, 1_4869, 281, 301, 25_6298, 275, 11_9983,1, 0, 0, 0, 0, 0, 0, 0,0, 0],
[ 320, 25_6299, 1_4869, 281, 2234, 289, 2275, 333,6_1391, 289, 25_6298, 543, 25_6297, 16_8714, 329, 25_6296,274, 1],
] )
# fmt: on
torch.testing.assert_allclose(A_ ,A_ )
A = model.generate(input_ids.to(A_ ) )
A = [
'<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>',
'<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>',
'<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>',
'<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>',
'<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>',
]
A = tokenizer.batch_decode(A_ )
self.assertEqual(A_ ,A_ ) | 721 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
_lowercase = {
'''configuration_clip''': [
'''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''CLIPConfig''',
'''CLIPOnnxConfig''',
'''CLIPTextConfig''',
'''CLIPVisionConfig''',
],
'''processing_clip''': ['''CLIPProcessor'''],
'''tokenization_clip''': ['''CLIPTokenizer'''],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = ['''CLIPTokenizerFast''']
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = ['''CLIPFeatureExtractor''']
_lowercase = ['''CLIPImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''CLIPModel''',
'''CLIPPreTrainedModel''',
'''CLIPTextModel''',
'''CLIPTextModelWithProjection''',
'''CLIPVisionModel''',
'''CLIPVisionModelWithProjection''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFCLIPModel''',
'''TFCLIPPreTrainedModel''',
'''TFCLIPTextModel''',
'''TFCLIPVisionModel''',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''FlaxCLIPModel''',
'''FlaxCLIPPreTrainedModel''',
'''FlaxCLIPTextModel''',
'''FlaxCLIPTextPreTrainedModel''',
'''FlaxCLIPVisionModel''',
'''FlaxCLIPVisionPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_clip import (
CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
CLIPConfig,
CLIPOnnxConfig,
CLIPTextConfig,
CLIPVisionConfig,
)
from .processing_clip import CLIPProcessor
from .tokenization_clip import CLIPTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_clip_fast import CLIPTokenizerFast
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_clip import CLIPFeatureExtractor
from .image_processing_clip import CLIPImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_clip import (
CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
CLIPModel,
CLIPPreTrainedModel,
CLIPTextModel,
CLIPTextModelWithProjection,
CLIPVisionModel,
CLIPVisionModelWithProjection,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_clip import (
TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
TFCLIPModel,
TFCLIPPreTrainedModel,
TFCLIPTextModel,
TFCLIPVisionModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_clip import (
FlaxCLIPModel,
FlaxCLIPPreTrainedModel,
FlaxCLIPTextModel,
FlaxCLIPTextPreTrainedModel,
FlaxCLIPVisionModel,
FlaxCLIPVisionPreTrainedModel,
)
else:
import sys
_lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 22 | 0 |
'''simple docstring'''
import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union
import transformers
from transformers.testing_utils import require_tf, require_torch, slow
SCREAMING_SNAKE_CASE_ = logging.getLogger()
@unittest.skip('''Temporarily disable the doc tests.''' )
@require_torch
@require_tf
@slow
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def __UpperCAmelCase ( self : Optional[Any] , snake_case : Path , snake_case : Union[str, None] = None , snake_case : Union[List[str], None] = None , snake_case : Union[str, List[str], None] = None , snake_case : bool = True , ):
"""simple docstring"""
_snake_case : Dict = [file for file in os.listdir(snake_case ) if os.path.isfile(os.path.join(snake_case , snake_case ) )]
if identifier is not None:
_snake_case : int = [file for file in files if identifier in file]
if n_identifier is not None:
if isinstance(snake_case , snake_case ):
for n_ in n_identifier:
_snake_case : str = [file for file in files if n_ not in file]
else:
_snake_case : List[Any] = [file for file in files if n_identifier not in file]
_snake_case : str = ignore_files or []
ignore_files.append('__init__.py' )
_snake_case : Optional[Any] = [file for file in files if file not in ignore_files]
for file in files:
# Open all files
print('Testing' , snake_case )
if only_modules:
_snake_case : Tuple = file.split('.' )[0]
try:
_snake_case : str = getattr(snake_case , snake_case )
_snake_case : Union[str, Any] = doctest.DocTestSuite(snake_case )
_snake_case : Dict = unittest.TextTestRunner().run(snake_case )
self.assertIs(len(result.failures ) , 0 )
except AttributeError:
logger.info(F"""{module_identifier} is not a module.""" )
else:
_snake_case : Optional[Any] = doctest.testfile(str('..' / directory / file ) , optionflags=doctest.ELLIPSIS )
self.assertIs(result.failed , 0 )
def __UpperCAmelCase ( self : Dict ):
"""simple docstring"""
_snake_case : Optional[int] = Path('src/transformers' )
_snake_case : Tuple = 'modeling'
_snake_case : Dict = [
'modeling_ctrl.py',
'modeling_tf_ctrl.py',
]
self.analyze_directory(snake_case , identifier=snake_case , ignore_files=snake_case )
def __UpperCAmelCase ( self : str ):
"""simple docstring"""
_snake_case : List[str] = Path('src/transformers' )
_snake_case : str = 'tokenization'
self.analyze_directory(snake_case , identifier=snake_case )
def __UpperCAmelCase ( self : Tuple ):
"""simple docstring"""
_snake_case : int = Path('src/transformers' )
_snake_case : int = 'configuration'
self.analyze_directory(snake_case , identifier=snake_case )
def __UpperCAmelCase ( self : List[str] ):
"""simple docstring"""
_snake_case : Optional[int] = Path('src/transformers' )
_snake_case : Union[str, Any] = ['configuration', 'modeling', 'tokenization']
self.analyze_directory(snake_case , n_identifier=snake_case )
def __UpperCAmelCase ( self : Union[str, Any] ):
"""simple docstring"""
_snake_case : Tuple = Path('docs/source' )
_snake_case : Any = ['favicon.ico']
self.analyze_directory(snake_case , ignore_files=snake_case , only_modules=snake_case )
| 517 |
'''simple docstring'''
import collections
import json
import os
import re
from typing import TYPE_CHECKING, List, Optional, Tuple
import numpy as np
from ...tokenization_utils_fast import PreTrainedTokenizer
from ...utils import logging
if TYPE_CHECKING:
from transformers.pipelines.conversational import Conversation
SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE_ = {"vocab_file": "vocab.txt", "emoji_file": "emoji.json"}
SCREAMING_SNAKE_CASE_ = {
"vocab_file": {
"abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt",
},
"emoji_file": {
"abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json",
},
}
SCREAMING_SNAKE_CASE_ = {
"abeja/gpt-neox-japanese-2.7b": 2_048,
}
def lowerCamelCase__ ( a__ , a__) -> List[str]:
"""simple docstring"""
with open(a__ , 'r' , encoding='utf-8') as f:
_snake_case : Union[str, Any] = json.loads(f.read())
_snake_case : List[Any] = collections.OrderedDict()
_snake_case : str = collections.OrderedDict()
_snake_case : Union[str, Any] = collections.OrderedDict()
with open(a__ , 'r' , encoding='utf-8') as f:
_snake_case : Tuple = f.readlines()
_snake_case : Optional[Any] = [[t.rstrip('\n')] if (t == ',' or ',' not in t) else t.rstrip('\n').split(',') for t in token]
for idx, b in enumerate(a__):
_snake_case : Optional[int] = b
_snake_case : Optional[Any] = idx
for wd in b:
_snake_case : Tuple = idx
return vocab, raw_vocab, ids_to_tokens, emoji
class SCREAMING_SNAKE_CASE ( lowercase_ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : List[str] = VOCAB_FILES_NAMES
SCREAMING_SNAKE_CASE__ : Any = PRETRAINED_VOCAB_FILES_MAP
SCREAMING_SNAKE_CASE__ : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
SCREAMING_SNAKE_CASE__ : Optional[Any] = ['''input_ids''', '''attention_mask''']
def __init__( self : Any , snake_case : str , snake_case : Any , snake_case : str="<|endoftext|>" , snake_case : List[str]="<|endoftext|>" , snake_case : Optional[Any]="<|startoftext|>" , snake_case : str="<|endoftext|>" , snake_case : Any=False , **snake_case : List[Any] , ):
"""simple docstring"""
super().__init__(
unk_token=snake_case , pad_token=snake_case , bos_token=snake_case , eos_token=snake_case , do_clean_text=snake_case , **snake_case , )
if not os.path.isfile(snake_case ):
raise ValueError(
F"""Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"""
' model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`' )
if not os.path.isfile(snake_case ):
raise ValueError(
F"""Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google"""
' pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`' )
_snake_case : Any = do_clean_text
_snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = load_vocab_and_emoji(snake_case , snake_case )
_snake_case : Optional[int] = SubWordJapaneseTokenizer(
vocab=self.vocab , ids_to_tokens=self.ids_to_tokens , emoji=self.emoji )
@property
def __UpperCAmelCase ( self : Optional[int] ):
"""simple docstring"""
return len(self.raw_vocab )
def __UpperCAmelCase ( self : str ):
"""simple docstring"""
return dict(self.raw_vocab , **self.added_tokens_encoder )
def __UpperCAmelCase ( self : Optional[int] , snake_case : Optional[Any] ):
"""simple docstring"""
return self.subword_tokenizer.tokenize(snake_case , clean=self.do_clean_text )
def __UpperCAmelCase ( self : Optional[int] , snake_case : Optional[Any] ):
"""simple docstring"""
return self.vocab.get(snake_case , self.vocab.get(self.unk_token ) )
def __UpperCAmelCase ( self : List[str] , snake_case : Tuple ):
"""simple docstring"""
return self.subword_tokenizer.convert_id_to_token(snake_case )
def __UpperCAmelCase ( self : List[Any] , snake_case : Dict ):
"""simple docstring"""
_snake_case : List[Any] = ''.join(snake_case ).strip()
return out_string
def __UpperCAmelCase ( self : Optional[Any] , snake_case : "Conversation" ):
"""simple docstring"""
_snake_case : Any = []
for is_user, text in conversation.iter_texts():
input_ids.extend(self.encode(snake_case , add_special_tokens=snake_case ) + [self.eos_token_id] )
if len(snake_case ) > self.model_max_length:
_snake_case : Dict = input_ids[-self.model_max_length :]
return input_ids
def __UpperCAmelCase ( self : List[str] , snake_case : str , snake_case : Optional[str] = None ):
"""simple docstring"""
_snake_case : Optional[int] = 0
if os.path.isdir(snake_case ):
_snake_case : List[str] = os.path.join(
snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
_snake_case : List[Any] = os.path.join(
snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['emoji_file'] )
else:
_snake_case : List[Any] = (
(filename_prefix + '-' if filename_prefix else '') + save_directory + VOCAB_FILES_NAMES['vocab_file']
)
_snake_case : List[str] = (
(filename_prefix + '-' if filename_prefix else '') + save_directory + VOCAB_FILES_NAMES['emoji_file']
)
with open(snake_case , 'w' , encoding='utf-8' ) as writer:
for token_index, token in self.ids_to_tokens.items():
if index != token_index:
logger.warning(
F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."""
' Please check that the vocabulary is not corrupted!' )
_snake_case : List[str] = token_index
writer.write(','.join(snake_case ) + '\n' )
index += 1
with open(snake_case , 'w' , encoding='utf-8' ) as writer:
json.dump(self.emoji , snake_case )
return vocab_file, emoji_file
class SCREAMING_SNAKE_CASE ( lowercase_ ):
'''simple docstring'''
def __init__( self : str , snake_case : str , snake_case : List[str] , snake_case : List[str] ):
"""simple docstring"""
_snake_case : List[str] = vocab # same as swe
_snake_case : List[str] = ids_to_tokens # same as bpe
_snake_case : int = emoji
_snake_case : List[str] = np.max([len(snake_case ) for w in self.vocab.keys()] )
_snake_case : Dict = re.compile(r'(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)' )
_snake_case : int = re.compile(r'[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*' )
_snake_case : List[Any] = re.compile(r'[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}' )
_snake_case : List[str] = re.compile(
r'([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*' )
_snake_case : Tuple = re.compile(
r'(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*' )
_snake_case : Union[str, Any] = re.compile(
r'((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*' )
_snake_case : Optional[int] = '─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿'
_snake_case : Dict = '▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟'
_snake_case : Tuple = str.maketrans({k: '<BLOCK>' for k in keisen + blocks} )
def __len__( self : int ):
"""simple docstring"""
return len(self.ids_to_tokens )
def __UpperCAmelCase ( self : Dict , snake_case : List[str] ):
"""simple docstring"""
_snake_case : str = self.content_repattera.sub('<URL>' , snake_case )
_snake_case : List[str] = self.content_repattera.sub('<EMAIL>' , snake_case )
_snake_case : Dict = self.content_repattera.sub('<TEL>' , snake_case )
_snake_case : Optional[int] = self.content_repattera.sub('<DATE>' , snake_case )
_snake_case : Tuple = self.content_repattera.sub('<DATE>' , snake_case )
_snake_case : str = self.content_repattera.sub('<PRICE>' , snake_case )
_snake_case : str = content.translate(self.content_transa )
while "<BLOCK><BLOCK>" in content:
_snake_case : int = content.replace('<BLOCK><BLOCK>' , '<BLOCK>' )
return content
def __UpperCAmelCase ( self : Any , snake_case : Tuple , snake_case : str=False ):
"""simple docstring"""
_snake_case : List[Any] = text.replace(' ' , '<SP>' )
_snake_case : List[Any] = text.replace(' ' , '<SP>' )
_snake_case : List[str] = text.replace('\r\n' , '<BR>' )
_snake_case : int = text.replace('\n' , '<BR>' )
_snake_case : Dict = text.replace('\r' , '<BR>' )
_snake_case : int = text.replace('\t' , '<TAB>' )
_snake_case : int = text.replace('—' , 'ー' )
_snake_case : str = text.replace('−' , 'ー' )
for k, v in self.emoji["emoji"].items():
if k in text:
_snake_case : Optional[Any] = text.replace(snake_case , snake_case )
if clean:
_snake_case : List[str] = self.clean_text(snake_case )
def check_simbol(snake_case : Dict ):
_snake_case : Optional[Any] = x.encode()
if len(snake_case ) == 1 and len(snake_case ) == 2:
_snake_case : int = (int(e[0] ) << 8) + int(e[1] )
if (
(c >= 0Xc2a1 and c <= 0Xc2bf)
or (c >= 0Xc780 and c <= 0Xc783)
or (c >= 0Xcab9 and c <= 0Xcbbf)
or (c >= 0Xcc80 and c <= 0Xcda2)
):
return True
return False
def checkuae(snake_case : List[Any] ):
_snake_case : int = x.encode()
if len(snake_case ) == 1 and len(snake_case ) == 3:
_snake_case : Optional[int] = (int(e[0] ) << 16) + (int(e[1] ) << 8) + int(e[2] )
if c >= 0Xe28080 and c <= 0Xe2b07f:
return True
return False
_snake_case : Optional[int] = 0
_snake_case : Union[str, Any] = []
while pos < len(snake_case ):
_snake_case : Tuple = min(len(snake_case ) , pos + self.maxlen + 1 ) if text[pos] == '<' else pos + 3
_snake_case : Union[str, Any] = [] # (token_id, token, pos)
for e in range(snake_case , snake_case , -1 ):
_snake_case : str = text[pos:e]
if wd in self.vocab:
if wd[0] == "<" and len(snake_case ) > 2:
_snake_case : List[Any] = [(self.vocab[wd], wd, e)]
break
else:
candidates.append((self.vocab[wd], wd, e) )
if len(snake_case ) > 0:
# the smallest token_id is adopted
_snake_case , _snake_case , _snake_case : List[str] = sorted(snake_case , key=lambda snake_case : x[0] )[0]
result.append(snake_case )
_snake_case : Optional[Any] = e
else:
_snake_case : int = pos + 1
_snake_case : Tuple = text[pos:end]
if check_simbol(snake_case ):
result.append('<KIGOU>' )
elif checkuae(snake_case ):
result.append('<U2000U2BFF>' )
else:
for i in wd.encode('utf-8' ):
result.append('<|byte%d|>' % i )
_snake_case : int = end
return result
def __UpperCAmelCase ( self : Union[str, Any] , snake_case : Tuple , snake_case : str="\n" ):
"""simple docstring"""
_snake_case : Union[str, Any] = []
_snake_case : List[str] = []
_snake_case : Optional[int] = self.ids_to_tokens[index][0]
if word[:6] == "<|byte" and word[-2:] == "|>":
byte_tokens.append(int(word[6:-2] ) )
else:
if len(snake_case ) > 0:
words.append(bytearray(snake_case ).decode('utf-8' , errors='replace' ) )
_snake_case : Union[str, Any] = []
if word[:7] == "<|emoji" and word[-2:] == "|>":
words.append(self.emoji['emoji_inv'][word] )
elif word == "<SP>":
words.append(' ' )
elif word == "<BR>":
words.append(snake_case )
elif word == "<TAB>":
words.append('\t' )
elif word == "<BLOCK>":
words.append('▀' )
elif word == "<KIGOU>":
words.append('ǀ' )
elif word == "<U2000U2BFF>":
words.append('‖' )
else:
words.append(snake_case )
if len(snake_case ) > 0:
words.append(bytearray(snake_case ).decode('utf-8' , errors='replace' ) )
_snake_case : Dict = ''.join(snake_case )
return text
| 517 | 1 |
def __lowerCAmelCase ( _UpperCamelCase = 100 ) -> int:
'''simple docstring'''
lowerCamelCase__: str = (n * (n + 1) // 2) ** 2
lowerCamelCase__: Dict = n * (n + 1) * (2 * n + 1) // 6
return sum_cubes - sum_squares
if __name__ == "__main__":
print(F"""{solution() = }""")
| 703 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowercase = logging.get_logger(__name__)
_lowercase = {
'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/config.json',
'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/config.json'
# See all FNet models at https://huggingface.co/models?filter=fnet
}
class lowerCamelCase__ ( A__ ):
__lowerCamelCase = """fnet"""
def __init__( self : List[Any] , __a : Union[str, Any]=32000 , __a : Any=768 , __a : Tuple=12 , __a : Tuple=3072 , __a : List[Any]="gelu_new" , __a : str=0.1 , __a : Optional[int]=512 , __a : int=4 , __a : str=0.02 , __a : Dict=1e-12 , __a : Optional[Any]=False , __a : Any=512 , __a : Any=3 , __a : int=1 , __a : Optional[int]=2 , **__a : List[str] , ):
'''simple docstring'''
super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a )
lowerCamelCase__: Tuple = vocab_size
lowerCamelCase__: str = max_position_embeddings
lowerCamelCase__: str = hidden_size
lowerCamelCase__: str = num_hidden_layers
lowerCamelCase__: Union[str, Any] = intermediate_size
lowerCamelCase__: List[str] = hidden_act
lowerCamelCase__: str = hidden_dropout_prob
lowerCamelCase__: Any = initializer_range
lowerCamelCase__: List[Any] = type_vocab_size
lowerCamelCase__: List[str] = layer_norm_eps
lowerCamelCase__: Dict = use_tpu_fourier_optimizations
lowerCamelCase__: Union[str, Any] = tpu_short_seq_length
| 242 | 0 |
from ..utils import DummyObject, requires_backends
class UpperCamelCase_ ( metaclass=UpperCAmelCase__ ):
'''simple docstring'''
UpperCAmelCase__ = ['''transformers''', '''torch''', '''note_seq''']
def __init__( self : Tuple , *UpperCAmelCase__ : str , **UpperCAmelCase__ : Union[str, Any]) ->Any:
'''simple docstring'''
requires_backends(self , ['''transformers''', '''torch''', '''note_seq'''])
@classmethod
def SCREAMING_SNAKE_CASE ( cls : Union[str, Any] , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : Union[str, Any]) ->List[Any]:
'''simple docstring'''
requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''])
@classmethod
def SCREAMING_SNAKE_CASE ( cls : List[Any] , *UpperCAmelCase__ : Tuple , **UpperCAmelCase__ : List[str]) ->Union[str, Any]:
'''simple docstring'''
requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''])
| 87 |
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 __lowerCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : Union[str, Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : List[Any]=7 , _lowerCAmelCase : Any=3 , _lowerCAmelCase : Dict=1_8 , _lowerCAmelCase : Tuple=3_0 , _lowerCAmelCase : Optional[int]=4_0_0 , _lowerCAmelCase : Optional[int]=True , _lowerCAmelCase : Any=None , _lowerCAmelCase : List[Any]=True , ) -> Dict:
"""simple docstring"""
snake_case_ = size if size is not None else {"height": 1_8, "width": 1_8}
snake_case_ = parent
snake_case_ = batch_size
snake_case_ = num_channels
snake_case_ = image_size
snake_case_ = min_resolution
snake_case_ = max_resolution
snake_case_ = do_resize
snake_case_ = size
snake_case_ = do_normalize
def lowerCAmelCase__ ( self : str ) -> Optional[int]:
"""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 __lowerCAmelCase ( a , unittest.TestCase ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE = ImageGPTImageProcessor if is_vision_available() else None
def lowerCAmelCase__ ( self : Union[str, Any] ) -> List[Any]:
"""simple docstring"""
snake_case_ = ImageGPTImageProcessingTester(self )
@property
def lowerCAmelCase__ ( self : str ) -> Union[str, Any]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCAmelCase__ ( self : List[Any] ) -> int:
"""simple docstring"""
snake_case_ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowerCAmelCase , "clusters" ) )
self.assertTrue(hasattr(_lowerCAmelCase , "do_resize" ) )
self.assertTrue(hasattr(_lowerCAmelCase , "size" ) )
self.assertTrue(hasattr(_lowerCAmelCase , "do_normalize" ) )
def lowerCAmelCase__ ( self : int ) -> Any:
"""simple docstring"""
snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"height": 1_8, "width": 1_8} )
snake_case_ = 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 lowerCAmelCase__ ( self : Tuple ) -> Any:
"""simple docstring"""
snake_case_ = self.image_processing_class(**self.image_processor_dict )
snake_case_ = json.loads(image_processor.to_json_string() )
for key, value in self.image_processor_dict.items():
if key == "clusters":
self.assertTrue(np.array_equal(_lowerCAmelCase , obj[key] ) )
else:
self.assertEqual(obj[key] , _lowerCAmelCase )
def lowerCAmelCase__ ( self : int ) -> Optional[Any]:
"""simple docstring"""
snake_case_ = self.image_processing_class(**self.image_processor_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
snake_case_ = os.path.join(_lowerCAmelCase , "image_processor.json" )
image_processor_first.to_json_file(_lowerCAmelCase )
snake_case_ = self.image_processing_class.from_json_file(_lowerCAmelCase ).to_dict()
snake_case_ = image_processor_first.to_dict()
for key, value in image_processor_first.items():
if key == "clusters":
self.assertTrue(np.array_equal(_lowerCAmelCase , image_processor_second[key] ) )
else:
self.assertEqual(image_processor_first[key] , _lowerCAmelCase )
def lowerCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]:
"""simple docstring"""
snake_case_ = self.image_processing_class(**self.image_processor_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
image_processor_first.save_pretrained(_lowerCAmelCase )
snake_case_ = self.image_processing_class.from_pretrained(_lowerCAmelCase ).to_dict()
snake_case_ = image_processor_first.to_dict()
for key, value in image_processor_first.items():
if key == "clusters":
self.assertTrue(np.array_equal(_lowerCAmelCase , image_processor_second[key] ) )
else:
self.assertEqual(image_processor_first[key] , _lowerCAmelCase )
@unittest.skip("ImageGPT requires clusters at initialization" )
def lowerCAmelCase__ ( self : List[str] ) -> int:
"""simple docstring"""
pass
def _lowerCAmelCase ( )->Optional[Any]:
'''simple docstring'''
snake_case_ = load_dataset("hf-internal-testing/fixtures_image_utils" , split="test" )
snake_case_ = Image.open(dataset[4]["file"] )
snake_case_ = Image.open(dataset[5]["file"] )
snake_case_ = [imagea, imagea]
return images
@require_vision
@require_torch
class __lowerCAmelCase ( unittest.TestCase ):
"""simple docstring"""
@slow
def lowerCAmelCase__ ( self : List[str] ) -> int:
"""simple docstring"""
snake_case_ = ImageGPTImageProcessor.from_pretrained("openai/imagegpt-small" )
snake_case_ = prepare_images()
# test non-batched
snake_case_ = 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_ = [3_0_6, 1_9_1, 1_9_1]
self.assertEqual(encoding.input_ids[0, :3].tolist() , _lowerCAmelCase )
# test batched
snake_case_ = image_processing(_lowerCAmelCase , return_tensors="pt" )
self.assertIsInstance(encoding.input_ids , torch.LongTensor )
self.assertEqual(encoding.input_ids.shape , (2, 1_0_2_4) )
snake_case_ = [3_0_3, 1_3, 1_3]
self.assertEqual(encoding.input_ids[1, -3:].tolist() , _lowerCAmelCase )
| 283 | 0 |
import cva
import numpy as np
class _SCREAMING_SNAKE_CASE :
def __init__( self , lowercase , lowercase ) -> str:
if k in (0.0_4, 0.0_6):
lowerCamelCase_ = k
lowerCamelCase_ = window_size
else:
raise ValueError("invalid k value" )
def __str__( self ) -> str:
return str(self.k )
def SCREAMING_SNAKE_CASE_( self , lowercase ) -> tuple[cva.Mat, list[list[int]]]:
lowerCamelCase_ = cva.imread(lowercase , 0 )
lowerCamelCase_ , lowerCamelCase_ = img.shape
lowerCamelCase_ = []
lowerCamelCase_ = img.copy()
lowerCamelCase_ = cva.cvtColor(lowercase , cva.COLOR_GRAY2RGB )
lowerCamelCase_ , lowerCamelCase_ = np.gradient(lowercase )
lowerCamelCase_ = dx**2
lowerCamelCase_ = dy**2
lowerCamelCase_ = dx * dy
lowerCamelCase_ = 0.0_4
lowerCamelCase_ = self.window_size // 2
for y in range(lowercase , h - offset ):
for x in range(lowercase , w - offset ):
lowerCamelCase_ = ixx[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
lowerCamelCase_ = iyy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
lowerCamelCase_ = ixy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
lowerCamelCase_ = (wxx * wyy) - (wxy**2)
lowerCamelCase_ = wxx + wyy
lowerCamelCase_ = 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) , 255 )
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)
| 313 |
import argparse
import requests
import torch
from PIL import Image
from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor
def lowerCamelCase_ ( lowerCamelCase__ ):
if "cls_token" in name:
lowerCamelCase_ = name.replace("cls_token" , "vit.embeddings.cls_token" )
if "mask_token" in name:
lowerCamelCase_ = name.replace("mask_token" , "decoder.mask_token" )
if "decoder_pos_embed" in name:
lowerCamelCase_ = name.replace("decoder_pos_embed" , "decoder.decoder_pos_embed" )
if "pos_embed" in name and "decoder" not in name:
lowerCamelCase_ = name.replace("pos_embed" , "vit.embeddings.position_embeddings" )
if "patch_embed.proj" in name:
lowerCamelCase_ = name.replace("patch_embed.proj" , "vit.embeddings.patch_embeddings.projection" )
if "patch_embed.norm" in name:
lowerCamelCase_ = name.replace("patch_embed.norm" , "vit.embeddings.norm" )
if "decoder_blocks" in name:
lowerCamelCase_ = name.replace("decoder_blocks" , "decoder.decoder_layers" )
if "blocks" in name:
lowerCamelCase_ = name.replace("blocks" , "vit.encoder.layer" )
if "attn.proj" in name:
lowerCamelCase_ = name.replace("attn.proj" , "attention.output.dense" )
if "attn" in name:
lowerCamelCase_ = name.replace("attn" , "attention.self" )
if "norm1" in name:
lowerCamelCase_ = name.replace("norm1" , "layernorm_before" )
if "norm2" in name:
lowerCamelCase_ = name.replace("norm2" , "layernorm_after" )
if "mlp.fc1" in name:
lowerCamelCase_ = name.replace("mlp.fc1" , "intermediate.dense" )
if "mlp.fc2" in name:
lowerCamelCase_ = name.replace("mlp.fc2" , "output.dense" )
if "decoder_embed" in name:
lowerCamelCase_ = name.replace("decoder_embed" , "decoder.decoder_embed" )
if "decoder_norm" in name:
lowerCamelCase_ = name.replace("decoder_norm" , "decoder.decoder_norm" )
if "decoder_pred" in name:
lowerCamelCase_ = name.replace("decoder_pred" , "decoder.decoder_pred" )
if "norm.weight" in name and "decoder" not in name:
lowerCamelCase_ = name.replace("norm.weight" , "vit.layernorm.weight" )
if "norm.bias" in name and "decoder" not in name:
lowerCamelCase_ = name.replace("norm.bias" , "vit.layernorm.bias" )
return name
def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ):
for key in orig_state_dict.copy().keys():
lowerCamelCase_ = orig_state_dict.pop(lowerCamelCase__ )
if "qkv" in key:
lowerCamelCase_ = key.split("." )
lowerCamelCase_ = int(key_split[1] )
if "decoder_blocks" in key:
lowerCamelCase_ = config.decoder_hidden_size
lowerCamelCase_ = "decoder.decoder_layers."
if "weight" in key:
lowerCamelCase_ = val[:dim, :]
lowerCamelCase_ = val[dim : dim * 2, :]
lowerCamelCase_ = val[-dim:, :]
elif "bias" in key:
lowerCamelCase_ = val[:dim]
lowerCamelCase_ = val[dim : dim * 2]
lowerCamelCase_ = val[-dim:]
else:
lowerCamelCase_ = config.hidden_size
lowerCamelCase_ = "vit.encoder.layer."
if "weight" in key:
lowerCamelCase_ = val[:dim, :]
lowerCamelCase_ = val[dim : dim * 2, :]
lowerCamelCase_ = val[-dim:, :]
elif "bias" in key:
lowerCamelCase_ = val[:dim]
lowerCamelCase_ = val[dim : dim * 2]
lowerCamelCase_ = val[-dim:]
else:
lowerCamelCase_ = val
return orig_state_dict
def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ):
lowerCamelCase_ = ViTMAEConfig()
if "large" in checkpoint_url:
lowerCamelCase_ = 1_0_2_4
lowerCamelCase_ = 4_0_9_6
lowerCamelCase_ = 2_4
lowerCamelCase_ = 1_6
elif "huge" in checkpoint_url:
lowerCamelCase_ = 1_4
lowerCamelCase_ = 1_2_8_0
lowerCamelCase_ = 5_1_2_0
lowerCamelCase_ = 3_2
lowerCamelCase_ = 1_6
lowerCamelCase_ = ViTMAEForPreTraining(lowerCamelCase__ )
lowerCamelCase_ = torch.hub.load_state_dict_from_url(lowerCamelCase__ , map_location="cpu" )["model"]
lowerCamelCase_ = ViTMAEImageProcessor(size=config.image_size )
lowerCamelCase_ = convert_state_dict(lowerCamelCase__ , lowerCamelCase__ )
model.load_state_dict(lowerCamelCase__ )
model.eval()
lowerCamelCase_ = "https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg"
lowerCamelCase_ = Image.open(requests.get(lowerCamelCase__ , stream=lowerCamelCase__ ).raw )
lowerCamelCase_ = ViTMAEImageProcessor(size=config.image_size )
lowerCamelCase_ = image_processor(images=lowerCamelCase__ , return_tensors="pt" )
# forward pass
torch.manual_seed(2 )
lowerCamelCase_ = model(**lowerCamelCase__ )
lowerCamelCase_ = outputs.logits
if "large" in checkpoint_url:
lowerCamelCase_ = torch.tensor(
[[-0.73_09, -0.71_28, -1.01_69], [-1.01_61, -0.90_58, -1.18_78], [-1.04_78, -0.94_11, -1.19_11]] )
elif "huge" in checkpoint_url:
lowerCamelCase_ = torch.tensor(
[[-1.15_99, -0.91_99, -1.22_21], [-1.19_52, -0.92_69, -1.23_07], [-1.21_43, -0.93_37, -1.22_62]] )
else:
lowerCamelCase_ = torch.tensor(
[[-0.91_92, -0.84_81, -1.12_59], [-1.13_49, -1.00_34, -1.25_99], [-1.17_57, -1.04_29, -1.27_26]] )
# verify logits
assert torch.allclose(logits[0, :3, :3] , lowerCamelCase__ , atol=1e-4 )
print(F'Saving model to {pytorch_dump_folder_path}' )
model.save_pretrained(lowerCamelCase__ )
print(F'Saving image processor to {pytorch_dump_folder_path}' )
image_processor.save_pretrained(lowerCamelCase__ )
if __name__ == "__main__":
__A =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--checkpoint_url''',
default='''https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth''',
type=str,
help='''URL of the checkpoint 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_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
| 313 | 1 |
"""simple docstring"""
import unittest
import numpy as np
import torch
from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad
class _UpperCamelCase ( unittest.TestCase):
def A (self ):
"""simple docstring"""
A__ = 1_0
def A (self ):
"""simple docstring"""
A__ = [1, 2, 3, 4]
A__ = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0]
self.assertEqual(truncate_or_pad(lowerCamelCase__ , self.block_size , 0 ) , lowerCamelCase__ )
def A (self ):
"""simple docstring"""
A__ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0]
A__ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0]
self.assertEqual(truncate_or_pad(lowerCamelCase__ , self.block_size , 0 ) , lowerCamelCase__ )
def A (self ):
"""simple docstring"""
A__ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3]
A__ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0]
self.assertEqual(truncate_or_pad(lowerCamelCase__ , self.block_size , 0 ) , lowerCamelCase__ )
def A (self ):
"""simple docstring"""
A__ = """It was the year of Our Lord one thousand seven hundred and
seventy-five.\n\nSpiritual revelations were conceded to England at that
favoured period, as at this."""
A__ ,A__ = process_story(lowerCamelCase__ )
self.assertEqual(lowerCamelCase__ , [] )
def A (self ):
"""simple docstring"""
A__ = """"""
A__ ,A__ = process_story(lowerCamelCase__ )
self.assertEqual(lowerCamelCase__ , [] )
self.assertEqual(lowerCamelCase__ , [] )
def A (self ):
"""simple docstring"""
A__ = (
"""It was the year of Our Lord one thousand seven hundred and """
"""seventy-five\n\nSpiritual revelations were conceded to England """
"""at that favoured period, as at this.\n@highlight\n\nIt was the best of times"""
)
A__ ,A__ = process_story(lowerCamelCase__ )
A__ = [
"""It was the year of Our Lord one thousand seven hundred and seventy-five.""",
"""Spiritual revelations were conceded to England at that favoured period, as at this.""",
]
self.assertEqual(lowerCamelCase__ , lowerCamelCase__ )
A__ = ["""It was the best of times."""]
self.assertEqual(lowerCamelCase__ , lowerCamelCase__ )
def A (self ):
"""simple docstring"""
A__ = torch.tensor([1, 2, 3, 4] )
A__ = torch.tensor([1, 1, 1, 1] )
np.testing.assert_array_equal(build_mask(lowerCamelCase__ , 0 ).numpy() , expected.numpy() )
def A (self ):
"""simple docstring"""
A__ = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] )
A__ = torch.tensor([1, 1, 1, 1, 0, 0, 0] )
np.testing.assert_array_equal(build_mask(lowerCamelCase__ , 2_3 ).numpy() , expected.numpy() )
def A (self ):
"""simple docstring"""
A__ = torch.tensor([8, 2, 3, 4, 1, 1, 1] )
A__ = torch.tensor([1, 1, 1, 1, 0, 0, 0] )
np.testing.assert_array_equal(build_mask(lowerCamelCase__ , 1 ).numpy() , expected.numpy() )
def A (self ):
"""simple docstring"""
A__ = 1_0_1
A__ = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] )
A__ = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] )
A__ = compute_token_type_ids(lowerCamelCase__ , lowerCamelCase__ )
np.testing.assert_array_equal(lowerCamelCase__ , lowerCamelCase__ )
| 574 |
"""simple docstring"""
from __future__ import annotations
import time
lowerCamelCase__ = list[tuple[int, int]]
lowerCamelCase__ = [
[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],
]
lowerCamelCase__ = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right
class _UpperCamelCase :
def __init__(self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
"""simple docstring"""
A__ = pos_x
A__ = pos_y
A__ = (pos_y, pos_x)
A__ = goal_x
A__ = goal_y
A__ = parent
class _UpperCamelCase :
def __init__(self , lowerCamelCase__ , lowerCamelCase__ ):
"""simple docstring"""
A__ = Node(start[1] , start[0] , goal[1] , goal[0] , lowerCamelCase__ )
A__ = Node(goal[1] , goal[0] , goal[1] , goal[0] , lowerCamelCase__ )
A__ = [self.start]
A__ = False
def A (self ):
"""simple docstring"""
while self.node_queue:
A__ = self.node_queue.pop(0 )
if current_node.pos == self.target.pos:
A__ = True
return self.retrace_path(lowerCamelCase__ )
A__ = self.get_successors(lowerCamelCase__ )
for node in successors:
self.node_queue.append(lowerCamelCase__ )
if not self.reached:
return [self.start.pos]
return None
def A (self , lowerCamelCase__ ):
"""simple docstring"""
A__ = []
for action in delta:
A__ = parent.pos_x + action[1]
A__ = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(lowerCamelCase__ ) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(lowerCamelCase__ , lowerCamelCase__ , self.target.pos_y , self.target.pos_x , lowerCamelCase__ ) )
return successors
def A (self , lowerCamelCase__ ):
"""simple docstring"""
A__ = node
A__ = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x) )
A__ = current_node.parent
path.reverse()
return path
class _UpperCamelCase :
def __init__(self , lowerCamelCase__ , lowerCamelCase__ ):
"""simple docstring"""
A__ = BreadthFirstSearch(lowerCamelCase__ , lowerCamelCase__ )
A__ = BreadthFirstSearch(lowerCamelCase__ , lowerCamelCase__ )
A__ = False
def A (self ):
"""simple docstring"""
while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
A__ = self.fwd_bfs.node_queue.pop(0 )
A__ = self.bwd_bfs.node_queue.pop(0 )
if current_bwd_node.pos == current_fwd_node.pos:
A__ = True
return self.retrace_bidirectional_path(
lowerCamelCase__ , lowerCamelCase__ )
A__ = current_bwd_node
A__ = current_fwd_node
A__ = {
self.fwd_bfs: self.fwd_bfs.get_successors(lowerCamelCase__ ),
self.bwd_bfs: self.bwd_bfs.get_successors(lowerCamelCase__ ),
}
for bfs in [self.fwd_bfs, self.bwd_bfs]:
for node in successors[bfs]:
bfs.node_queue.append(lowerCamelCase__ )
if not self.reached:
return [self.fwd_bfs.start.pos]
return None
def A (self , lowerCamelCase__ , lowerCamelCase__ ):
"""simple docstring"""
A__ = self.fwd_bfs.retrace_path(lowerCamelCase__ )
A__ = self.bwd_bfs.retrace_path(lowerCamelCase__ )
bwd_path.pop()
bwd_path.reverse()
A__ = fwd_path + bwd_path
return path
if __name__ == "__main__":
# all coordinates are given in format [y,x]
import doctest
doctest.testmod()
lowerCamelCase__ = (0, 0)
lowerCamelCase__ = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
lowerCamelCase__ = time.time()
lowerCamelCase__ = BreadthFirstSearch(init, goal)
lowerCamelCase__ = bfs.search()
lowerCamelCase__ = time.time() - start_bfs_time
print("Unidirectional BFS computation time : ", bfs_time)
lowerCamelCase__ = time.time()
lowerCamelCase__ = BidirectionalBreadthFirstSearch(init, goal)
lowerCamelCase__ = bd_bfs.search()
lowerCamelCase__ = time.time() - start_bd_bfs_time
print("Bidirectional BFS computation time : ", bd_bfs_time)
| 574 | 1 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_convbert import ConvBertTokenizer
snake_case = logging.get_logger(__name__)
snake_case = {"""vocab_file""": """vocab.txt"""}
snake_case = {
"""vocab_file""": {
"""YituTech/conv-bert-base""": """https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt""",
"""YituTech/conv-bert-medium-small""": (
"""https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt"""
),
"""YituTech/conv-bert-small""": """https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt""",
}
}
snake_case = {
"""YituTech/conv-bert-base""": 5_1_2,
"""YituTech/conv-bert-medium-small""": 5_1_2,
"""YituTech/conv-bert-small""": 5_1_2,
}
snake_case = {
"""YituTech/conv-bert-base""": {"""do_lower_case""": True},
"""YituTech/conv-bert-medium-small""": {"""do_lower_case""": True},
"""YituTech/conv-bert-small""": {"""do_lower_case""": True},
}
class A_ ( UpperCamelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = VOCAB_FILES_NAMES
SCREAMING_SNAKE_CASE_ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP
SCREAMING_SNAKE_CASE_ : List[Any] = PRETRAINED_INIT_CONFIGURATION
SCREAMING_SNAKE_CASE_ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
SCREAMING_SNAKE_CASE_ : Dict = ConvBertTokenizer
def __init__( self : Dict ,__A : Dict=None ,__A : Dict=None ,__A : Tuple=True ,__A : Union[str, Any]="[UNK]" ,__A : Optional[Any]="[SEP]" ,__A : Union[str, Any]="[PAD]" ,__A : Optional[int]="[CLS]" ,__A : Optional[int]="[MASK]" ,__A : List[Any]=True ,__A : Any=None ,**__A : int ,) -> Any:
super().__init__(
_a ,tokenizer_file=_a ,do_lower_case=_a ,unk_token=_a ,sep_token=_a ,pad_token=_a ,cls_token=_a ,mask_token=_a ,tokenize_chinese_chars=_a ,strip_accents=_a ,**_a ,)
_lowercase = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get('lowercase' ,_a ) != do_lower_case
or normalizer_state.get('strip_accents' ,_a ) != strip_accents
or normalizer_state.get('handle_chinese_chars' ,_a ) != tokenize_chinese_chars
):
_lowercase = getattr(_a ,normalizer_state.pop('type' ) )
_lowercase = do_lower_case
_lowercase = strip_accents
_lowercase = tokenize_chinese_chars
_lowercase = normalizer_class(**_a )
_lowercase = do_lower_case
def __UpperCAmelCase ( self : str ,__A : Tuple ,__A : Union[str, Any]=None ) -> Dict:
_lowercase = [self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def __UpperCAmelCase ( self : Optional[Any] ,__A : Tuple ,__A : Dict = None ) -> List[int]:
_lowercase = [self.sep_token_id]
_lowercase = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def __UpperCAmelCase ( self : List[Any] ,__A : str ,__A : str = None ) -> Tuple[str]:
_lowercase = self._tokenizer.model.save(_a ,name=_a )
return tuple(_a ) | 710 |
from collections import Counter
from pathlib import Path
from typing import Optional, Tuple
import yaml
class A_ ( yaml.SafeLoader ):
"""simple docstring"""
def __UpperCAmelCase ( self : Dict ,__A : List[Any] ) -> Any:
_lowercase = [self.constructed_objects[key_node] for key_node, _ in node.value]
_lowercase = [tuple(__A ) if isinstance(__A ,__A ) else key for key in keys]
_lowercase = Counter(__A )
_lowercase = [key for key in counter if counter[key] > 1]
if duplicate_keys:
raise TypeError(F"""Got duplicate yaml keys: {duplicate_keys}""" )
def __UpperCAmelCase ( self : Any ,__A : int ,__A : Dict=False ) -> Union[str, Any]:
_lowercase = super().construct_mapping(__A ,deep=__A )
self._check_no_duplicates_on_constructed_node(__A )
return mapping
def SCREAMING_SNAKE_CASE__ ( snake_case__ :str ) -> Tuple[Optional[str], str]:
_lowercase = list(readme_content.splitlines() )
if full_content and full_content[0] == "---" and "---" in full_content[1:]:
_lowercase = full_content[1:].index('---' ) + 1
_lowercase = '\n'.join(full_content[1:sep_idx] )
return yamlblock, "\n".join(full_content[sep_idx + 1 :] )
return None, "\n".join(snake_case__ )
class A_ ( UpperCAmelCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = {'''train_eval_index'''} # train-eval-index in the YAML metadata
@classmethod
def __UpperCAmelCase ( cls : List[Any] ,__A : Path ) -> "DatasetMetadata":
with open(__A ,encoding='utf-8' ) as readme_file:
_lowercase , _lowercase = _split_yaml_from_readme(readme_file.read() )
if yaml_string is not None:
return cls.from_yaml_string(__A )
else:
return cls()
def __UpperCAmelCase ( self : Union[str, Any] ,__A : Path ) -> Optional[Any]:
if path.exists():
with open(__A ,encoding='utf-8' ) as readme_file:
_lowercase = readme_file.read()
else:
_lowercase = None
_lowercase = self._to_readme(__A )
with open(__A ,'w' ,encoding='utf-8' ) as readme_file:
readme_file.write(__A )
def __UpperCAmelCase ( self : Tuple ,__A : Optional[str] = None ) -> str:
if readme_content is not None:
_lowercase , _lowercase = _split_yaml_from_readme(__A )
_lowercase = '---\n' + self.to_yaml_string() + '---\n' + content
else:
_lowercase = '---\n' + self.to_yaml_string() + '---\n'
return full_content
@classmethod
def __UpperCAmelCase ( cls : List[Any] ,__A : str ) -> "DatasetMetadata":
_lowercase = yaml.load(__A ,Loader=_NoDuplicateSafeLoader ) or {}
# Convert the YAML keys to DatasetMetadata fields
_lowercase = {
(key.replace('-' ,'_' ) if key.replace('-' ,'_' ) in cls._FIELDS_WITH_DASHES else key): value
for key, value in metadata_dict.items()
}
return cls(**__A )
def __UpperCAmelCase ( self : Optional[int] ) -> str:
return yaml.safe_dump(
{
(key.replace('_' ,'-' ) if key in self._FIELDS_WITH_DASHES else key): value
for key, value in self.items()
} ,sort_keys=__A ,allow_unicode=__A ,encoding='utf-8' ,).decode('utf-8' )
snake_case = {
"""image-classification""": [],
"""translation""": [],
"""image-segmentation""": [],
"""fill-mask""": [],
"""automatic-speech-recognition""": [],
"""token-classification""": [],
"""sentence-similarity""": [],
"""audio-classification""": [],
"""question-answering""": [],
"""summarization""": [],
"""zero-shot-classification""": [],
"""table-to-text""": [],
"""feature-extraction""": [],
"""other""": [],
"""multiple-choice""": [],
"""text-classification""": [],
"""text-to-image""": [],
"""text2text-generation""": [],
"""zero-shot-image-classification""": [],
"""tabular-classification""": [],
"""tabular-regression""": [],
"""image-to-image""": [],
"""tabular-to-text""": [],
"""unconditional-image-generation""": [],
"""text-retrieval""": [],
"""text-to-speech""": [],
"""object-detection""": [],
"""audio-to-audio""": [],
"""text-generation""": [],
"""conversational""": [],
"""table-question-answering""": [],
"""visual-question-answering""": [],
"""image-to-text""": [],
"""reinforcement-learning""": [],
"""voice-activity-detection""": [],
"""time-series-forecasting""": [],
"""document-question-answering""": [],
}
if __name__ == "__main__":
from argparse import ArgumentParser
snake_case = ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""")
ap.add_argument("""readme_filepath""")
snake_case = ap.parse_args()
snake_case = Path(args.readme_filepath)
snake_case = DatasetMetadata.from_readme(readme_filepath)
print(dataset_metadata)
dataset_metadata.to_readme(readme_filepath) | 535 | 0 |
import copy
from typing import Any, Dict, List, Optional, Union
import numpy as np
from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging
lowercase_ = logging.get_logger(__name__)
class A_ ( UpperCamelCase_ ):
'''simple docstring'''
__snake_case = ["""input_features"""]
def __init__( self: Optional[int] , a: Union[str, Any]=80 , a: str=1_6000 , a: Any=160 , a: Optional[int]=30 , a: Union[str, Any]=400 , a: Any=0.0 , a: Union[str, Any]=False , **a: int , ):
super().__init__(
feature_size=__A , sampling_rate=__A , padding_value=__A , return_attention_mask=__A , **__A , )
__lowerCamelCase : Tuple = n_fft
__lowerCamelCase : int = hop_length
__lowerCamelCase : List[str] = chunk_length
__lowerCamelCase : List[Any] = chunk_length * sampling_rate
__lowerCamelCase : str = self.n_samples // hop_length
__lowerCamelCase : Optional[int] = sampling_rate
__lowerCamelCase : Any = mel_filter_bank(
num_frequency_bins=1 + n_fft // 2 , num_mel_filters=__A , min_frequency=0.0 , max_frequency=8000.0 , sampling_rate=__A , norm='slaney' , mel_scale='slaney' , )
def _snake_case ( self: Dict , a: np.array ):
__lowerCamelCase : Dict = spectrogram(
__A , window_function(self.n_fft , 'hann' ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters , log_mel='log10' , )
__lowerCamelCase : Tuple = log_spec[:, :-1]
__lowerCamelCase : Tuple = np.maximum(__A , log_spec.max() - 8.0 )
__lowerCamelCase : str = (log_spec + 4.0) / 4.0
return log_spec
@staticmethod
# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
def _snake_case ( a: List[np.ndarray] , a: List[np.ndarray] , a: float = 0.0 ):
if attention_mask is not None:
__lowerCamelCase : List[Any] = np.array(__A , np.intaa )
__lowerCamelCase : Any = []
for vector, length in zip(__A , attention_mask.sum(-1 ) ):
__lowerCamelCase : Dict = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 )
if length < normed_slice.shape[0]:
__lowerCamelCase : str = padding_value
normed_input_values.append(__A )
else:
__lowerCamelCase : Union[str, Any] = [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values]
return normed_input_values
def __call__( self: Any , a: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , a: bool = True , a: Optional[int] = None , a: Optional[Union[str, TensorType]] = None , a: Optional[bool] = None , a: Optional[str] = "max_length" , a: Optional[int] = None , a: Optional[int] = None , a: Optional[bool] = None , **a: List[str] , ):
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
F'The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a'
F' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input'
F' was sampled with {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.' )
__lowerCamelCase : int = isinstance(__A , 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}' )
__lowerCamelCase : Union[str, Any] = is_batched_numpy or (
isinstance(__A , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
__lowerCamelCase : Union[str, Any] = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech]
elif not is_batched and not isinstance(__A , np.ndarray ):
__lowerCamelCase : str = np.asarray(__A , dtype=np.floataa )
elif isinstance(__A , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
__lowerCamelCase : Tuple = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
__lowerCamelCase : Any = [np.asarray([raw_speech] ).T]
__lowerCamelCase : List[str] = BatchFeature({'input_features': raw_speech} )
# convert into correct format for padding
__lowerCamelCase : int = self.pad(
__A , padding=__A , max_length=max_length if max_length else self.n_samples , truncation=__A , pad_to_multiple_of=__A , return_attention_mask=return_attention_mask or do_normalize , )
# zero-mean and unit-variance normalization
if do_normalize:
__lowerCamelCase : List[Any] = self.zero_mean_unit_var_norm(
padded_inputs['input_features'] , attention_mask=padded_inputs['attention_mask'] , padding_value=self.padding_value , )
__lowerCamelCase : Union[str, Any] = np.stack(padded_inputs['input_features'] , axis=0 )
# make sure list is in array format
__lowerCamelCase : int = padded_inputs.get('input_features' ).transpose(2 , 0 , 1 )
__lowerCamelCase : List[Any] = [self._np_extract_fbank_features(__A ) for waveform in input_features[0]]
if isinstance(input_features[0] , __A ):
__lowerCamelCase : Union[str, Any] = [np.asarray(__A , dtype=np.floataa ) for feature in input_features]
else:
__lowerCamelCase : Any = input_features
if return_attention_mask:
# rescale from sample (48000) to feature (3000)
__lowerCamelCase : Any = padded_inputs["attention_mask"][:, :: self.hop_length]
if return_tensors is not None:
__lowerCamelCase : List[str] = padded_inputs.convert_to_tensors(__A )
return padded_inputs
def _snake_case ( self: List[Any] ):
__lowerCamelCase : Tuple = copy.deepcopy(self.__dict__ )
__lowerCamelCase : Tuple = self.__class__.__name__
if "mel_filters" in output:
del output["mel_filters"]
return output
| 669 |
import warnings
from typing import List, Optional, Union
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ):
"""simple docstring"""
a_ = ["image_processor", "tokenizer"]
a_ = "FlavaImageProcessor"
a_ = ("BertTokenizer", "BertTokenizerFast")
def __init__( self : Tuple , __A : int=None , __A : Optional[Any]=None , **__A : Dict ):
snake_case__ : int = None
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__ : Tuple = kwargs.pop("feature_extractor" )
snake_case__ : Optional[Any] = 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 )
snake_case__ : Optional[int] = self.image_processor
def __call__( self : Dict , __A : Optional[ImageInput] = None , __A : Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None , __A : bool = True , __A : Union[bool, str, PaddingStrategy] = False , __A : Union[bool, str, TruncationStrategy] = False , __A : Optional[int] = None , __A : int = 0 , __A : Optional[int] = None , __A : Optional[bool] = None , __A : Optional[bool] = None , __A : Optional[bool] = None , __A : Optional[bool] = None , __A : bool = False , __A : bool = False , __A : bool = False , __A : bool = False , __A : bool = True , __A : Optional[Union[str, TensorType]] = None , **__A : Dict , ):
if text is None and images is None:
raise ValueError("You have to specify either text or images. Both cannot be none." )
if text is not None:
snake_case__ : Dict = self.tokenizer(
text=__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 , )
if images is not None:
snake_case__ : int = self.image_processor(
__A , return_image_mask=__A , return_codebook_pixels=__A , return_tensors=__A , **__A , )
if text is not None and images is not None:
encoding.update(__A )
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**__A ) , tensor_type=__A )
def _lowercase ( self : str , *__A : List[Any] , **__A : Dict ):
return self.tokenizer.batch_decode(*__A , **__A )
def _lowercase ( self : Optional[Any] , *__A : Optional[int] , **__A : List[Any] ):
return self.tokenizer.decode(*__A , **__A )
@property
def _lowercase ( self : Optional[Any] ):
snake_case__ : Any = self.tokenizer.model_input_names
snake_case__ : Dict = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
@property
def _lowercase ( self : Optional[Any] ):
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 _lowercase ( self : List[str] ):
warnings.warn(
"`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , __A , )
return self.image_processor
| 297 | 0 |
"""simple docstring"""
import unittest
from transformers import JukeboxTokenizer
from transformers.testing_utils import require_torch
class _UpperCamelCase ( unittest.TestCase ):
'''simple docstring'''
__UpperCAmelCase : Union[str, Any] =JukeboxTokenizer
__UpperCAmelCase : Optional[Any] ={
"""artist""": """Zac Brown Band""",
"""genres""": """Country""",
"""lyrics""": """I met a traveller from an antique land,
Who said \"Two vast and trunkless legs of stone
Stand in the desert. . . . Near them, on the sand,
Half sunk a shattered visage lies, whose frown,
And wrinkled lip, and sneer of cold command,
Tell that its sculptor well those passions read
Which yet survive, stamped on these lifeless things,
The hand that mocked them, and the heart that fed;
And on the pedestal, these words appear:
My name is Ozymandias, King of Kings;
Look on my Works, ye Mighty, and despair!
Nothing beside remains. Round the decay
Of that colossal Wreck, boundless and bare
The lone and level sands stretch far away
""",
}
@require_torch
def snake_case ( self ):
import torch
__lowerCAmelCase = JukeboxTokenizer.from_pretrained("openai/jukebox-1b-lyrics" )
__lowerCAmelCase = tokenizer(**self.metas )["input_ids"]
# fmt: off
__lowerCAmelCase = [
torch.tensor([[
0, 0, 0, 71_69, 5_07, 9, 76, 39, 31, 46, 76, 27,
76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32,
44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43,
47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76,
76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35,
30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76,
27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45,
45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46,
41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76,
19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31,
76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63,
76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39,
64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40,
30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8,
27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45,
34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45,
27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34,
41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76,
76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49,
44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64,
76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41,
32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27,
40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76,
20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46,
45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49,
31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27,
45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78,
76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29,
34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48,
31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41,
40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31,
38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64,
78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31,
76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39,
41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76,
27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44,
46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78,
76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76,
41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45,
46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49,
41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65,
78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76,
40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39,
27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33,
76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76,
76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76,
41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64,
76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76,
27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67,
78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46,
34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76,
44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47,
40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51,
78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76,
46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27,
38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47,
40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28,
27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76,
20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30,
76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45,
76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44,
76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76,
76, 76]] ),
torch.tensor([[0, 0, 0, 10_69, 11]] ),
torch.tensor([[0, 0, 0, 10_69, 11]] ),
]
# fmt: on
self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) )
self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) )
self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
@require_torch
def snake_case ( self ):
import torch
__lowerCAmelCase = JukeboxTokenizer.from_pretrained("openai/jukebox-5b-lyrics" )
__lowerCAmelCase = tokenizer(**self.metas )["input_ids"]
# fmt: off
__lowerCAmelCase = [
torch.tensor([[
0, 0, 0, 10_69, 11, -1, -1, -1, -1, 9, 77, 39,
31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38,
31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27,
40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64,
79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41,
77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48,
27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40,
37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41,
32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77,
77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40,
77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63,
77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77,
46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31,
77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77,
77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37,
77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30,
77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45,
64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49,
40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1,
40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77,
38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31,
31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29,
41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77,
77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27,
46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46,
41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45,
31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44,
31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77,
23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47,
44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42,
31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77,
38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35,
40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77,
77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34,
27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34,
31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77,
34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32,
31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77,
1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42,
31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31,
45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42,
31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77,
77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77,
15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77,
11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33,
45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12,
41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41,
44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34,
46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42,
27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77,
77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45,
35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63,
77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30,
31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77,
77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38,
41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64,
77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27,
40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77,
77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31,
77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45,
27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34,
77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77,
77, 77, 77, 77, 77, 77]] ),
torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ),
torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ),
]
# fmt: on
self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) )
self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) )
self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
| 282 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
A : Union[str, Any] = {
"configuration_x_clip": [
"XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP",
"XCLIPConfig",
"XCLIPTextConfig",
"XCLIPVisionConfig",
],
"processing_x_clip": ["XCLIPProcessor"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A : Optional[int] = [
"XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
"XCLIPModel",
"XCLIPPreTrainedModel",
"XCLIPTextModel",
"XCLIPVisionModel",
]
if TYPE_CHECKING:
from .configuration_x_clip import (
XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
XCLIPConfig,
XCLIPTextConfig,
XCLIPVisionConfig,
)
from .processing_x_clip import XCLIPProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_x_clip import (
XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
XCLIPModel,
XCLIPPreTrainedModel,
XCLIPTextModel,
XCLIPVisionModel,
)
else:
import sys
A : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 282 | 1 |
"""simple docstring"""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
# @@protoc_insertion_point(imports)
lowercase = _symbol_database.Default()
lowercase = _descriptor_pool.Default().AddSerializedFile(
b'''\n\x19sentencepiece_model.proto\x12\rsentencepiece"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03'''
)
lowercase = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, '''sentencepiece_model_pb2''', _globals)
if _descriptor._USE_C_DESCRIPTORS is False:
lowercase = None
lowercase = b'''H\003'''
# (generated by protobuf compiler, but `_TRAINERSPEC` is not defined)
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001"
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001"
lowercase = 45
lowercase = 15_81
lowercase = 15_17
lowercase = 15_70
lowercase = 15_84
lowercase = 17_93
lowercase = 17_95
lowercase = 19_16
lowercase = 18_64
lowercase = 19_05
lowercase = 19_19
lowercase = 24_29
lowercase = 22_08
lowercase = 24_18
lowercase = 23_23
lowercase = 24_07
# @@protoc_insertion_point(module_scope)
| 573 |
"""simple docstring"""
from typing import List
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowercase = logging.get_logger(__name__)
lowercase = {
'''snap-research/efficientformer-l1-300''': (
'''https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json'''
),
}
class lowercase__ ( A ):
'''simple docstring'''
_UpperCAmelCase = '''efficientformer'''
def __init__( self , snake_case = [3, 2, 6, 4] , snake_case = [48, 96, 224, 448] , snake_case = [True, True, True, True] , snake_case = 448 , snake_case = 32 , snake_case = 4 , snake_case = 7 , snake_case = 5 , snake_case = 8 , snake_case = 4 , snake_case = 0.0 , snake_case = 16 , snake_case = 3 , snake_case = 3 , snake_case = 3 , snake_case = 2 , snake_case = 1 , snake_case = 0.0 , snake_case = 1 , snake_case = True , snake_case = True , snake_case = 1E-5 , snake_case = "gelu" , snake_case = 0.02 , snake_case = 1E-12 , snake_case = 224 , snake_case = 1E-05 , **snake_case , ) -> None:
super().__init__(**snake_case )
_UpperCAmelCase = hidden_act
_UpperCAmelCase = hidden_dropout_prob
_UpperCAmelCase = hidden_sizes
_UpperCAmelCase = num_hidden_layers
_UpperCAmelCase = num_attention_heads
_UpperCAmelCase = initializer_range
_UpperCAmelCase = layer_norm_eps
_UpperCAmelCase = patch_size
_UpperCAmelCase = num_channels
_UpperCAmelCase = depths
_UpperCAmelCase = mlp_expansion_ratio
_UpperCAmelCase = downsamples
_UpperCAmelCase = dim
_UpperCAmelCase = key_dim
_UpperCAmelCase = attention_ratio
_UpperCAmelCase = resolution
_UpperCAmelCase = pool_size
_UpperCAmelCase = downsample_patch_size
_UpperCAmelCase = downsample_stride
_UpperCAmelCase = downsample_pad
_UpperCAmelCase = drop_path_rate
_UpperCAmelCase = num_metaad_blocks
_UpperCAmelCase = distillation
_UpperCAmelCase = use_layer_scale
_UpperCAmelCase = layer_scale_init_value
_UpperCAmelCase = image_size
_UpperCAmelCase = batch_norm_eps
| 573 | 1 |
import string
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ):
for key in range(len(string.ascii_uppercase ) ):
__UpperCamelCase =''
for symbol in message:
if symbol in string.ascii_uppercase:
__UpperCamelCase =string.ascii_uppercase.find(SCREAMING_SNAKE_CASE__ )
__UpperCamelCase =num - key
if num < 0:
__UpperCamelCase =num + len(string.ascii_uppercase )
__UpperCamelCase =translated + string.ascii_uppercase[num]
else:
__UpperCamelCase =translated + symbol
print(F'Decryption using Key #{key}: {translated}' )
def _UpperCAmelCase ( ):
__UpperCamelCase =input('Encrypted message: ' )
__UpperCamelCase =message.upper()
decrypt(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 706 |
import argparse
import json
from collections import OrderedDict
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
_A = logging.get_logger(__name__)
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ):
__UpperCamelCase =original_name.split('.' )[0]
__UpperCamelCase =key.split('.' )
__UpperCamelCase =int(key_list[key_list.index(SCREAMING_SNAKE_CASE__ ) - 2] )
__UpperCamelCase =int(key_list[key_list.index(SCREAMING_SNAKE_CASE__ ) - 1] )
__UpperCamelCase =orig_block_num - offset
__UpperCamelCase =key.replace(F'{orig_block_num}.{layer_num}.{original_name}' , F'block.{new_block_num}.{layer_num}.{new_name}' )
return key
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ):
__UpperCamelCase =OrderedDict()
__UpperCamelCase , __UpperCamelCase =0, 0
for key, value in state_dict.items():
if key.startswith('network' ):
__UpperCamelCase =key.replace('network' , 'poolformer.encoder' )
if "proj" in key:
# Works for the first embedding as well as the internal embedding layers
if key.endswith('bias' ) and "patch_embed" not in key:
patch_emb_offset += 1
__UpperCamelCase =key[: key.find('proj' )]
__UpperCamelCase =key.replace(SCREAMING_SNAKE_CASE__ , F'patch_embeddings.{total_embed_found}.' )
__UpperCamelCase =key.replace('proj' , 'projection' )
if key.endswith('bias' ):
total_embed_found += 1
if "patch_embeddings" in key:
__UpperCamelCase ='poolformer.encoder.' + key
if "mlp.fc1" in key:
__UpperCamelCase =replace_key_with_offset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'mlp.fc1' , 'output.conv1' )
if "mlp.fc2" in key:
__UpperCamelCase =replace_key_with_offset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'mlp.fc2' , 'output.conv2' )
if "norm1" in key:
__UpperCamelCase =replace_key_with_offset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'norm1' , 'before_norm' )
if "norm2" in key:
__UpperCamelCase =replace_key_with_offset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'norm2' , 'after_norm' )
if "layer_scale_1" in key:
__UpperCamelCase =replace_key_with_offset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'layer_scale_1' , 'layer_scale_1' )
if "layer_scale_2" in key:
__UpperCamelCase =replace_key_with_offset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'layer_scale_2' , 'layer_scale_2' )
if "head" in key:
__UpperCamelCase =key.replace('head' , 'classifier' )
__UpperCamelCase =value
return new_state_dict
def _UpperCAmelCase ( ):
__UpperCamelCase ='http://images.cocodataset.org/val2017/000000039769.jpg'
__UpperCamelCase =Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw )
return image
@torch.no_grad()
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ):
__UpperCamelCase =PoolFormerConfig()
# set attributes based on model_name
__UpperCamelCase ='huggingface/label-files'
__UpperCamelCase =model_name[-3:]
__UpperCamelCase =10_00
__UpperCamelCase ='imagenet-1k-id2label.json'
__UpperCamelCase =(1, 10_00)
# set config attributes
__UpperCamelCase =json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='dataset' ) , 'r' ) )
__UpperCamelCase ={int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()}
__UpperCamelCase =idalabel
__UpperCamelCase ={v: k for k, v in idalabel.items()}
if size == "s12":
__UpperCamelCase =[2, 2, 6, 2]
__UpperCamelCase =[64, 1_28, 3_20, 5_12]
__UpperCamelCase =4.0
__UpperCamelCase =0.9
elif size == "s24":
__UpperCamelCase =[4, 4, 12, 4]
__UpperCamelCase =[64, 1_28, 3_20, 5_12]
__UpperCamelCase =4.0
__UpperCamelCase =0.9
elif size == "s36":
__UpperCamelCase =[6, 6, 18, 6]
__UpperCamelCase =[64, 1_28, 3_20, 5_12]
__UpperCamelCase =4.0
__UpperCamelCase =1E-6
__UpperCamelCase =0.9
elif size == "m36":
__UpperCamelCase =[6, 6, 18, 6]
__UpperCamelCase =[96, 1_92, 3_84, 7_68]
__UpperCamelCase =4.0
__UpperCamelCase =1E-6
__UpperCamelCase =0.95
elif size == "m48":
__UpperCamelCase =[8, 8, 24, 8]
__UpperCamelCase =[96, 1_92, 3_84, 7_68]
__UpperCamelCase =4.0
__UpperCamelCase =1E-6
__UpperCamelCase =0.95
else:
raise ValueError(F'Size {size} not supported' )
# load image processor
__UpperCamelCase =PoolFormerImageProcessor(crop_pct=SCREAMING_SNAKE_CASE__ )
# Prepare image
__UpperCamelCase =prepare_img()
__UpperCamelCase =image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values
logger.info(F'Converting model {model_name}...' )
# load original state dict
__UpperCamelCase =torch.load(SCREAMING_SNAKE_CASE__ , map_location=torch.device('cpu' ) )
# rename keys
__UpperCamelCase =rename_keys(SCREAMING_SNAKE_CASE__ )
# create HuggingFace model and load state dict
__UpperCamelCase =PoolFormerForImageClassification(SCREAMING_SNAKE_CASE__ )
model.load_state_dict(SCREAMING_SNAKE_CASE__ )
model.eval()
# Define image processor
__UpperCamelCase =PoolFormerImageProcessor(crop_pct=SCREAMING_SNAKE_CASE__ )
__UpperCamelCase =image_processor(images=prepare_img() , return_tensors='pt' ).pixel_values
# forward pass
__UpperCamelCase =model(SCREAMING_SNAKE_CASE__ )
__UpperCamelCase =outputs.logits
# define expected logit slices for different models
if size == "s12":
__UpperCamelCase =torch.tensor([-0.3045, -0.6758, -0.4869] )
elif size == "s24":
__UpperCamelCase =torch.tensor([0.4402, -0.1374, -0.8045] )
elif size == "s36":
__UpperCamelCase =torch.tensor([-0.6080, -0.5133, -0.5898] )
elif size == "m36":
__UpperCamelCase =torch.tensor([0.3952, 0.2263, -1.2668] )
elif size == "m48":
__UpperCamelCase =torch.tensor([0.1167, -0.0656, -0.3423] )
else:
raise ValueError(F'Size {size} not supported' )
# verify logits
assert logits.shape == expected_shape
assert torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-2 )
# finally, save model and image processor
logger.info(F'Saving PyTorch model and image processor to {pytorch_dump_folder_path}...' )
Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ )
model.save_pretrained(SCREAMING_SNAKE_CASE__ )
print(F'Saving image processor to {pytorch_dump_folder_path}' )
image_processor.save_pretrained(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
_A = argparse.ArgumentParser()
parser.add_argument(
'--model_name',
default='poolformer_s12',
type=str,
help='Name of the model you\'d like to convert.',
)
parser.add_argument(
'--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).'
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.'
)
_A = parser.parse_args()
convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
| 682 | 0 |
import torch
from diffusers import CMStochasticIterativeScheduler
from .test_schedulers import SchedulerCommonTest
class _snake_case ( UpperCAmelCase_ ):
__lowerCAmelCase : Optional[int] = (CMStochasticIterativeScheduler,)
__lowerCAmelCase : int = 10
def lowercase__ ( self , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
lowercase__ : Dict = {
"""num_train_timesteps""": 2_01,
"""sigma_min""": 0.0_0_2,
"""sigma_max""": 8_0.0,
}
config.update(**SCREAMING_SNAKE_CASE_)
return config
def lowercase__ ( self):
'''simple docstring'''
lowercase__ : Optional[Any] = 10
lowercase__ : Union[str, Any] = self.get_scheduler_config()
lowercase__ : List[str] = self.scheduler_classes[0](**SCREAMING_SNAKE_CASE_)
scheduler.set_timesteps(SCREAMING_SNAKE_CASE_)
lowercase__ : int = scheduler.timesteps[0]
lowercase__ : str = scheduler.timesteps[1]
lowercase__ : List[Any] = self.dummy_sample
lowercase__ : str = 0.1 * sample
lowercase__ : List[Any] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_).prev_sample
lowercase__ : int = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_).prev_sample
self.assertEqual(output_a.shape , sample.shape)
self.assertEqual(output_a.shape , output_a.shape)
def lowercase__ ( self):
'''simple docstring'''
for timesteps in [10, 50, 1_00, 10_00]:
self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_)
def lowercase__ ( self):
'''simple docstring'''
for clip_denoised in [True, False]:
self.check_over_configs(clip_denoised=SCREAMING_SNAKE_CASE_)
def lowercase__ ( self):
'''simple docstring'''
lowercase__ : List[str] = self.scheduler_classes[0]
lowercase__ : int = self.get_scheduler_config()
lowercase__ : List[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_)
lowercase__ : Dict = 1
scheduler.set_timesteps(SCREAMING_SNAKE_CASE_)
lowercase__ : List[str] = scheduler.timesteps
lowercase__ : int = torch.manual_seed(0)
lowercase__ : List[str] = self.dummy_model()
lowercase__ : str = self.dummy_sample_deter * scheduler.init_noise_sigma
for i, t in enumerate(SCREAMING_SNAKE_CASE_):
# 1. scale model input
lowercase__ : Dict = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_)
# 2. predict noise residual
lowercase__ : Optional[Any] = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_)
# 3. predict previous sample x_t-1
lowercase__ : Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_).prev_sample
lowercase__ : int = pred_prev_sample
lowercase__ : int = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_))
lowercase__ : Any = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_))
assert abs(result_sum.item() - 1_9_2.7_6_1_4) < 1E-2
assert abs(result_mean.item() - 0.2_5_1_0) < 1E-3
def lowercase__ ( self):
'''simple docstring'''
lowercase__ : List[Any] = self.scheduler_classes[0]
lowercase__ : Union[str, Any] = self.get_scheduler_config()
lowercase__ : Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE_)
lowercase__ : List[str] = [1_06, 0]
scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_)
lowercase__ : Any = scheduler.timesteps
lowercase__ : List[Any] = torch.manual_seed(0)
lowercase__ : Optional[int] = self.dummy_model()
lowercase__ : Tuple = self.dummy_sample_deter * scheduler.init_noise_sigma
for t in timesteps:
# 1. scale model input
lowercase__ : Any = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_)
# 2. predict noise residual
lowercase__ : Optional[int] = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_)
# 3. predict previous sample x_t-1
lowercase__ : Any = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_).prev_sample
lowercase__ : Any = pred_prev_sample
lowercase__ : Optional[int] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_))
lowercase__ : Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_))
assert abs(result_sum.item() - 3_4_7.6_3_5_7) < 1E-2
assert abs(result_mean.item() - 0.4_5_2_7) < 1E-3
def lowercase__ ( self):
'''simple docstring'''
lowercase__ : Tuple = self.scheduler_classes[0]
lowercase__ : Tuple = self.get_scheduler_config()
lowercase__ : Dict = scheduler_class(**SCREAMING_SNAKE_CASE_)
lowercase__ : Dict = [39, 30, 12, 15, 0]
with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg="""`timesteps` must be in descending order."""):
scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_)
def lowercase__ ( self):
'''simple docstring'''
lowercase__ : List[Any] = self.scheduler_classes[0]
lowercase__ : Dict = self.get_scheduler_config()
lowercase__ : List[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_)
lowercase__ : str = [39, 30, 12, 1, 0]
lowercase__ : str = len(SCREAMING_SNAKE_CASE_)
with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg="""Can only pass one of `num_inference_steps` or `timesteps`."""):
scheduler.set_timesteps(num_inference_steps=SCREAMING_SNAKE_CASE_ , timesteps=SCREAMING_SNAKE_CASE_)
def lowercase__ ( self):
'''simple docstring'''
lowercase__ : int = self.scheduler_classes[0]
lowercase__ : Dict = self.get_scheduler_config()
lowercase__ : Any = scheduler_class(**SCREAMING_SNAKE_CASE_)
lowercase__ : Optional[int] = [scheduler.config.num_train_timesteps]
with self.assertRaises(
SCREAMING_SNAKE_CASE_ , msg="""`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}""" , ):
scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_)
| 12 |
'''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_roberta import RobertaTokenizer
snake_case_ = logging.get_logger(__name__)
snake_case_ = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}
snake_case_ = {
"""vocab_file""": {
"""roberta-base""": """https://huggingface.co/roberta-base/resolve/main/vocab.json""",
"""roberta-large""": """https://huggingface.co/roberta-large/resolve/main/vocab.json""",
"""roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json""",
"""distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/vocab.json""",
"""roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json""",
"""roberta-large-openai-detector""": (
"""https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json"""
),
},
"""merges_file""": {
"""roberta-base""": """https://huggingface.co/roberta-base/resolve/main/merges.txt""",
"""roberta-large""": """https://huggingface.co/roberta-large/resolve/main/merges.txt""",
"""roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt""",
"""distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/merges.txt""",
"""roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt""",
"""roberta-large-openai-detector""": (
"""https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt"""
),
},
"""tokenizer_file""": {
"""roberta-base""": """https://huggingface.co/roberta-base/resolve/main/tokenizer.json""",
"""roberta-large""": """https://huggingface.co/roberta-large/resolve/main/tokenizer.json""",
"""roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json""",
"""distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json""",
"""roberta-base-openai-detector""": (
"""https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json"""
),
"""roberta-large-openai-detector""": (
"""https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json"""
),
},
}
snake_case_ = {
"""roberta-base""": 512,
"""roberta-large""": 512,
"""roberta-large-mnli""": 512,
"""distilroberta-base""": 512,
"""roberta-base-openai-detector""": 512,
"""roberta-large-openai-detector""": 512,
}
class a__ ( _lowercase ):
__magic_name__ : Any = VOCAB_FILES_NAMES
__magic_name__ : Any = PRETRAINED_VOCAB_FILES_MAP
__magic_name__ : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__magic_name__ : Dict = ["input_ids", "attention_mask"]
__magic_name__ : Tuple = RobertaTokenizer
def __init__(self : Optional[Any], __UpperCAmelCase : Dict=None, __UpperCAmelCase : Tuple=None, __UpperCAmelCase : Tuple=None, __UpperCAmelCase : Any="replace", __UpperCAmelCase : Dict="<s>", __UpperCAmelCase : List[Any]="</s>", __UpperCAmelCase : Union[str, Any]="</s>", __UpperCAmelCase : int="<s>", __UpperCAmelCase : Optional[Any]="<unk>", __UpperCAmelCase : Tuple="<pad>", __UpperCAmelCase : Union[str, Any]="<mask>", __UpperCAmelCase : Any=False, __UpperCAmelCase : Optional[int]=True, **__UpperCAmelCase : Optional[Any], ) -> Tuple:
"""simple docstring"""
super().__init__(
__UpperCAmelCase, __UpperCAmelCase, tokenizer_file=__UpperCAmelCase, errors=__UpperCAmelCase, bos_token=__UpperCAmelCase, eos_token=__UpperCAmelCase, sep_token=__UpperCAmelCase, cls_token=__UpperCAmelCase, unk_token=__UpperCAmelCase, pad_token=__UpperCAmelCase, mask_token=__UpperCAmelCase, add_prefix_space=__UpperCAmelCase, trim_offsets=__UpperCAmelCase, **__UpperCAmelCase, )
SCREAMING_SNAKE_CASE : Optional[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get('''add_prefix_space''', __UpperCAmelCase ) != add_prefix_space:
SCREAMING_SNAKE_CASE : str = getattr(__UpperCAmelCase, pre_tok_state.pop('''type''' ) )
SCREAMING_SNAKE_CASE : Dict = add_prefix_space
SCREAMING_SNAKE_CASE : Optional[int] = pre_tok_class(**__UpperCAmelCase )
SCREAMING_SNAKE_CASE : Any = add_prefix_space
SCREAMING_SNAKE_CASE : Optional[int] = '''post_processor'''
SCREAMING_SNAKE_CASE : Any = getattr(self.backend_tokenizer, __UpperCAmelCase, __UpperCAmelCase )
if tokenizer_component_instance:
SCREAMING_SNAKE_CASE : Union[str, 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:
SCREAMING_SNAKE_CASE : Optional[Any] = tuple(state['''sep'''] )
if "cls" in state:
SCREAMING_SNAKE_CASE : Tuple = tuple(state['''cls'''] )
SCREAMING_SNAKE_CASE : str = False
if state.get('''add_prefix_space''', __UpperCAmelCase ) != add_prefix_space:
SCREAMING_SNAKE_CASE : int = add_prefix_space
SCREAMING_SNAKE_CASE : List[str] = True
if state.get('''trim_offsets''', __UpperCAmelCase ) != trim_offsets:
SCREAMING_SNAKE_CASE : Any = trim_offsets
SCREAMING_SNAKE_CASE : Dict = True
if changes_to_apply:
SCREAMING_SNAKE_CASE : Tuple = getattr(__UpperCAmelCase, state.pop('''type''' ) )
SCREAMING_SNAKE_CASE : List[Any] = component_class(**__UpperCAmelCase )
setattr(self.backend_tokenizer, __UpperCAmelCase, __UpperCAmelCase )
@property
def lowercase__ (self : int ) -> 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 lowercase__ (self : int, __UpperCAmelCase : List[str] ) -> Tuple:
"""simple docstring"""
SCREAMING_SNAKE_CASE : str = AddedToken(__UpperCAmelCase, lstrip=__UpperCAmelCase, rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase, __UpperCAmelCase ) else value
SCREAMING_SNAKE_CASE : List[str] = value
def lowercase__ (self : Optional[int], *__UpperCAmelCase : List[Any], **__UpperCAmelCase : Optional[Any] ) -> BatchEncoding:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Any = kwargs.get('''is_split_into_words''', __UpperCAmelCase )
assert self.add_prefix_space or not is_split_into_words, (
F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
"to use it with pretokenized inputs."
)
return super()._batch_encode_plus(*__UpperCAmelCase, **__UpperCAmelCase )
def lowercase__ (self : int, *__UpperCAmelCase : List[str], **__UpperCAmelCase : Tuple ) -> BatchEncoding:
"""simple docstring"""
SCREAMING_SNAKE_CASE : str = kwargs.get('''is_split_into_words''', __UpperCAmelCase )
assert self.add_prefix_space or not is_split_into_words, (
F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
"to use it with pretokenized inputs."
)
return super()._encode_plus(*__UpperCAmelCase, **__UpperCAmelCase )
def lowercase__ (self : Optional[Any], __UpperCAmelCase : str, __UpperCAmelCase : Optional[str] = None ) -> Tuple[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Any = self._tokenizer.model.save(__UpperCAmelCase, name=__UpperCAmelCase )
return tuple(__UpperCAmelCase )
def lowercase__ (self : Optional[int], __UpperCAmelCase : Dict, __UpperCAmelCase : List[str]=None ) -> Optional[Any]:
"""simple docstring"""
SCREAMING_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 lowercase__ (self : Union[str, Any], __UpperCAmelCase : List[int], __UpperCAmelCase : Optional[List[int]] = None ) -> List[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Union[str, Any] = [self.sep_token_id]
SCREAMING_SNAKE_CASE : int = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
| 507 | 0 |
from __future__ import annotations
def _a ( UpperCamelCase_ : list[float] ) -> float:
"""simple docstring"""
lowerCAmelCase__ = 0.00
lowerCAmelCase__ = 0
for resistor in resistors:
if resistor <= 0:
lowerCAmelCase__ = F"Resistor at index {index} has a negative or zero value!"
raise ValueError(UpperCamelCase_ )
first_sum += 1 / float(UpperCamelCase_ )
index += 1
return 1 / first_sum
def _a ( UpperCamelCase_ : list[float] ) -> float:
"""simple docstring"""
lowerCAmelCase__ = 0.00
lowerCAmelCase__ = 0
for resistor in resistors:
sum_r += resistor
if resistor < 0:
lowerCAmelCase__ = F"Resistor at index {index} has a negative value!"
raise ValueError(UpperCamelCase_ )
index += 1
return sum_r
if __name__ == "__main__":
import doctest
doctest.testmod()
| 702 |
import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
def _a ( UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Tuple=0.999 , UpperCamelCase_ : Union[str, Any]="cosine" , ) -> str:
"""simple docstring"""
if alpha_transform_type == "cosine":
def alpha_bar_fn(UpperCamelCase_ : List[Any] ):
return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2
elif alpha_transform_type == "exp":
def alpha_bar_fn(UpperCamelCase_ : int ):
return math.exp(t * -12.0 )
else:
raise ValueError(F"Unsupported alpha_tranform_type: {alpha_transform_type}" )
lowerCAmelCase__ = []
for i in range(UpperCamelCase_ ):
lowerCAmelCase__ = i / num_diffusion_timesteps
lowerCAmelCase__ = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar_fn(UpperCamelCase_ ) / alpha_bar_fn(UpperCamelCase_ ) , UpperCamelCase_ ) )
return torch.tensor(UpperCamelCase_ , dtype=torch.floataa )
class lowercase__ ( _UpperCAmelCase, _UpperCAmelCase ):
a_ =[e.name for e in KarrasDiffusionSchedulers]
a_ =2
@register_to_config
def __init__( self , __UpperCAmelCase = 1000 , __UpperCAmelCase = 0.00_085 , __UpperCAmelCase = 0.012 , __UpperCAmelCase = "linear" , __UpperCAmelCase = None , __UpperCAmelCase = "epsilon" , __UpperCAmelCase = "linspace" , __UpperCAmelCase = 0 , )-> int:
'''simple docstring'''
if trained_betas is not None:
lowerCAmelCase__ = torch.tensor(__UpperCAmelCase , dtype=torch.floataa )
elif beta_schedule == "linear":
lowerCAmelCase__ = torch.linspace(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , dtype=torch.floataa )
elif beta_schedule == "scaled_linear":
# this schedule is very specific to the latent diffusion model.
lowerCAmelCase__ = (
torch.linspace(beta_start**0.5 , beta_end**0.5 , __UpperCAmelCase , dtype=torch.floataa ) ** 2
)
elif beta_schedule == "squaredcos_cap_v2":
# Glide cosine schedule
lowerCAmelCase__ = betas_for_alpha_bar(__UpperCAmelCase )
else:
raise NotImplementedError(F"{beta_schedule} does is not implemented for {self.__class__}" )
lowerCAmelCase__ = 1.0 - self.betas
lowerCAmelCase__ = torch.cumprod(self.alphas , dim=0 )
# set all values
self.set_timesteps(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase=None )-> str:
'''simple docstring'''
if schedule_timesteps is None:
lowerCAmelCase__ = self.timesteps
lowerCAmelCase__ = (schedule_timesteps == timestep).nonzero()
# The sigma index that is taken for the **very** first `step`
# is always the second index (or the last index if there is only 1)
# This way we can ensure we don't accidentally skip a sigma in
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
if len(self._index_counter ) == 0:
lowerCAmelCase__ = 1 if len(__UpperCAmelCase ) > 1 else 0
else:
lowerCAmelCase__ = timestep.cpu().item() if torch.is_tensor(__UpperCAmelCase ) else timestep
lowerCAmelCase__ = self._index_counter[timestep_int]
return indices[pos].item()
@property
def UpperCAmelCase ( self )-> List[str]:
'''simple docstring'''
if self.config.timestep_spacing in ["linspace", "trailing"]:
return self.sigmas.max()
return (self.sigmas.max() ** 2 + 1) ** 0.5
def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , )-> torch.FloatTensor:
'''simple docstring'''
lowerCAmelCase__ = self.index_for_timestep(__UpperCAmelCase )
if self.state_in_first_order:
lowerCAmelCase__ = self.sigmas[step_index]
else:
lowerCAmelCase__ = self.sigmas_interpol[step_index]
lowerCAmelCase__ = sample / ((sigma**2 + 1) ** 0.5)
return sample
def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , )-> Optional[int]:
'''simple docstring'''
lowerCAmelCase__ = num_inference_steps
lowerCAmelCase__ = num_train_timesteps or self.config.num_train_timesteps
# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
if self.config.timestep_spacing == "linspace":
lowerCAmelCase__ = np.linspace(0 , num_train_timesteps - 1 , __UpperCAmelCase , dtype=__UpperCAmelCase )[::-1].copy()
elif self.config.timestep_spacing == "leading":
lowerCAmelCase__ = num_train_timesteps // self.num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
lowerCAmelCase__ = (np.arange(0 , __UpperCAmelCase ) * step_ratio).round()[::-1].copy().astype(__UpperCAmelCase )
timesteps += self.config.steps_offset
elif self.config.timestep_spacing == "trailing":
lowerCAmelCase__ = num_train_timesteps / self.num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
lowerCAmelCase__ = (np.arange(__UpperCAmelCase , 0 , -step_ratio )).round().copy().astype(__UpperCAmelCase )
timesteps -= 1
else:
raise ValueError(
F"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'." )
lowerCAmelCase__ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 )
lowerCAmelCase__ = torch.from_numpy(np.log(__UpperCAmelCase ) ).to(__UpperCAmelCase )
lowerCAmelCase__ = np.interp(__UpperCAmelCase , np.arange(0 , len(__UpperCAmelCase ) ) , __UpperCAmelCase )
lowerCAmelCase__ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa )
lowerCAmelCase__ = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase )
# interpolate sigmas
lowerCAmelCase__ = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp()
lowerCAmelCase__ = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] )
lowerCAmelCase__ = torch.cat(
[sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] )
if str(__UpperCAmelCase ).startswith("mps" ):
# mps does not support float64
lowerCAmelCase__ = torch.from_numpy(__UpperCAmelCase ).to(__UpperCAmelCase , dtype=torch.floataa )
else:
lowerCAmelCase__ = torch.from_numpy(__UpperCAmelCase ).to(__UpperCAmelCase )
# interpolate timesteps
lowerCAmelCase__ = self.sigma_to_t(__UpperCAmelCase ).to(__UpperCAmelCase , dtype=timesteps.dtype )
lowerCAmelCase__ = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten()
lowerCAmelCase__ = torch.cat([timesteps[:1], interleaved_timesteps] )
lowerCAmelCase__ = None
# for exp beta schedules, such as the one for `pipeline_shap_e.py`
# we need an index counter
lowerCAmelCase__ = defaultdict(__UpperCAmelCase )
def UpperCAmelCase ( self , __UpperCAmelCase )-> Tuple:
'''simple docstring'''
lowerCAmelCase__ = sigma.log()
# get distribution
lowerCAmelCase__ = log_sigma - self.log_sigmas[:, None]
# get sigmas range
lowerCAmelCase__ = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 )
lowerCAmelCase__ = low_idx + 1
lowerCAmelCase__ = self.log_sigmas[low_idx]
lowerCAmelCase__ = self.log_sigmas[high_idx]
# interpolate sigmas
lowerCAmelCase__ = (low - log_sigma) / (low - high)
lowerCAmelCase__ = w.clamp(0 , 1 )
# transform interpolation to time range
lowerCAmelCase__ = (1 - w) * low_idx + w * high_idx
lowerCAmelCase__ = t.view(sigma.shape )
return t
@property
def UpperCAmelCase ( self )-> List[str]:
'''simple docstring'''
return self.sample is None
def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = True , )-> Union[SchedulerOutput, Tuple]:
'''simple docstring'''
lowerCAmelCase__ = self.index_for_timestep(__UpperCAmelCase )
# advance index counter by 1
lowerCAmelCase__ = timestep.cpu().item() if torch.is_tensor(__UpperCAmelCase ) else timestep
self._index_counter[timestep_int] += 1
if self.state_in_first_order:
lowerCAmelCase__ = self.sigmas[step_index]
lowerCAmelCase__ = self.sigmas_interpol[step_index + 1]
lowerCAmelCase__ = self.sigmas[step_index + 1]
else:
# 2nd order / KDPM2's method
lowerCAmelCase__ = self.sigmas[step_index - 1]
lowerCAmelCase__ = self.sigmas_interpol[step_index]
lowerCAmelCase__ = self.sigmas[step_index]
# currently only gamma=0 is supported. This usually works best anyways.
# We can support gamma in the future but then need to scale the timestep before
# passing it to the model which requires a change in API
lowerCAmelCase__ = 0
lowerCAmelCase__ = sigma * (gamma + 1) # Note: sigma_hat == sigma for now
# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
if self.config.prediction_type == "epsilon":
lowerCAmelCase__ = sigma_hat if self.state_in_first_order else sigma_interpol
lowerCAmelCase__ = sample - sigma_input * model_output
elif self.config.prediction_type == "v_prediction":
lowerCAmelCase__ = sigma_hat if self.state_in_first_order else sigma_interpol
lowerCAmelCase__ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
sample / (sigma_input**2 + 1)
)
elif self.config.prediction_type == "sample":
raise NotImplementedError("prediction_type not implemented yet: sample" )
else:
raise ValueError(
F"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`" )
if self.state_in_first_order:
# 2. Convert to an ODE derivative for 1st order
lowerCAmelCase__ = (sample - pred_original_sample) / sigma_hat
# 3. delta timestep
lowerCAmelCase__ = sigma_interpol - sigma_hat
# store for 2nd order step
lowerCAmelCase__ = sample
else:
# DPM-Solver-2
# 2. Convert to an ODE derivative for 2nd order
lowerCAmelCase__ = (sample - pred_original_sample) / sigma_interpol
# 3. delta timestep
lowerCAmelCase__ = sigma_next - sigma_hat
lowerCAmelCase__ = self.sample
lowerCAmelCase__ = None
lowerCAmelCase__ = sample + derivative * dt
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=__UpperCAmelCase )
def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , )-> torch.FloatTensor:
'''simple docstring'''
lowerCAmelCase__ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype )
if original_samples.device.type == "mps" and torch.is_floating_point(__UpperCAmelCase ):
# mps does not support float64
lowerCAmelCase__ = self.timesteps.to(original_samples.device , dtype=torch.floataa )
lowerCAmelCase__ = timesteps.to(original_samples.device , dtype=torch.floataa )
else:
lowerCAmelCase__ = self.timesteps.to(original_samples.device )
lowerCAmelCase__ = timesteps.to(original_samples.device )
lowerCAmelCase__ = [self.index_for_timestep(__UpperCAmelCase , __UpperCAmelCase ) for t in timesteps]
lowerCAmelCase__ = sigmas[step_indices].flatten()
while len(sigma.shape ) < len(original_samples.shape ):
lowerCAmelCase__ = sigma.unsqueeze(-1 )
lowerCAmelCase__ = original_samples + noise * sigma
return noisy_samples
def __len__( self )-> List[Any]:
'''simple docstring'''
return self.config.num_train_timesteps
| 115 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
UpperCAmelCase_ : List[str] = {
"configuration_ctrl": ["CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP", "CTRLConfig"],
"tokenization_ctrl": ["CTRLTokenizer"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : int = [
"CTRL_PRETRAINED_MODEL_ARCHIVE_LIST",
"CTRLForSequenceClassification",
"CTRLLMHeadModel",
"CTRLModel",
"CTRLPreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : Optional[Any] = [
"TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFCTRLForSequenceClassification",
"TFCTRLLMHeadModel",
"TFCTRLModel",
"TFCTRLPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig
from .tokenization_ctrl import CTRLTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_ctrl import (
CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
CTRLForSequenceClassification,
CTRLLMHeadModel,
CTRLModel,
CTRLPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_ctrl import (
TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
TFCTRLForSequenceClassification,
TFCTRLLMHeadModel,
TFCTRLModel,
TFCTRLPreTrainedModel,
)
else:
import sys
UpperCAmelCase_ : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 120 |
'''simple docstring'''
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class a ( snake_case__ ):
'''simple docstring'''
__lowerCAmelCase : Optional[int] = """ClapFeatureExtractor"""
__lowerCAmelCase : str = ("""RobertaTokenizer""", """RobertaTokenizerFast""")
def __init__( self , lowerCamelCase_ , lowerCamelCase_ ) -> Union[str, Any]:
super().__init__(lowerCamelCase_ , lowerCamelCase_ )
def __call__( self , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , **lowerCamelCase_ ) -> List[Any]:
_a : Any = kwargs.pop('sampling_rate' , lowerCamelCase_ )
if text is None and audios is None:
raise ValueError('You have to specify either text or audios. Both cannot be none.' )
if text is not None:
_a : Union[str, Any] = self.tokenizer(lowerCamelCase_ , return_tensors=lowerCamelCase_ , **lowerCamelCase_ )
if audios is not None:
_a : List[str] = self.feature_extractor(
lowerCamelCase_ , sampling_rate=lowerCamelCase_ , return_tensors=lowerCamelCase_ , **lowerCamelCase_ )
if text is not None and audios is not None:
_a : List[Any] = audio_features.input_features
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**lowerCamelCase_ ) , tensor_type=lowerCamelCase_ )
def __UpperCamelCase ( self , *lowerCamelCase_ , **lowerCamelCase_ ) -> Tuple:
return self.tokenizer.batch_decode(*lowerCamelCase_ , **lowerCamelCase_ )
def __UpperCamelCase ( self , *lowerCamelCase_ , **lowerCamelCase_ ) -> List[str]:
return self.tokenizer.decode(*lowerCamelCase_ , **lowerCamelCase_ )
@property
def __UpperCamelCase ( self ) -> Tuple:
_a : Dict = self.tokenizer.model_input_names
_a : Tuple = self.feature_extractor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
| 120 | 1 |
'''simple docstring'''
def _A ( A ,A ) -> Optional[Any]:
if not len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == 3:
raise ValueError("Please enter a valid equation." )
if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0:
raise ValueError("Both a & b of two equations can\'t be zero." )
# Extract the coefficients
lowercase : Optional[Any] = equationa
lowercase : Tuple = equationa
# Calculate the determinants of the matrices
lowercase : List[Any] = aa * ba - aa * ba
lowercase : Dict = ca * ba - ca * ba
lowercase : int = aa * ca - aa * ca
# Check if the system of linear equations has a solution (using Cramer's rule)
if determinant == 0:
if determinant_x == determinant_y == 0:
raise ValueError("Infinite solutions. (Consistent system)" )
else:
raise ValueError("No solution. (Inconsistent system)" )
else:
if determinant_x == determinant_y == 0:
# Trivial solution (Inconsistent system)
return (0.0, 0.0)
else:
lowercase : Optional[int] = determinant_x / determinant
lowercase : Optional[Any] = determinant_y / determinant
# Non-Trivial Solution (Consistent system)
return (x, y)
| 703 |
'''simple docstring'''
def _A ( A ) -> list:
lowercase : Optional[Any] = False
while is_sorted is False: # Until all the indices are traversed keep looping
lowercase : List[str] = True
for i in range(0 ,len(A ) - 1 ,2 ): # iterating over all even indices
if input_list[i] > input_list[i + 1]:
lowercase , lowercase : List[Any] = input_list[i + 1], input_list[i]
# swapping if elements not in order
lowercase : Any = False
for i in range(1 ,len(A ) - 1 ,2 ): # iterating over all odd indices
if input_list[i] > input_list[i + 1]:
lowercase , lowercase : Any = input_list[i + 1], input_list[i]
# swapping if elements not in order
lowercase : Optional[int] = False
return input_list
if __name__ == "__main__":
print("""Enter list to be sorted""")
lowerCAmelCase : Optional[Any] = [int(x) for x in input().split()]
# inputing elements of the list in one line
lowerCAmelCase : str = odd_even_sort(input_list)
print("""The sorted list is""")
print(sorted_list)
| 425 | 0 |
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowerCAmelCase : str = logging.get_logger(__name__)
_lowerCAmelCase : Dict = {
'microsoft/unispeech-sat-base-100h-libri-ft': (
'https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json'
),
# See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat
}
class lowerCAmelCase ( __UpperCamelCase ):
'''simple docstring'''
snake_case = 'unispeech-sat'
def __init__( self : List[str] , __snake_case : List[Any]=32 , __snake_case : List[Any]=768 , __snake_case : Optional[int]=12 , __snake_case : List[Any]=12 , __snake_case : Any=3072 , __snake_case : Tuple="gelu" , __snake_case : Tuple=0.1 , __snake_case : Optional[int]=0.1 , __snake_case : Any=0.1 , __snake_case : str=0.0 , __snake_case : List[str]=0.0 , __snake_case : Dict=0.1 , __snake_case : Optional[Any]=0.1 , __snake_case : Optional[Any]=0.02 , __snake_case : str=1e-5 , __snake_case : Tuple="group" , __snake_case : Optional[Any]="gelu" , __snake_case : Optional[int]=(512, 512, 512, 512, 512, 512, 512) , __snake_case : List[str]=(5, 2, 2, 2, 2, 2, 2) , __snake_case : Dict=(10, 3, 3, 3, 3, 2, 2) , __snake_case : str=False , __snake_case : List[str]=128 , __snake_case : Optional[Any]=16 , __snake_case : Dict=False , __snake_case : Tuple=True , __snake_case : Optional[int]=0.05 , __snake_case : Tuple=10 , __snake_case : Dict=2 , __snake_case : Optional[Any]=0.0 , __snake_case : List[Any]=10 , __snake_case : Any=0 , __snake_case : str=320 , __snake_case : Union[str, Any]=2 , __snake_case : List[str]=0.1 , __snake_case : int=100 , __snake_case : str=256 , __snake_case : Optional[Any]=256 , __snake_case : List[Any]=0.1 , __snake_case : List[Any]="mean" , __snake_case : Tuple=False , __snake_case : Any=False , __snake_case : Tuple=256 , __snake_case : Any=(512, 512, 512, 512, 1500) , __snake_case : Any=(5, 3, 3, 1, 1) , __snake_case : Tuple=(1, 2, 3, 1, 1) , __snake_case : List[Any]=512 , __snake_case : List[str]=0 , __snake_case : Any=1 , __snake_case : List[Any]=2 , __snake_case : List[str]=504 , **__snake_case : Any , ) -> Tuple:
'''simple docstring'''
super().__init__(**__snake_case , pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case )
lowerCamelCase = hidden_size
lowerCamelCase = feat_extract_norm
lowerCamelCase = feat_extract_activation
lowerCamelCase = list(__snake_case )
lowerCamelCase = list(__snake_case )
lowerCamelCase = list(__snake_case )
lowerCamelCase = conv_bias
lowerCamelCase = num_conv_pos_embeddings
lowerCamelCase = num_conv_pos_embedding_groups
lowerCamelCase = len(self.conv_dim )
lowerCamelCase = num_hidden_layers
lowerCamelCase = intermediate_size
lowerCamelCase = hidden_act
lowerCamelCase = num_attention_heads
lowerCamelCase = hidden_dropout
lowerCamelCase = attention_dropout
lowerCamelCase = activation_dropout
lowerCamelCase = feat_proj_dropout
lowerCamelCase = final_dropout
lowerCamelCase = layerdrop
lowerCamelCase = layer_norm_eps
lowerCamelCase = initializer_range
lowerCamelCase = vocab_size
lowerCamelCase = num_clusters
lowerCamelCase = do_stable_layer_norm
lowerCamelCase = use_weighted_layer_sum
if (
(len(self.conv_stride ) != self.num_feat_extract_layers)
or (len(self.conv_kernel ) != self.num_feat_extract_layers)
or (len(self.conv_dim ) != self.num_feat_extract_layers)
):
raise ValueError(
'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =='
' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ='
F''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,'''
F''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
lowerCamelCase = apply_spec_augment
lowerCamelCase = mask_time_prob
lowerCamelCase = mask_time_length
lowerCamelCase = mask_time_min_masks
lowerCamelCase = mask_feature_prob
lowerCamelCase = mask_feature_length
lowerCamelCase = mask_feature_min_masks
# parameters for pretraining with codevector quantized representations
lowerCamelCase = num_codevectors_per_group
lowerCamelCase = num_codevector_groups
lowerCamelCase = contrastive_logits_temperature
lowerCamelCase = feat_quantizer_dropout
lowerCamelCase = num_negatives
lowerCamelCase = codevector_dim
lowerCamelCase = proj_codevector_dim
lowerCamelCase = diversity_loss_weight
# ctc loss
lowerCamelCase = ctc_loss_reduction
lowerCamelCase = ctc_zero_infinity
# SequenceClassification-specific parameter. Feel free to ignore for other classes.
lowerCamelCase = classifier_proj_size
# XVector-specific parameters. Feel free to ignore for other classes.
lowerCamelCase = list(__snake_case )
lowerCamelCase = list(__snake_case )
lowerCamelCase = list(__snake_case )
lowerCamelCase = xvector_output_dim
@property
def lowerCamelCase__ ( self : List[Any] ) -> Any:
'''simple docstring'''
return functools.reduce(operator.mul , self.conv_stride , 1 )
| 246 |
import argparse
import json
from pathlib import Path
import torch
import torchaudio
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification
from transformers.utils import logging
logging.set_verbosity_info()
_lowerCAmelCase : Dict = logging.get_logger(__name__)
def a_ ( UpperCamelCase_ : List[Any] ) -> str:
"""simple docstring"""
lowerCamelCase = ASTConfig()
if "10-10" in model_name:
pass
elif "speech-commands" in model_name:
lowerCamelCase = 1_2_8
elif "12-12" in model_name:
lowerCamelCase = 1_2
lowerCamelCase = 1_2
elif "14-14" in model_name:
lowerCamelCase = 1_4
lowerCamelCase = 1_4
elif "16-16" in model_name:
lowerCamelCase = 1_6
lowerCamelCase = 1_6
else:
raise ValueError('Model not supported' )
lowerCamelCase = 'huggingface/label-files'
if "speech-commands" in model_name:
lowerCamelCase = 3_5
lowerCamelCase = 'speech-commands-v2-id2label.json'
else:
lowerCamelCase = 5_2_7
lowerCamelCase = 'audioset-id2label.json'
lowerCamelCase = json.load(open(hf_hub_download(UpperCamelCase_ , UpperCamelCase_ , repo_type='dataset' ) , 'r' ) )
lowerCamelCase = {int(UpperCamelCase_ ): v for k, v in idalabel.items()}
lowerCamelCase = idalabel
lowerCamelCase = {v: k for k, v in idalabel.items()}
return config
def a_ ( UpperCamelCase_ : Optional[Any] ) -> Tuple:
"""simple docstring"""
if "module.v" in name:
lowerCamelCase = name.replace('module.v' , 'audio_spectrogram_transformer' )
if "cls_token" in name:
lowerCamelCase = name.replace('cls_token' , 'embeddings.cls_token' )
if "dist_token" in name:
lowerCamelCase = name.replace('dist_token' , 'embeddings.distillation_token' )
if "pos_embed" in name:
lowerCamelCase = name.replace('pos_embed' , 'embeddings.position_embeddings' )
if "patch_embed.proj" in name:
lowerCamelCase = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' )
# transformer blocks
if "blocks" in name:
lowerCamelCase = name.replace('blocks' , 'encoder.layer' )
if "attn.proj" in name:
lowerCamelCase = name.replace('attn.proj' , 'attention.output.dense' )
if "attn" in name:
lowerCamelCase = name.replace('attn' , 'attention.self' )
if "norm1" in name:
lowerCamelCase = name.replace('norm1' , 'layernorm_before' )
if "norm2" in name:
lowerCamelCase = name.replace('norm2' , 'layernorm_after' )
if "mlp.fc1" in name:
lowerCamelCase = name.replace('mlp.fc1' , 'intermediate.dense' )
if "mlp.fc2" in name:
lowerCamelCase = name.replace('mlp.fc2' , 'output.dense' )
# final layernorm
if "audio_spectrogram_transformer.norm" in name:
lowerCamelCase = name.replace('audio_spectrogram_transformer.norm' , 'audio_spectrogram_transformer.layernorm' )
# classifier head
if "module.mlp_head.0" in name:
lowerCamelCase = name.replace('module.mlp_head.0' , 'classifier.layernorm' )
if "module.mlp_head.1" in name:
lowerCamelCase = name.replace('module.mlp_head.1' , 'classifier.dense' )
return name
def a_ ( UpperCamelCase_ : List[str] , UpperCamelCase_ : Dict ) -> Tuple:
"""simple docstring"""
for key in orig_state_dict.copy().keys():
lowerCamelCase = orig_state_dict.pop(UpperCamelCase_ )
if "qkv" in key:
lowerCamelCase = key.split('.' )
lowerCamelCase = int(key_split[3] )
lowerCamelCase = config.hidden_size
if "weight" in key:
lowerCamelCase = val[:dim, :]
lowerCamelCase = val[dim : dim * 2, :]
lowerCamelCase = val[-dim:, :]
else:
lowerCamelCase = val[:dim]
lowerCamelCase = val[dim : dim * 2]
lowerCamelCase = val[-dim:]
else:
lowerCamelCase = val
return orig_state_dict
def a_ ( UpperCamelCase_ : Union[str, Any] ) -> Dict:
"""simple docstring"""
lowerCamelCase = [
'module.v.head.weight',
'module.v.head.bias',
'module.v.head_dist.weight',
'module.v.head_dist.bias',
]
for k in ignore_keys:
state_dict.pop(UpperCamelCase_ , UpperCamelCase_ )
@torch.no_grad()
def a_ ( UpperCamelCase_ : Dict , UpperCamelCase_ : Any , UpperCamelCase_ : int=False ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase = get_audio_spectrogram_transformer_config(UpperCamelCase_ )
lowerCamelCase = {
'ast-finetuned-audioset-10-10-0.4593': (
'https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1'
),
'ast-finetuned-audioset-10-10-0.450': (
'https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1'
),
'ast-finetuned-audioset-10-10-0.448': (
'https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1'
),
'ast-finetuned-audioset-10-10-0.448-v2': (
'https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1'
),
'ast-finetuned-audioset-12-12-0.447': (
'https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1'
),
'ast-finetuned-audioset-14-14-0.443': (
'https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1'
),
'ast-finetuned-audioset-16-16-0.442': (
'https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1'
),
'ast-finetuned-speech-commands-v2': (
'https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1'
),
}
# load original state_dict
lowerCamelCase = model_name_to_url[model_name]
lowerCamelCase = torch.hub.load_state_dict_from_url(UpperCamelCase_ , map_location='cpu' )
# remove some keys
remove_keys(UpperCamelCase_ )
# rename some keys
lowerCamelCase = convert_state_dict(UpperCamelCase_ , UpperCamelCase_ )
# load 🤗 model
lowerCamelCase = ASTForAudioClassification(UpperCamelCase_ )
model.eval()
model.load_state_dict(UpperCamelCase_ )
# verify outputs on dummy input
# source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62
lowerCamelCase = -4.2_677_393 if 'speech-commands' not in model_name else -6.845_978
lowerCamelCase = 4.5_689_974 if 'speech-commands' not in model_name else 5.5_654_526
lowerCamelCase = 1_0_2_4 if 'speech-commands' not in model_name else 1_2_8
lowerCamelCase = ASTFeatureExtractor(mean=UpperCamelCase_ , std=UpperCamelCase_ , max_length=UpperCamelCase_ )
if "speech-commands" in model_name:
lowerCamelCase = load_dataset('speech_commands' , 'v0.02' , split='validation' )
lowerCamelCase = dataset[0]['audio']['array']
else:
lowerCamelCase = hf_hub_download(
repo_id='nielsr/audio-spectogram-transformer-checkpoint' , filename='sample_audio.flac' , repo_type='dataset' , )
lowerCamelCase , lowerCamelCase = torchaudio.load(UpperCamelCase_ )
lowerCamelCase = waveform.squeeze().numpy()
lowerCamelCase = feature_extractor(UpperCamelCase_ , sampling_rate=1_6_0_0_0 , return_tensors='pt' )
# forward pass
lowerCamelCase = model(**UpperCamelCase_ )
lowerCamelCase = outputs.logits
if model_name == "ast-finetuned-audioset-10-10-0.4593":
lowerCamelCase = torch.tensor([-0.8_760, -7.0_042, -8.6_602] )
elif model_name == "ast-finetuned-audioset-10-10-0.450":
lowerCamelCase = torch.tensor([-1.1_986, -7.0_903, -8.2_718] )
elif model_name == "ast-finetuned-audioset-10-10-0.448":
lowerCamelCase = torch.tensor([-2.6_128, -8.0_080, -9.4_344] )
elif model_name == "ast-finetuned-audioset-10-10-0.448-v2":
lowerCamelCase = torch.tensor([-1.5_080, -7.4_534, -8.8_917] )
elif model_name == "ast-finetuned-audioset-12-12-0.447":
lowerCamelCase = torch.tensor([-0.5_050, -6.5_833, -8.0_843] )
elif model_name == "ast-finetuned-audioset-14-14-0.443":
lowerCamelCase = torch.tensor([-0.3_826, -7.0_336, -8.2_413] )
elif model_name == "ast-finetuned-audioset-16-16-0.442":
lowerCamelCase = torch.tensor([-1.2_113, -6.9_101, -8.3_470] )
elif model_name == "ast-finetuned-speech-commands-v2":
lowerCamelCase = torch.tensor([6.1_589, -8.0_566, -8.7_984] )
else:
raise ValueError('Unknown model name' )
if not torch.allclose(logits[0, :3] , UpperCamelCase_ , atol=1E-4 ):
raise ValueError('Logits don\'t match' )
print('Looks ok!' )
if pytorch_dump_folder_path is not None:
Path(UpperCamelCase_ ).mkdir(exist_ok=UpperCamelCase_ )
print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(UpperCamelCase_ )
print(f'''Saving feature extractor to {pytorch_dump_folder_path}''' )
feature_extractor.save_pretrained(UpperCamelCase_ )
if push_to_hub:
print('Pushing model and feature extractor to the hub...' )
model.push_to_hub(f'''MIT/{model_name}''' )
feature_extractor.push_to_hub(f'''MIT/{model_name}''' )
if __name__ == "__main__":
_lowerCAmelCase : Union[str, Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='ast-finetuned-audioset-10-10-0.4593',
type=str,
help='Name of the Audio Spectrogram Transformer 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.'
)
_lowerCAmelCase : Tuple = parser.parse_args()
convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 246 | 1 |
def a__ (__lowercase :str = 1000 ) -> List[Any]:
return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) )
if __name__ == "__main__":
print(solution())
| 719 |
def a__ (__lowercase :str , __lowercase :str ) -> bool:
_A : Dict = len(__lowercase ) + 1
_A : Optional[int] = len(__lowercase ) + 1
# dp is a 2d matrix where dp[i][j] denotes whether prefix string of
# length i of input_string matches with prefix string of length j of
# given pattern.
# "dp" stands for dynamic programming.
_A : Optional[Any] = [[0 for i in range(__lowercase )] for j in range(__lowercase )]
# since string of zero length match pattern of zero length
_A : int = 1
# since pattern of zero length will never match with string of non-zero length
for i in range(1 , __lowercase ):
_A : List[Any] = 0
# since string of zero length will match with pattern where there
# is at least one * alternatively
for j in range(1 , __lowercase ):
_A : List[str] = dp[0][j - 2] if pattern[j - 1] == '''*''' else 0
# now using bottom-up approach to find for all remaining lengths
for i in range(1 , __lowercase ):
for j in range(1 , __lowercase ):
if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".":
_A : Tuple = dp[i - 1][j - 1]
elif pattern[j - 1] == "*":
if dp[i][j - 2] == 1:
_A : List[str] = 1
elif pattern[j - 2] in (input_string[i - 1], "."):
_A : List[Any] = dp[i - 1][j]
else:
_A : Optional[int] = 0
else:
_A : Optional[Any] = 0
return bool(dp[-1][-1] )
if __name__ == "__main__":
import doctest
doctest.testmod()
# inputing the strings
# input_string = input("input a string :")
# pattern = input("input a pattern :")
_UpperCamelCase : Union[str, Any] ='aab'
_UpperCamelCase : Any ='c*a*b'
# using function to check whether given string matches the given pattern
if match_pattern(input_string, pattern):
print(f'''{input_string} matches the given pattern {pattern}''')
else:
print(f'''{input_string} does not match with the given pattern {pattern}''')
| 332 | 0 |
from .imports import is_tqdm_available
if is_tqdm_available():
from tqdm.auto import tqdm as _tqdm
from ..state import PartialState
def SCREAMING_SNAKE_CASE_ ( __A : str = True , *__A : Union[str, Any] , **__A : Tuple ) -> List[str]:
"""simple docstring"""
if not is_tqdm_available():
raise ImportError('Accelerate\'s `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.' )
a_ : Optional[Any] = False
if main_process_only:
a_ : Optional[int] = PartialState().local_process_index == 0
return _tqdm(*__A , **__A , disable=__A )
| 570 |
'''simple docstring'''
import os
import pytest
from datasets import (
get_dataset_config_info,
get_dataset_config_names,
get_dataset_infos,
get_dataset_split_names,
inspect_dataset,
inspect_metric,
)
_UpperCAmelCase : Optional[int] = pytest.mark.integration
@pytest.mark.parametrize('''path''' ,['''paws''', '''csv'''] )
def snake_case__ ( UpperCamelCase ,UpperCamelCase ) -> Dict:
inspect_dataset(UpperCamelCase ,UpperCamelCase )
_UpperCamelCase : Optional[Any] = path + '''.py'''
assert script_name in os.listdir(UpperCamelCase )
assert "__pycache__" not in os.listdir(UpperCamelCase )
@pytest.mark.filterwarnings('''ignore:inspect_metric is deprecated:FutureWarning''' )
@pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' )
@pytest.mark.parametrize('''path''' ,['''accuracy'''] )
def snake_case__ ( UpperCamelCase ,UpperCamelCase ) -> int:
inspect_metric(UpperCamelCase ,UpperCamelCase )
_UpperCamelCase : List[str] = path + '''.py'''
assert script_name in os.listdir(UpperCamelCase )
assert "__pycache__" not in os.listdir(UpperCamelCase )
@pytest.mark.parametrize(
'''path, config_name, expected_splits''' ,[
('''squad''', '''plain_text''', ['''train''', '''validation''']),
('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']),
('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']),
] ,)
def snake_case__ ( UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) -> int:
_UpperCamelCase : List[str] = get_dataset_config_info(UpperCamelCase ,config_name=UpperCamelCase )
assert info.config_name == config_name
assert list(info.splits.keys() ) == expected_splits
@pytest.mark.parametrize(
'''path, config_name, expected_exception''' ,[
('''paws''', None, ValueError),
] ,)
def snake_case__ ( UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) -> List[str]:
with pytest.raises(UpperCamelCase ):
get_dataset_config_info(UpperCamelCase ,config_name=UpperCamelCase )
@pytest.mark.parametrize(
'''path, expected''' ,[
('''squad''', '''plain_text'''),
('''acronym_identification''', '''default'''),
('''lhoestq/squad''', '''plain_text'''),
('''lhoestq/test''', '''default'''),
('''lhoestq/demo1''', '''lhoestq--demo1'''),
('''dalle-mini/wit''', '''dalle-mini--wit'''),
] ,)
def snake_case__ ( UpperCamelCase ,UpperCamelCase ) -> Union[str, Any]:
_UpperCamelCase : int = get_dataset_config_names(UpperCamelCase )
assert expected in config_names
@pytest.mark.parametrize(
'''path, expected_configs, expected_splits_in_first_config''' ,[
('''squad''', ['''plain_text'''], ['''train''', '''validation''']),
('''dalle-mini/wit''', ['''dalle-mini--wit'''], ['''train''']),
('''paws''', ['''labeled_final''', '''labeled_swap''', '''unlabeled_final'''], ['''train''', '''test''', '''validation''']),
] ,)
def snake_case__ ( UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) -> Dict:
_UpperCamelCase : Dict = get_dataset_infos(UpperCamelCase )
assert list(infos.keys() ) == expected_configs
_UpperCamelCase : Dict = expected_configs[0]
assert expected_config in infos
_UpperCamelCase : Any = infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys() ) == expected_splits_in_first_config
@pytest.mark.parametrize(
'''path, expected_config, expected_splits''' ,[
('''squad''', '''plain_text''', ['''train''', '''validation''']),
('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']),
('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']),
] ,)
def snake_case__ ( UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) -> Union[str, Any]:
_UpperCamelCase : List[Any] = get_dataset_infos(UpperCamelCase )
assert expected_config in infos
_UpperCamelCase : Union[str, Any] = infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys() ) == expected_splits
@pytest.mark.parametrize(
'''path, config_name, expected_exception''' ,[
('''paws''', None, ValueError),
] ,)
def snake_case__ ( UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) -> List[Any]:
with pytest.raises(UpperCamelCase ):
get_dataset_split_names(UpperCamelCase ,config_name=UpperCamelCase )
| 683 | 0 |
'''simple docstring'''
from __future__ import annotations
def snake_case__ ( _A: int , _A: int ) -> tuple[int, int]:
'''simple docstring'''
if b == 0:
return (1, 0)
((lowerCAmelCase) , (lowerCAmelCase)) = extended_euclid(_A , a % b )
lowerCAmelCase = a // b
return (y, x - k * y)
def snake_case__ ( _A: int , _A: int , _A: int , _A: int ) -> int:
'''simple docstring'''
((lowerCAmelCase) , (lowerCAmelCase)) = extended_euclid(_A , _A )
lowerCAmelCase = na * na
lowerCAmelCase = ra * x * na + ra * y * na
return (n % m + m) % m
def snake_case__ ( _A: int , _A: int ) -> int:
'''simple docstring'''
((lowerCAmelCase) , (lowerCAmelCase)) = extended_euclid(_A , _A )
if b < 0:
lowerCAmelCase = (b % n + n) % n
return b
def snake_case__ ( _A: int , _A: int , _A: int , _A: int ) -> int:
'''simple docstring'''
lowerCAmelCase , lowerCAmelCase = invert_modulo(_A , _A ), invert_modulo(_A , _A )
lowerCAmelCase = na * na
lowerCAmelCase = ra * x * na + ra * y * na
return (n % m + m) % m
if __name__ == "__main__":
from doctest import testmod
testmod(name='''chinese_remainder_theorem''', verbose=True)
testmod(name='''chinese_remainder_theorem2''', verbose=True)
testmod(name='''invert_modulo''', verbose=True)
testmod(name='''extended_euclid''', verbose=True)
| 605 | '''simple docstring'''
from __future__ import annotations
from typing import Any
def snake_case__ ( _A: list ) -> int:
'''simple docstring'''
if not postfix_notation:
return 0
lowerCAmelCase = {"""+""", """-""", """*""", """/"""}
lowerCAmelCase = []
for token in postfix_notation:
if token in operations:
lowerCAmelCase , lowerCAmelCase = stack.pop(), stack.pop()
if token == "+":
stack.append(a + b )
elif token == "-":
stack.append(a - b )
elif token == "*":
stack.append(a * b )
else:
if a * b < 0 and a % b != 0:
stack.append(a // b + 1 )
else:
stack.append(a // b )
else:
stack.append(int(_A ) )
return stack.pop()
if __name__ == "__main__":
import doctest
doctest.testmod()
| 605 | 1 |
from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline
else:
from .pipeline_kandinsky import KandinskyPipeline
from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline
from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline
from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput
from .text_encoder import MultilingualCLIP
| 55 |
import gc
import unittest
import numpy as np
import torch
from torch.backends.cuda import sdp_kernel
from diffusers import (
CMStochasticIterativeScheduler,
ConsistencyModelPipeline,
UNetaDModel,
)
from diffusers.utils import randn_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu
from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class __lowercase ( a_ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase : List[str] = ConsistencyModelPipeline
UpperCamelCase : int = UNCONDITIONAL_IMAGE_GENERATION_PARAMS
UpperCamelCase : Any = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
# Override required_optional_params to remove num_images_per_prompt
UpperCamelCase : Optional[int] = frozenset(
[
"num_inference_steps",
"generator",
"latents",
"output_type",
"return_dict",
"callback",
"callback_steps",
] )
@property
def __A ( self ) -> Optional[int]:
'''simple docstring'''
lowerCamelCase = UNetaDModel.from_pretrained(
"""diffusers/consistency-models-test""" , subfolder="""test_unet""" , )
return unet
@property
def __A ( self ) -> str:
'''simple docstring'''
lowerCamelCase = UNetaDModel.from_pretrained(
"""diffusers/consistency-models-test""" , subfolder="""test_unet_class_cond""" , )
return unet
def __A ( self , A=False ) -> Tuple:
'''simple docstring'''
if class_cond:
lowerCamelCase = self.dummy_cond_unet
else:
lowerCamelCase = self.dummy_uncond_unet
# Default to CM multistep sampler
lowerCamelCase = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , )
lowerCamelCase = {
"""unet""": unet,
"""scheduler""": scheduler,
}
return components
def __A ( self , A , A=0 ) -> List[str]:
'''simple docstring'''
if str(A ).startswith("""mps""" ):
lowerCamelCase = torch.manual_seed(A )
else:
lowerCamelCase = torch.Generator(device=A ).manual_seed(A )
lowerCamelCase = {
"""batch_size""": 1,
"""num_inference_steps""": None,
"""timesteps""": [22, 0],
"""generator""": generator,
"""output_type""": """np""",
}
return inputs
def __A ( self ) -> Optional[Any]:
'''simple docstring'''
lowerCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator
lowerCamelCase = self.get_dummy_components()
lowerCamelCase = ConsistencyModelPipeline(**A )
lowerCamelCase = pipe.to(A )
pipe.set_progress_bar_config(disable=A )
lowerCamelCase = self.get_dummy_inputs(A )
lowerCamelCase = pipe(**A ).images
assert image.shape == (1, 32, 32, 3)
lowerCamelCase = image[0, -3:, -3:, -1]
lowerCamelCase = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
def __A ( self ) -> Dict:
'''simple docstring'''
lowerCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator
lowerCamelCase = self.get_dummy_components(class_cond=A )
lowerCamelCase = ConsistencyModelPipeline(**A )
lowerCamelCase = pipe.to(A )
pipe.set_progress_bar_config(disable=A )
lowerCamelCase = self.get_dummy_inputs(A )
lowerCamelCase = 0
lowerCamelCase = pipe(**A ).images
assert image.shape == (1, 32, 32, 3)
lowerCamelCase = image[0, -3:, -3:, -1]
lowerCamelCase = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
def __A ( self ) -> List[Any]:
'''simple docstring'''
lowerCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator
lowerCamelCase = self.get_dummy_components()
lowerCamelCase = ConsistencyModelPipeline(**A )
lowerCamelCase = pipe.to(A )
pipe.set_progress_bar_config(disable=A )
lowerCamelCase = self.get_dummy_inputs(A )
lowerCamelCase = 1
lowerCamelCase = None
lowerCamelCase = pipe(**A ).images
assert image.shape == (1, 32, 32, 3)
lowerCamelCase = image[0, -3:, -3:, -1]
lowerCamelCase = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
def __A ( self ) -> List[str]:
'''simple docstring'''
lowerCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator
lowerCamelCase = self.get_dummy_components(class_cond=A )
lowerCamelCase = ConsistencyModelPipeline(**A )
lowerCamelCase = pipe.to(A )
pipe.set_progress_bar_config(disable=A )
lowerCamelCase = self.get_dummy_inputs(A )
lowerCamelCase = 1
lowerCamelCase = None
lowerCamelCase = 0
lowerCamelCase = pipe(**A ).images
assert image.shape == (1, 32, 32, 3)
lowerCamelCase = image[0, -3:, -3:, -1]
lowerCamelCase = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
@slow
@require_torch_gpu
class __lowercase ( unittest.TestCase ):
"""simple docstring"""
def __A ( self ) -> Optional[Any]:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __A ( self , A=0 , A=False , A="cpu" , A=torch.floataa , A=(1, 3, 64, 64) ) -> Optional[int]:
'''simple docstring'''
lowerCamelCase = torch.manual_seed(A )
lowerCamelCase = {
"""num_inference_steps""": None,
"""timesteps""": [22, 0],
"""class_labels""": 0,
"""generator""": generator,
"""output_type""": """np""",
}
if get_fixed_latents:
lowerCamelCase = self.get_fixed_latents(seed=A , device=A , dtype=A , shape=A )
lowerCamelCase = latents
return inputs
def __A ( self , A=0 , A="cpu" , A=torch.floataa , A=(1, 3, 64, 64) ) -> Union[str, Any]:
'''simple docstring'''
if type(A ) == str:
lowerCamelCase = torch.device(A )
lowerCamelCase = torch.Generator(device=A ).manual_seed(A )
lowerCamelCase = randn_tensor(A , generator=A , device=A , dtype=A )
return latents
def __A ( self ) -> str:
'''simple docstring'''
lowerCamelCase = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" )
lowerCamelCase = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , )
lowerCamelCase = ConsistencyModelPipeline(unet=A , scheduler=A )
pipe.to(torch_device=A )
pipe.set_progress_bar_config(disable=A )
lowerCamelCase = self.get_inputs()
lowerCamelCase = pipe(**A ).images
assert image.shape == (1, 64, 64, 3)
lowerCamelCase = image[0, -3:, -3:, -1]
lowerCamelCase = np.array([0.0888, 0.0881, 0.0666, 0.0479, 0.0292, 0.0195, 0.0201, 0.0163, 0.0254] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
def __A ( self ) -> Optional[Any]:
'''simple docstring'''
lowerCamelCase = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" )
lowerCamelCase = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , )
lowerCamelCase = ConsistencyModelPipeline(unet=A , scheduler=A )
pipe.to(torch_device=A )
pipe.set_progress_bar_config(disable=A )
lowerCamelCase = self.get_inputs()
lowerCamelCase = 1
lowerCamelCase = None
lowerCamelCase = pipe(**A ).images
assert image.shape == (1, 64, 64, 3)
lowerCamelCase = image[0, -3:, -3:, -1]
lowerCamelCase = np.array([0.0340, 0.0152, 0.0063, 0.0267, 0.0221, 0.0107, 0.0416, 0.0186, 0.0217] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
@require_torch_a
def __A ( self ) -> Any:
'''simple docstring'''
lowerCamelCase = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" )
lowerCamelCase = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , )
lowerCamelCase = ConsistencyModelPipeline(unet=A , scheduler=A )
pipe.to(torch_device=A , torch_dtype=torch.floataa )
pipe.set_progress_bar_config(disable=A )
lowerCamelCase = self.get_inputs(get_fixed_latents=A , device=A )
# Ensure usage of flash attention in torch 2.0
with sdp_kernel(enable_flash=A , enable_math=A , enable_mem_efficient=A ):
lowerCamelCase = pipe(**A ).images
assert image.shape == (1, 64, 64, 3)
lowerCamelCase = image[0, -3:, -3:, -1]
lowerCamelCase = np.array([0.1875, 0.1428, 0.1289, 0.2151, 0.2092, 0.1477, 0.1877, 0.1641, 0.1353] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
@require_torch_a
def __A ( self ) -> List[Any]:
'''simple docstring'''
lowerCamelCase = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" )
lowerCamelCase = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , )
lowerCamelCase = ConsistencyModelPipeline(unet=A , scheduler=A )
pipe.to(torch_device=A , torch_dtype=torch.floataa )
pipe.set_progress_bar_config(disable=A )
lowerCamelCase = self.get_inputs(get_fixed_latents=A , device=A )
lowerCamelCase = 1
lowerCamelCase = None
# Ensure usage of flash attention in torch 2.0
with sdp_kernel(enable_flash=A , enable_math=A , enable_mem_efficient=A ):
lowerCamelCase = pipe(**A ).images
assert image.shape == (1, 64, 64, 3)
lowerCamelCase = image[0, -3:, -3:, -1]
lowerCamelCase = np.array([0.1663, 0.1948, 0.2275, 0.1680, 0.1204, 0.1245, 0.1858, 0.1338, 0.2095] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
| 457 | 0 |
import logging
import os
from typing import Dict, List, Optional, Union
import torch
import torch.nn as nn
from accelerate.utils.imports import (
is_abit_bnb_available,
is_abit_bnb_available,
is_bnb_available,
)
from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
find_tied_parameters,
get_balanced_memory,
infer_auto_device_map,
load_checkpoint_in_model,
offload_weight,
set_module_tensor_to_device,
)
if is_bnb_available():
import bitsandbytes as bnb
from copy import deepcopy
lowercase : Tuple = logging.getLogger(__name__)
def UpperCAmelCase_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = False , ):
lowerCamelCase_: Optional[int] = bnb_quantization_config.load_in_abit
lowerCamelCase_: Optional[Any] = bnb_quantization_config.load_in_abit
if load_in_abit and not is_abit_bnb_available():
raise ImportError(
"""You have a version of `bitsandbytes` that is not compatible with 8bit quantization,"""
""" make sure you have the latest version of `bitsandbytes` installed.""" )
if load_in_abit and not is_abit_bnb_available():
raise ValueError(
"""You have a version of `bitsandbytes` that is not compatible with 4bit quantization,"""
"""make sure you have the latest version of `bitsandbytes` installed.""" )
lowerCamelCase_: int = []
# custom device map
if isinstance(_UpperCAmelCase , _UpperCAmelCase ) and len(device_map.keys() ) > 1:
lowerCamelCase_: Tuple = [key for key, value in device_map.items() if value in ["""disk""", """cpu"""]]
# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
if bnb_quantization_config.skip_modules is None:
lowerCamelCase_: List[Any] = get_keys_to_not_convert(_UpperCAmelCase )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(_UpperCAmelCase )
lowerCamelCase_: Optional[int] = bnb_quantization_config.skip_modules
# We add the modules we want to keep in full precision
if bnb_quantization_config.keep_in_fpaa_modules is None:
lowerCamelCase_: int = []
lowerCamelCase_: Optional[int] = bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(_UpperCAmelCase )
# compatibility with peft
lowerCamelCase_: Optional[Any] = load_in_abit
lowerCamelCase_: Tuple = load_in_abit
lowerCamelCase_: Any = get_parameter_device(_UpperCAmelCase )
if model_device.type != "meta":
# quantization of an already loaded model
logger.warning(
"""It is not recommended to quantize a loaded model. """
"""The model should be instantiated under the `init_empty_weights` context manager.""" )
lowerCamelCase_: Union[str, Any] = replace_with_bnb_layers(_UpperCAmelCase , _UpperCAmelCase , modules_to_not_convert=_UpperCAmelCase )
# convert param to the right dtype
lowerCamelCase_: Tuple = bnb_quantization_config.torch_dtype
for name, param in model.state_dict().items():
if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ):
param.to(torch.floataa )
if param.dtype != torch.floataa:
lowerCamelCase_: List[str] = name.replace(""".weight""" , """""" ).replace(""".bias""" , """""" )
lowerCamelCase_: List[str] = getattr(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(_UpperCAmelCase ):
param.to(_UpperCAmelCase )
if model_device.type == "cuda":
# move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
model.cuda(torch.cuda.current_device() )
torch.cuda.empty_cache()
elif torch.cuda.is_available():
model.to(torch.cuda.current_device() )
else:
raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" )
logger.info(
f"""The model device type is {model_device.type}. However, cuda is needed for quantization."""
"""We move the model to cuda.""" )
return model
elif weights_location is None:
raise RuntimeError(
f"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ )
else:
with init_empty_weights():
lowerCamelCase_: Dict = replace_with_bnb_layers(
_UpperCAmelCase , _UpperCAmelCase , modules_to_not_convert=_UpperCAmelCase )
lowerCamelCase_: Dict = get_quantized_model_device_map(
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , max_memory=_UpperCAmelCase , no_split_module_classes=_UpperCAmelCase , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
lowerCamelCase_: Optional[Any] = True
lowerCamelCase_: List[str] = any(x in list(device_map.values() ) for x in ["""cpu""", """disk"""] )
load_checkpoint_in_model(
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , dtype=bnb_quantization_config.torch_dtype , offload_folder=_UpperCAmelCase , offload_state_dict=_UpperCAmelCase , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(_UpperCAmelCase , device_map=_UpperCAmelCase , offload_dir=_UpperCAmelCase )
def UpperCAmelCase_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None ):
if device_map is None:
if torch.cuda.is_available():
lowerCamelCase_: Any = {"""""": torch.cuda.current_device()}
else:
raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" )
logger.info("""The device_map was not initialized.""" """Setting device_map to `{'':torch.cuda.current_device()}`.""" )
if isinstance(_UpperCAmelCase , _UpperCAmelCase ):
if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
raise ValueError(
"""If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or """
"""'sequential'.""" )
lowerCamelCase_: Union[str, Any] = {}
special_dtypes.update(
{
name: bnb_quantization_config.torch_dtype
for name, _ in model.named_parameters()
if any(m in name for m in bnb_quantization_config.skip_modules )
} )
special_dtypes.update(
{
name: torch.floataa
for name, _ in model.named_parameters()
if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules )
} )
lowerCamelCase_: Any = {}
lowerCamelCase_: List[str] = special_dtypes
lowerCamelCase_: Tuple = no_split_module_classes
lowerCamelCase_: int = bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
lowerCamelCase_: Optional[int] = get_balanced_memory(
_UpperCAmelCase , low_zero=(device_map == """balanced_low_0""") , max_memory=_UpperCAmelCase , **_UpperCAmelCase , )
lowerCamelCase_: List[Any] = max_memory
lowerCamelCase_: Any = infer_auto_device_map(_UpperCAmelCase , **_UpperCAmelCase )
if isinstance(_UpperCAmelCase , _UpperCAmelCase ):
# check if don't have any quantized module on the cpu
lowerCamelCase_: Tuple = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
lowerCamelCase_: Optional[Any] = {
key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
}
for device in ["cpu", "disk"]:
if device in device_map_without_some_modules.values():
if bnb_quantization_config.load_in_abit:
raise ValueError(
"""
Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit
the quantized model. If you want to dispatch the model on the CPU or the disk while keeping
these modules in `torch_dtype`, you need to pass a custom `device_map` to
`load_and_quantize_model`. Check
https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk
for more details.
""" )
else:
logger.info(
"""Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit""" )
del device_map_without_some_modules
return device_map
def UpperCAmelCase_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None ):
if modules_to_not_convert is None:
lowerCamelCase_: Any = []
lowerCamelCase_ , lowerCamelCase_: Optional[int] = _replace_with_bnb_layers(
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
if not has_been_replaced:
logger.warning(
"""You are loading your model in 8bit or 4bit but no linear modules were found in your model."""
""" this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers."""
""" Please double check your model architecture, or submit an issue on github if you think this is"""
""" a bug.""" )
return model
def UpperCAmelCase_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , ):
lowerCamelCase_: Union[str, Any] = False
for name, module in model.named_children():
if current_key_name is None:
lowerCamelCase_: Dict = []
current_key_name.append(_UpperCAmelCase )
if isinstance(_UpperCAmelCase , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
lowerCamelCase_: Optional[int] = """.""".join(_UpperCAmelCase )
lowerCamelCase_: Dict = True
for key in modules_to_not_convert:
if (
(key in current_key_name_str) and (key + "." in current_key_name_str)
) or key == current_key_name_str:
lowerCamelCase_: str = False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
lowerCamelCase_: Optional[int] = bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=_UpperCAmelCase , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
lowerCamelCase_: Dict = bnb.nn.Linearabit(
module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , )
else:
raise ValueError("""load_in_8bit and load_in_4bit can't be both False""" )
lowerCamelCase_: str = module.weight.data
if module.bias is not None:
lowerCamelCase_: Union[str, Any] = module.bias.data
bnb_module.requires_grad_(_UpperCAmelCase )
setattr(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
lowerCamelCase_: int = True
if len(list(module.children() ) ) > 0:
lowerCamelCase_ , lowerCamelCase_: Optional[int] = _replace_with_bnb_layers(
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
lowerCamelCase_: Tuple = has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def UpperCAmelCase_ ( _UpperCAmelCase ):
# Create a copy of the model
with init_empty_weights():
lowerCamelCase_: Tuple = deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
lowerCamelCase_: Union[str, Any] = find_tied_parameters(_UpperCAmelCase )
# For compatibility with Accelerate < 0.18
if isinstance(_UpperCAmelCase , _UpperCAmelCase ):
lowerCamelCase_: Union[str, Any] = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
lowerCamelCase_: Optional[Any] = sum(_UpperCAmelCase , [] )
lowerCamelCase_: int = len(_UpperCAmelCase ) > 0
# Check if it is a base model
lowerCamelCase_: int = False
if hasattr(_UpperCAmelCase , """base_model_prefix""" ):
lowerCamelCase_: Tuple = not hasattr(_UpperCAmelCase , model.base_model_prefix )
# Ignore this for base models (BertModel, GPT2Model, etc.)
if (not has_tied_params) and is_base_model:
return []
# otherwise they have an attached head
lowerCamelCase_: Optional[Any] = list(model.named_children() )
lowerCamelCase_: List[Any] = [list_modules[-1][0]]
# add last module together with tied weights
lowerCamelCase_: Tuple = set(_UpperCAmelCase ) - set(_UpperCAmelCase )
lowerCamelCase_: Any = list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase )
# remove ".weight" from the keys
lowerCamelCase_: int = [""".weight""", """.bias"""]
lowerCamelCase_: Tuple = []
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
lowerCamelCase_: List[str] = name.replace(_UpperCAmelCase , """""" )
filtered_module_names.append(_UpperCAmelCase )
return filtered_module_names
def UpperCAmelCase_ ( _UpperCAmelCase ):
for m in model.modules():
if isinstance(_UpperCAmelCase , bnb.nn.Linearabit ):
return True
return False
def UpperCAmelCase_ ( _UpperCAmelCase ):
return next(parameter.parameters() ).device
def UpperCAmelCase_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ):
# if it is not quantized, we quantize and offload the quantized weights and the SCB stats
if fpaa_statistics is None:
set_module_tensor_to_device(_UpperCAmelCase , _UpperCAmelCase , 0 , dtype=_UpperCAmelCase , value=_UpperCAmelCase )
lowerCamelCase_: Any = param_name
lowerCamelCase_: Optional[int] = model
if "." in tensor_name:
lowerCamelCase_: List[Any] = tensor_name.split(""".""" )
for split in splits[:-1]:
lowerCamelCase_: List[str] = getattr(_UpperCAmelCase , _UpperCAmelCase )
if new_module is None:
raise ValueError(f"""{module} has no attribute {split}.""" )
lowerCamelCase_: Optional[Any] = new_module
lowerCamelCase_: List[str] = splits[-1]
# offload weights
lowerCamelCase_: Optional[Any] = False
offload_weight(module._parameters[tensor_name] , _UpperCAmelCase , _UpperCAmelCase , index=_UpperCAmelCase )
if hasattr(module._parameters[tensor_name] , """SCB""" ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace("""weight""" , """SCB""" ) , _UpperCAmelCase , index=_UpperCAmelCase , )
else:
offload_weight(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , index=_UpperCAmelCase )
offload_weight(_UpperCAmelCase , param_name.replace("""weight""" , """SCB""" ) , _UpperCAmelCase , index=_UpperCAmelCase )
set_module_tensor_to_device(_UpperCAmelCase , _UpperCAmelCase , """meta""" , dtype=_UpperCAmelCase , value=torch.empty(*param.size() ) )
| 584 | import argparse
import json
import os
import sys
import tempfile
import unittest
from argparse import Namespace
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import List, Literal, Optional
import yaml
from transformers import HfArgumentParser, TrainingArguments
from transformers.hf_argparser import make_choice_type_function, string_to_bool
# Since Python 3.10, we can use the builtin `|` operator for Union types
# See PEP 604: https://peps.python.org/pep-0604
lowercase : str = sys.version_info >= (3, 1_0)
def UpperCAmelCase_ ( _UpperCAmelCase=None , _UpperCAmelCase=None ):
return field(default_factory=lambda: default , metadata=_UpperCAmelCase )
@dataclass
class a__ :
_A = 42
_A = 42
_A = 42
_A = 42
@dataclass
class a__ :
_A = 42
_A = field(default="toto" , metadata={"help": "help message"} )
@dataclass
class a__ :
_A = False
_A = True
_A = None
class a__ ( __SCREAMING_SNAKE_CASE ):
_A = "titi"
_A = "toto"
class a__ ( __SCREAMING_SNAKE_CASE ):
_A = "titi"
_A = "toto"
_A = 42
@dataclass
class a__ :
_A = "toto"
def lowerCAmelCase ( self : Union[str, Any] ) -> Any:
"""simple docstring"""
lowerCamelCase_: Any = BasicEnum(self.foo )
@dataclass
class a__ :
_A = "toto"
def lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase_: Optional[int] = MixedTypeEnum(self.foo )
@dataclass
class a__ :
_A = None
_A = field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "help message"} )
_A = None
_A = list_field(default=[] )
_A = list_field(default=[] )
@dataclass
class a__ :
_A = list_field(default=[] )
_A = list_field(default=[1, 2, 3] )
_A = list_field(default=["Hallo", "Bonjour", "Hello"] )
_A = list_field(default=[0.1, 0.2, 0.3] )
@dataclass
class a__ :
_A = field()
_A = field()
_A = field()
def lowerCAmelCase ( self : Optional[int] ) -> Union[str, Any]:
"""simple docstring"""
lowerCamelCase_: int = BasicEnum(self.required_enum )
@dataclass
class a__ :
_A = 42
_A = field()
_A = None
_A = field(default="toto" , metadata={"help": "help message"} )
_A = list_field(default=["Hallo", "Bonjour", "Hello"] )
if is_python_no_less_than_3_10:
@dataclass
class a__ :
_A = False
_A = True
_A = None
@dataclass
class a__ :
_A = None
_A = field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "help message"} )
_A = None
_A = list_field(default=[] )
_A = list_field(default=[] )
class a__ ( unittest.TestCase ):
def lowerCAmelCase ( self : Any , A_ : argparse.ArgumentParser , A_ : argparse.ArgumentParser ) -> List[Any]:
"""simple docstring"""
self.assertEqual(len(a._actions ) , len(b._actions ) )
for x, y in zip(a._actions , b._actions ):
lowerCamelCase_: Any = {k: v for k, v in vars(A_ ).items() if k != """container"""}
lowerCamelCase_: Any = {k: v for k, v in vars(A_ ).items() if k != """container"""}
# Choices with mixed type have custom function as "type"
# So we need to compare results directly for equality
if xx.get("""choices""" , A_ ) and yy.get("""choices""" , A_ ):
for expected_choice in yy["choices"] + xx["choices"]:
self.assertEqual(xx["""type"""](A_ ) , yy["""type"""](A_ ) )
del xx["type"], yy["type"]
self.assertEqual(A_ , A_ )
def lowerCAmelCase ( self : Dict ) -> Union[str, Any]:
"""simple docstring"""
lowerCamelCase_: str = HfArgumentParser(A_ )
lowerCamelCase_: str = argparse.ArgumentParser()
expected.add_argument("""--foo""" , type=A_ , required=A_ )
expected.add_argument("""--bar""" , type=A_ , required=A_ )
expected.add_argument("""--baz""" , type=A_ , required=A_ )
expected.add_argument("""--flag""" , type=A_ , default=A_ , const=A_ , nargs="""?""" )
self.argparsersEqual(A_ , A_ )
lowerCamelCase_: List[Any] = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""]
((lowerCamelCase_) , ): int = parser.parse_args_into_dataclasses(A_ , look_for_args_file=A_ )
self.assertFalse(example.flag )
def lowerCAmelCase ( self : Any ) -> Dict:
"""simple docstring"""
lowerCamelCase_: int = HfArgumentParser(A_ )
lowerCamelCase_: int = argparse.ArgumentParser()
expected.add_argument("""--foo""" , default=42 , type=A_ )
expected.add_argument("""--baz""" , default="""toto""" , type=A_ , help="""help message""" )
self.argparsersEqual(A_ , A_ )
def lowerCAmelCase ( self : int ) -> Dict:
"""simple docstring"""
lowerCamelCase_: Optional[Any] = argparse.ArgumentParser()
expected.add_argument("""--foo""" , type=A_ , default=A_ , const=A_ , nargs="""?""" )
expected.add_argument("""--baz""" , type=A_ , default=A_ , const=A_ , nargs="""?""" )
# A boolean no_* argument always has to come after its "default: True" regular counter-part
# and its default must be set to False
expected.add_argument("""--no_baz""" , action="""store_false""" , default=A_ , dest="""baz""" )
expected.add_argument("""--opt""" , type=A_ , default=A_ )
lowerCamelCase_: int = [WithDefaultBoolExample]
if is_python_no_less_than_3_10:
dataclass_types.append(A_ )
for dataclass_type in dataclass_types:
lowerCamelCase_: Any = HfArgumentParser(A_ )
self.argparsersEqual(A_ , A_ )
lowerCamelCase_: int = parser.parse_args([] )
self.assertEqual(A_ , Namespace(foo=A_ , baz=A_ , opt=A_ ) )
lowerCamelCase_: List[str] = parser.parse_args(["""--foo""", """--no_baz"""] )
self.assertEqual(A_ , Namespace(foo=A_ , baz=A_ , opt=A_ ) )
lowerCamelCase_: List[str] = parser.parse_args(["""--foo""", """--baz"""] )
self.assertEqual(A_ , Namespace(foo=A_ , baz=A_ , opt=A_ ) )
lowerCamelCase_: List[Any] = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""] )
self.assertEqual(A_ , Namespace(foo=A_ , baz=A_ , opt=A_ ) )
lowerCamelCase_: int = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""] )
self.assertEqual(A_ , Namespace(foo=A_ , baz=A_ , opt=A_ ) )
def lowerCAmelCase ( self : int ) -> str:
"""simple docstring"""
lowerCamelCase_: int = HfArgumentParser(A_ )
lowerCamelCase_: str = argparse.ArgumentParser()
expected.add_argument(
"""--foo""" , default="""toto""" , choices=["""titi""", """toto""", 42] , type=make_choice_type_function(["""titi""", """toto""", 42] ) , )
self.argparsersEqual(A_ , A_ )
lowerCamelCase_: Union[str, Any] = parser.parse_args([] )
self.assertEqual(args.foo , """toto""" )
lowerCamelCase_: List[str] = parser.parse_args_into_dataclasses([] )[0]
self.assertEqual(enum_ex.foo , MixedTypeEnum.toto )
lowerCamelCase_: List[Any] = parser.parse_args(["""--foo""", """titi"""] )
self.assertEqual(args.foo , """titi""" )
lowerCamelCase_: Union[str, Any] = parser.parse_args_into_dataclasses(["""--foo""", """titi"""] )[0]
self.assertEqual(enum_ex.foo , MixedTypeEnum.titi )
lowerCamelCase_: Any = parser.parse_args(["""--foo""", """42"""] )
self.assertEqual(args.foo , 42 )
lowerCamelCase_: Union[str, Any] = parser.parse_args_into_dataclasses(["""--foo""", """42"""] )[0]
self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo )
def lowerCAmelCase ( self : Dict ) -> Dict:
"""simple docstring"""
@dataclass
class a__ :
_A = "toto"
lowerCamelCase_: Union[str, Any] = HfArgumentParser(A_ )
lowerCamelCase_: List[Any] = argparse.ArgumentParser()
expected.add_argument(
"""--foo""" , default="""toto""" , choices=("""titi""", """toto""", 42) , type=make_choice_type_function(["""titi""", """toto""", 42] ) , )
self.argparsersEqual(A_ , A_ )
lowerCamelCase_: List[str] = parser.parse_args([] )
self.assertEqual(args.foo , """toto""" )
lowerCamelCase_: Any = parser.parse_args(["""--foo""", """titi"""] )
self.assertEqual(args.foo , """titi""" )
lowerCamelCase_: Optional[Any] = parser.parse_args(["""--foo""", """42"""] )
self.assertEqual(args.foo , 42 )
def lowerCAmelCase ( self : str ) -> Tuple:
"""simple docstring"""
lowerCamelCase_: List[Any] = HfArgumentParser(A_ )
lowerCamelCase_: Optional[Any] = argparse.ArgumentParser()
expected.add_argument("""--foo_int""" , nargs="""+""" , default=[] , type=A_ )
expected.add_argument("""--bar_int""" , nargs="""+""" , default=[1, 2, 3] , type=A_ )
expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=A_ )
expected.add_argument("""--foo_float""" , nargs="""+""" , default=[0.1, 0.2, 0.3] , type=A_ )
self.argparsersEqual(A_ , A_ )
lowerCamelCase_: List[str] = parser.parse_args([] )
self.assertEqual(
A_ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["""Hallo""", """Bonjour""", """Hello"""] , foo_float=[0.1, 0.2, 0.3] ) , )
lowerCamelCase_: Union[str, Any] = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split() )
self.assertEqual(A_ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["""a""", """b""", """c"""] , foo_float=[0.1, 0.7] ) )
def lowerCAmelCase ( self : str ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase_: Dict = argparse.ArgumentParser()
expected.add_argument("""--foo""" , default=A_ , type=A_ )
expected.add_argument("""--bar""" , default=A_ , type=A_ , help="""help message""" )
expected.add_argument("""--baz""" , default=A_ , type=A_ )
expected.add_argument("""--ces""" , nargs="""+""" , default=[] , type=A_ )
expected.add_argument("""--des""" , nargs="""+""" , default=[] , type=A_ )
lowerCamelCase_: Union[str, Any] = [OptionalExample]
if is_python_no_less_than_3_10:
dataclass_types.append(A_ )
for dataclass_type in dataclass_types:
lowerCamelCase_: Tuple = HfArgumentParser(A_ )
self.argparsersEqual(A_ , A_ )
lowerCamelCase_: Union[str, Any] = parser.parse_args([] )
self.assertEqual(A_ , Namespace(foo=A_ , bar=A_ , baz=A_ , ces=[] , des=[] ) )
lowerCamelCase_: Optional[int] = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split() )
self.assertEqual(A_ , Namespace(foo=12 , bar=3.14 , baz="""42""" , ces=["""a""", """b""", """c"""] , des=[1, 2, 3] ) )
def lowerCAmelCase ( self : Optional[int] ) -> Any:
"""simple docstring"""
lowerCamelCase_: Optional[int] = HfArgumentParser(A_ )
lowerCamelCase_: Optional[int] = argparse.ArgumentParser()
expected.add_argument("""--required_list""" , nargs="""+""" , type=A_ , required=A_ )
expected.add_argument("""--required_str""" , type=A_ , required=A_ )
expected.add_argument(
"""--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=A_ , )
self.argparsersEqual(A_ , A_ )
def lowerCAmelCase ( self : int ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase_: Any = HfArgumentParser(A_ )
lowerCamelCase_: Tuple = argparse.ArgumentParser()
expected.add_argument("""--foo""" , type=A_ , required=A_ )
expected.add_argument(
"""--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=A_ , )
expected.add_argument("""--opt""" , type=A_ , default=A_ )
expected.add_argument("""--baz""" , default="""toto""" , type=A_ , help="""help message""" )
expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=A_ )
self.argparsersEqual(A_ , A_ )
def lowerCAmelCase ( self : str ) -> int:
"""simple docstring"""
lowerCamelCase_: Tuple = HfArgumentParser(A_ )
lowerCamelCase_: List[Any] = {
"""foo""": 12,
"""bar""": 3.14,
"""baz""": """42""",
"""flag""": True,
}
lowerCamelCase_: Optional[int] = parser.parse_dict(A_ )[0]
lowerCamelCase_: Optional[Any] = BasicExample(**A_ )
self.assertEqual(A_ , A_ )
def lowerCAmelCase ( self : Optional[Any] ) -> Union[str, Any]:
"""simple docstring"""
lowerCamelCase_: Optional[int] = HfArgumentParser(A_ )
lowerCamelCase_: Tuple = {
"""foo""": 12,
"""bar""": 3.14,
"""baz""": """42""",
"""flag""": True,
"""extra""": 42,
}
self.assertRaises(A_ , parser.parse_dict , A_ , allow_extra_keys=A_ )
def lowerCAmelCase ( self : Any ) -> Union[str, Any]:
"""simple docstring"""
lowerCamelCase_: Union[str, Any] = HfArgumentParser(A_ )
lowerCamelCase_: int = {
"""foo""": 12,
"""bar""": 3.14,
"""baz""": """42""",
"""flag""": True,
}
with tempfile.TemporaryDirectory() as tmp_dir:
lowerCamelCase_: Union[str, Any] = os.path.join(A_ , """temp_json""" )
os.mkdir(A_ )
with open(temp_local_path + """.json""" , """w+""" ) as f:
json.dump(A_ , A_ )
lowerCamelCase_: List[str] = parser.parse_yaml_file(Path(temp_local_path + """.json""" ) )[0]
lowerCamelCase_: List[str] = BasicExample(**A_ )
self.assertEqual(A_ , A_ )
def lowerCAmelCase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
lowerCamelCase_: str = HfArgumentParser(A_ )
lowerCamelCase_: List[Any] = {
"""foo""": 12,
"""bar""": 3.14,
"""baz""": """42""",
"""flag""": True,
}
with tempfile.TemporaryDirectory() as tmp_dir:
lowerCamelCase_: Tuple = os.path.join(A_ , """temp_yaml""" )
os.mkdir(A_ )
with open(temp_local_path + """.yaml""" , """w+""" ) as f:
yaml.dump(A_ , A_ )
lowerCamelCase_: List[Any] = parser.parse_yaml_file(Path(temp_local_path + """.yaml""" ) )[0]
lowerCamelCase_: str = BasicExample(**A_ )
self.assertEqual(A_ , A_ )
def lowerCAmelCase ( self : Any ) -> str:
"""simple docstring"""
lowerCamelCase_: List[str] = HfArgumentParser(A_ )
self.assertIsNotNone(A_ )
| 584 | 1 |
"""simple docstring"""
from typing import List
import jiwer
import jiwer.transforms as tr
from packaging import version
import datasets
from datasets.config import PY_VERSION
if PY_VERSION < version.parse('''3.8'''):
import importlib_metadata
else:
import importlib.metadata as importlib_metadata
__lowerCAmelCase : Optional[Any] = ''''''
if version.parse(importlib_metadata.version('''jiwer''')) < version.parse('''2.3.0'''):
class _lowerCAmelCase ( tr.AbstractTransform ):
"""simple docstring"""
def __init__( self , _lowercase = " " ) -> Tuple:
'''simple docstring'''
snake_case_ : Union[str, Any] = sentence_delimiter
def UpperCAmelCase__ ( self , _lowercase ) -> str:
'''simple docstring'''
return list(_lowercase )
def UpperCAmelCase__ ( self , _lowercase ) -> Optional[Any]:
'''simple docstring'''
snake_case_ : Optional[int] = []
for sent_idx, sentence in enumerate(_lowercase ):
chars.extend(self.process_string(_lowercase ) )
if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(_lowercase ) - 1:
chars.append(self.sentence_delimiter )
return chars
__lowerCAmelCase : Union[str, Any] = tr.Compose(
[tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
)
else:
__lowerCAmelCase : Optional[int] = tr.Compose(
[
tr.RemoveMultipleSpaces(),
tr.Strip(),
tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
tr.ReduceToListOfListOfChars(),
]
)
__lowerCAmelCase : int = '''\
@inproceedings{inproceedings,
author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
year = {2004},
month = {01},
pages = {},
title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
'''
__lowerCAmelCase : List[str] = '''\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.
CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.
Character error rate can be computed as:
CER = (S + D + I) / N = (S + D + I) / (S + D + C)
where
S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).
CER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
'''
__lowerCAmelCase : Dict = '''
Computes CER score of transcribed segments against references.
Args:
references: list of references for each speech input.
predictions: list of transcribtions to score.
concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
(float): the character error rate
Examples:
>>> predictions = ["this is the prediction", "there is an other sample"]
>>> references = ["this is the reference", "there is another one"]
>>> cer = datasets.load_metric("cer")
>>> cer_score = cer.compute(predictions=predictions, references=references)
>>> print(cer_score)
0.34146341463414637
'''
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class _lowerCAmelCase ( datasets.Metric ):
"""simple docstring"""
def UpperCAmelCase__ ( self ) -> Any:
'''simple docstring'''
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"""predictions""": datasets.Value("""string""" , id="""sequence""" ),
"""references""": datasets.Value("""string""" , id="""sequence""" ),
} ) , codebase_urls=["""https://github.com/jitsi/jiwer/"""] , reference_urls=[
"""https://en.wikipedia.org/wiki/Word_error_rate""",
"""https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates""",
] , )
def UpperCAmelCase__ ( self , _lowercase , _lowercase , _lowercase=False ) -> Optional[Any]:
'''simple docstring'''
if concatenate_texts:
return jiwer.compute_measures(
_lowercase , _lowercase , truth_transform=_lowercase , hypothesis_transform=_lowercase , )["wer"]
snake_case_ : Optional[Any] = 0
snake_case_ : Optional[Any] = 0
for prediction, reference in zip(_lowercase , _lowercase ):
snake_case_ : Optional[int] = jiwer.compute_measures(
_lowercase , _lowercase , truth_transform=_lowercase , hypothesis_transform=_lowercase , )
incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
total += measures["substitutions"] + measures["deletions"] + measures["hits"]
return incorrect / total
| 58 |
import argparse
import os
import re
import numpy as np
import PIL
import torch
from timm import create_model
from torch.optim.lr_scheduler import OneCycleLR
from torch.utils.data import DataLoader, Dataset
from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor
from accelerate import Accelerator
def __lowercase( UpperCAmelCase__ ):
"""simple docstring"""
lowerCamelCase = fname.split(os.path.sep )[-1]
return re.search(r"^(.*)_\d+\.jpg$" , UpperCAmelCase__ ).groups()[0]
class lowerCamelCase__ ( UpperCAmelCase_):
"""simple docstring"""
def __init__(self , __a , __a=None , __a=None ):
'''simple docstring'''
lowerCamelCase = file_names
lowerCamelCase = image_transform
lowerCamelCase = label_to_id
def __len__(self ):
'''simple docstring'''
return len(self.file_names )
def __getitem__(self , __a ):
'''simple docstring'''
lowerCamelCase = self.file_names[idx]
lowerCamelCase = PIL.Image.open(__a )
lowerCamelCase = raw_image.convert("RGB" )
if self.image_transform is not None:
lowerCamelCase = self.image_transform(__a )
lowerCamelCase = extract_label(__a )
if self.label_to_id is not None:
lowerCamelCase = self.label_to_id[label]
return {"image": image, "label": label}
def __lowercase( UpperCAmelCase__ , UpperCAmelCase__ ):
"""simple docstring"""
if args.with_tracking:
lowerCamelCase = Accelerator(
cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="all" , project_dir=args.project_dir )
else:
lowerCamelCase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lowerCamelCase = config["lr"]
lowerCamelCase = int(config["num_epochs"] )
lowerCamelCase = int(config["seed"] )
lowerCamelCase = int(config["batch_size"] )
lowerCamelCase = config["image_size"]
if not isinstance(UpperCAmelCase__ , (list, tuple) ):
lowerCamelCase = (image_size, image_size)
# Parse out whether we are saving every epoch or after a certain number of batches
if hasattr(args.checkpointing_steps , "isdigit" ):
if args.checkpointing_steps == "epoch":
lowerCamelCase = args.checkpointing_steps
elif args.checkpointing_steps.isdigit():
lowerCamelCase = int(args.checkpointing_steps )
else:
raise ValueError(
F"""Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.""" )
else:
lowerCamelCase = None
# We need to initialize the trackers we use, and also store our configuration
if args.with_tracking:
lowerCamelCase = os.path.split(UpperCAmelCase__ )[-1].split("." )[0]
accelerator.init_trackers(UpperCAmelCase__ , UpperCAmelCase__ )
# Grab all the image filenames
lowerCamelCase = [os.path.join(args.data_dir , UpperCAmelCase__ ) for fname in os.listdir(args.data_dir ) if fname.endswith(".jpg" )]
# Build the label correspondences
lowerCamelCase = [extract_label(UpperCAmelCase__ ) for fname in file_names]
lowerCamelCase = list(set(UpperCAmelCase__ ) )
id_to_label.sort()
lowerCamelCase = {lbl: i for i, lbl in enumerate(UpperCAmelCase__ )}
# Set the seed before splitting the data.
np.random.seed(UpperCAmelCase__ )
torch.manual_seed(UpperCAmelCase__ )
torch.cuda.manual_seed_all(UpperCAmelCase__ )
# Split our filenames between train and validation
lowerCamelCase = np.random.permutation(len(UpperCAmelCase__ ) )
lowerCamelCase = int(0.8 * len(UpperCAmelCase__ ) )
lowerCamelCase = random_perm[:cut]
lowerCamelCase = random_perm[cut:]
# For training we use a simple RandomResizedCrop
lowerCamelCase = Compose([RandomResizedCrop(UpperCAmelCase__ , scale=(0.5, 1.0) ), ToTensor()] )
lowerCamelCase = PetsDataset(
[file_names[i] for i in train_split] , image_transform=UpperCAmelCase__ , label_to_id=UpperCAmelCase__ )
# For evaluation, we use a deterministic Resize
lowerCamelCase = Compose([Resize(UpperCAmelCase__ ), ToTensor()] )
lowerCamelCase = PetsDataset([file_names[i] for i in eval_split] , image_transform=UpperCAmelCase__ , label_to_id=UpperCAmelCase__ )
# Instantiate dataloaders.
lowerCamelCase = DataLoader(UpperCAmelCase__ , shuffle=UpperCAmelCase__ , batch_size=UpperCAmelCase__ , num_workers=4 )
lowerCamelCase = DataLoader(UpperCAmelCase__ , shuffle=UpperCAmelCase__ , batch_size=UpperCAmelCase__ , num_workers=4 )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
lowerCamelCase = create_model("resnet50d" , pretrained=UpperCAmelCase__ , num_classes=len(UpperCAmelCase__ ) )
# 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).
lowerCamelCase = model.to(accelerator.device )
# Freezing the base model
for param in model.parameters():
lowerCamelCase = False
for param in model.get_classifier().parameters():
lowerCamelCase = True
# We normalize the batches of images to be a bit faster.
lowerCamelCase = torch.tensor(model.default_cfg["mean"] )[None, :, None, None].to(accelerator.device )
lowerCamelCase = torch.tensor(model.default_cfg["std"] )[None, :, None, None].to(accelerator.device )
# Instantiate optimizer
lowerCamelCase = torch.optim.Adam(params=model.parameters() , lr=lr / 25 )
# Instantiate learning rate scheduler
lowerCamelCase = OneCycleLR(optimizer=UpperCAmelCase__ , max_lr=UpperCAmelCase__ , epochs=UpperCAmelCase__ , steps_per_epoch=len(UpperCAmelCase__ ) )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = accelerator.prepare(
UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
# We need to keep track of how many total steps we have iterated over
lowerCamelCase = 0
# We also need to keep track of the starting epoch so files are named properly
lowerCamelCase = 0
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
accelerator.print(F"""Resumed from checkpoint: {args.resume_from_checkpoint}""" )
accelerator.load_state(args.resume_from_checkpoint )
lowerCamelCase = os.path.basename(args.resume_from_checkpoint )
else:
# Get the most recent checkpoint
lowerCamelCase = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()]
dirs.sort(key=os.path.getctime )
lowerCamelCase = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
# Extract `epoch_{i}` or `step_{i}`
lowerCamelCase = os.path.splitext(UpperCAmelCase__ )[0]
if "epoch" in training_difference:
lowerCamelCase = int(training_difference.replace("epoch_" , "" ) ) + 1
lowerCamelCase = None
else:
lowerCamelCase = int(training_difference.replace("step_" , "" ) )
lowerCamelCase = resume_step // len(UpperCAmelCase__ )
resume_step -= starting_epoch * len(UpperCAmelCase__ )
# Now we train the model
for epoch in range(UpperCAmelCase__ , UpperCAmelCase__ ):
model.train()
if args.with_tracking:
lowerCamelCase = 0
if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
# We need to skip steps until we reach the resumed step
lowerCamelCase = accelerator.skip_first_batches(UpperCAmelCase__ , UpperCAmelCase__ )
overall_step += resume_step
else:
# After the first iteration though, we need to go back to the original dataloader
lowerCamelCase = train_dataloader
for batch in active_dataloader:
# We could avoid this line since we set the accelerator with `device_placement=True`.
lowerCamelCase = {k: v.to(accelerator.device ) for k, v in batch.items()}
lowerCamelCase = (batch["image"] - mean) / std
lowerCamelCase = model(UpperCAmelCase__ )
lowerCamelCase = torch.nn.functional.cross_entropy(UpperCAmelCase__ , batch["label"] )
# We keep track of the loss at each epoch
if args.with_tracking:
total_loss += loss.detach().float()
accelerator.backward(UpperCAmelCase__ )
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ):
lowerCamelCase = F"""step_{overall_step}"""
if overall_step % checkpointing_steps == 0:
if args.output_dir is not None:
lowerCamelCase = os.path.join(args.output_dir , UpperCAmelCase__ )
accelerator.save_state(UpperCAmelCase__ )
model.eval()
lowerCamelCase = 0
lowerCamelCase = 0
for step, batch in enumerate(UpperCAmelCase__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
lowerCamelCase = {k: v.to(accelerator.device ) for k, v in batch.items()}
lowerCamelCase = (batch["image"] - mean) / std
with torch.no_grad():
lowerCamelCase = model(UpperCAmelCase__ )
lowerCamelCase = outputs.argmax(dim=-1 )
lowerCamelCase , lowerCamelCase = accelerator.gather_for_metrics((predictions, batch["label"]) )
lowerCamelCase = predictions == references
num_elems += accurate_preds.shape[0]
accurate += accurate_preds.long().sum()
lowerCamelCase = accurate.item() / num_elems
# Use accelerator.print to print only on the main process.
accelerator.print(F"""epoch {epoch}: {100 * eval_metric:.2f}""" )
if args.with_tracking:
accelerator.log(
{
"accuracy": 100 * eval_metric,
"train_loss": total_loss.item() / len(UpperCAmelCase__ ),
"epoch": epoch,
} , step=UpperCAmelCase__ , )
if checkpointing_steps == "epoch":
lowerCamelCase = F"""epoch_{epoch}"""
if args.output_dir is not None:
lowerCamelCase = os.path.join(args.output_dir , UpperCAmelCase__ )
accelerator.save_state(UpperCAmelCase__ )
if args.with_tracking:
accelerator.end_training()
def __lowercase( ):
"""simple docstring"""
lowerCamelCase = argparse.ArgumentParser(description="Simple example of training script." )
parser.add_argument("--data_dir" , required=UpperCAmelCase__ , help="The data folder on disk." )
parser.add_argument("--fp16" , action="store_true" , help="If passed, will use FP16 training." )
parser.add_argument(
"--mixed_precision" , type=UpperCAmelCase__ , default=UpperCAmelCase__ , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose"
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
"and an Nvidia Ampere GPU." , )
parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." )
parser.add_argument(
"--checkpointing_steps" , type=UpperCAmelCase__ , default=UpperCAmelCase__ , help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch." , )
parser.add_argument(
"--output_dir" , type=UpperCAmelCase__ , default="." , help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory." , )
parser.add_argument(
"--resume_from_checkpoint" , type=UpperCAmelCase__ , default=UpperCAmelCase__ , help="If the training should continue from a checkpoint folder." , )
parser.add_argument(
"--with_tracking" , action="store_true" , help="Whether to load in all available experiment trackers from the environment and use them for logging." , )
parser.add_argument(
"--project_dir" , type=UpperCAmelCase__ , default="logs" , help="Location on where to store experiment tracking logs` and relevent project information" , )
lowerCamelCase = parser.parse_args()
lowerCamelCase = {"lr": 3E-2, "num_epochs": 3, "seed": 42, "batch_size": 64, "image_size": 224}
training_function(UpperCAmelCase__ , UpperCAmelCase__ )
if __name__ == "__main__":
main() | 623 | 0 |
from graphs.minimum_spanning_tree_kruskal import kruskal
def SCREAMING_SNAKE_CASE ( ) -> Any:
__UpperCAmelCase =9
__UpperCAmelCase =[
[0, 1, 4],
[0, 7, 8],
[1, 2, 8],
[7, 8, 7],
[7, 6, 1],
[2, 8, 2],
[8, 6, 6],
[2, 3, 7],
[2, 5, 4],
[6, 5, 2],
[3, 5, 14],
[3, 4, 9],
[5, 4, 10],
[1, 7, 11],
]
__UpperCAmelCase =kruskal(snake_case__ , snake_case__ )
__UpperCAmelCase =[
[7, 6, 1],
[2, 8, 2],
[6, 5, 2],
[0, 1, 4],
[2, 5, 4],
[2, 3, 7],
[0, 7, 8],
[3, 4, 9],
]
assert sorted(snake_case__ ) == sorted(snake_case__ )
| 719 |
def SCREAMING_SNAKE_CASE ( snake_case__ = 6008_5147_5143 ) -> int:
try:
__UpperCAmelCase =int(snake_case__ )
except (TypeError, ValueError):
raise TypeError('''Parameter n must be int or castable to int.''' )
if n <= 0:
raise ValueError('''Parameter n must be greater than or equal to one.''' )
__UpperCAmelCase =1
__UpperCAmelCase =2
while i * i <= n:
while n % i == 0:
__UpperCAmelCase =i
n //= i
i += 1
if n > 1:
__UpperCAmelCase =n
return int(snake_case__ )
if __name__ == "__main__":
print(f'{solution() = }')
| 142 | 0 |
def A ( lowercase__ : int ) -> List[str]:
UpperCamelCase__ , UpperCamelCase__ :Tuple = [], []
while len(lowercase__ ) > 1:
UpperCamelCase__ , UpperCamelCase__ :List[Any] = min(lowercase__ ), max(lowercase__ )
start.append(lowercase__ )
end.append(lowercase__ )
collection.remove(lowercase__ )
collection.remove(lowercase__ )
end.reverse()
return start + collection + end
if __name__ == "__main__":
UpperCamelCase = input("Enter numbers separated by a comma:\n").strip()
UpperCamelCase = [int(item) for item in user_input.split(",")]
print(*merge_sort(unsorted), sep=",") | 45 |
import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path
import torch_xla.distributed.xla_multiprocessing as xmp
def __snake_case ( ):
'''simple docstring'''
lowercase = ArgumentParser(
description=(
"PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes"
) )
# Optional arguments for the launch helper
parser.add_argument("--num_cores" , type=__magic_name__ , default=1 , help="Number of TPU cores to use (1 or 8)." )
# positional
parser.add_argument(
"training_script" , type=__magic_name__ , help=(
"The full path to the single TPU training "
"program/script to be launched in parallel, "
"followed by all the arguments for the "
"training script"
) , )
# rest from the training program
parser.add_argument("training_script_args" , nargs=__magic_name__ )
return parser.parse_args()
def __snake_case ( ):
'''simple docstring'''
lowercase = parse_args()
# Import training_script as a module.
lowercase = Path(args.training_script )
sys.path.append(str(script_fpath.parent.resolve() ) )
lowercase = script_fpath.stem
lowercase = importlib.import_module(__magic_name__ )
# Patch sys.argv
lowercase = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )]
xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores )
if __name__ == "__main__":
main()
| 441 | 0 |
"""simple docstring"""
from typing import List
from .keymap import KEYMAP, get_character
def _lowerCAmelCase ( lowerCAmelCase ):
'''simple docstring'''
def decorator(lowerCAmelCase ):
UpperCAmelCase = getattr(_A , """handle_key""" , [] )
handle += [key]
setattr(_A , """handle_key""" , _A )
return func
return decorator
def _lowerCAmelCase ( *lowerCAmelCase ):
'''simple docstring'''
def decorator(lowerCAmelCase ):
UpperCAmelCase = getattr(_A , """handle_key""" , [] )
handle += keys
setattr(_A , """handle_key""" , _A )
return func
return decorator
class UpperCamelCase_ ( lowercase__ ):
def __new__( cls , snake_case__ , snake_case__ , snake_case__ ) -> List[str]:
"""simple docstring"""
UpperCAmelCase = super().__new__(cls , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
if not hasattr(__lowerCamelCase , """key_handler""" ):
setattr(__lowerCamelCase , """key_handler""" , {} )
setattr(__lowerCamelCase , """handle_input""" , KeyHandler.handle_input )
for value in attrs.values():
UpperCAmelCase = getattr(__lowerCamelCase , """handle_key""" , [] )
for key in handled_keys:
UpperCAmelCase = value
return new_cls
@staticmethod
def UpperCamelCase_ ( cls ) -> List[Any]:
"""simple docstring"""
UpperCAmelCase = get_character()
if char != KEYMAP["undefined"]:
UpperCAmelCase = ord(__lowerCamelCase )
UpperCAmelCase = cls.key_handler.get(__lowerCamelCase )
if handler:
UpperCAmelCase = char
return handler(cls )
else:
return None
def _lowerCAmelCase ( cls ):
'''simple docstring'''
return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
| 705 |
"""simple docstring"""
import tempfile
import numpy as np
import torch
from transformers import AutoTokenizer, TaEncoderModel
from diffusers import DDPMScheduler, UNetaDConditionModel
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.pipelines.deepfloyd_if import IFWatermarker
from diffusers.utils.testing_utils import torch_device
from ..test_pipelines_common import to_np
class UpperCamelCase_ :
def UpperCamelCase_ ( self ) -> Any:
"""simple docstring"""
torch.manual_seed(0 )
UpperCAmelCase = TaEncoderModel.from_pretrained("""hf-internal-testing/tiny-random-t5""" )
torch.manual_seed(0 )
UpperCAmelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-t5""" )
torch.manual_seed(0 )
UpperCAmelCase = UNetaDConditionModel(
sample_size=32 , layers_per_block=1 , block_out_channels=[32, 64] , down_block_types=[
"""ResnetDownsampleBlock2D""",
"""SimpleCrossAttnDownBlock2D""",
] , mid_block_type="""UNetMidBlock2DSimpleCrossAttn""" , up_block_types=["""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""] , in_channels=3 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type="""text""" , addition_embed_type_num_heads=2 , cross_attention_norm="""group_norm""" , resnet_time_scale_shift="""scale_shift""" , act_fn="""gelu""" , )
unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests
torch.manual_seed(0 )
UpperCAmelCase = DDPMScheduler(
num_train_timesteps=10_00 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0_001 , beta_end=0.02 , thresholding=snake_case__ , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type="""epsilon""" , variance_type="""learned_range""" , )
torch.manual_seed(0 )
UpperCAmelCase = IFWatermarker()
return {
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"unet": unet,
"scheduler": scheduler,
"watermarker": watermarker,
"safety_checker": None,
"feature_extractor": None,
}
def UpperCamelCase_ ( self ) -> int:
"""simple docstring"""
torch.manual_seed(0 )
UpperCAmelCase = TaEncoderModel.from_pretrained("""hf-internal-testing/tiny-random-t5""" )
torch.manual_seed(0 )
UpperCAmelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-t5""" )
torch.manual_seed(0 )
UpperCAmelCase = UNetaDConditionModel(
sample_size=32 , layers_per_block=[1, 2] , block_out_channels=[32, 64] , down_block_types=[
"""ResnetDownsampleBlock2D""",
"""SimpleCrossAttnDownBlock2D""",
] , mid_block_type="""UNetMidBlock2DSimpleCrossAttn""" , up_block_types=["""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""] , in_channels=6 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type="""text""" , addition_embed_type_num_heads=2 , cross_attention_norm="""group_norm""" , resnet_time_scale_shift="""scale_shift""" , act_fn="""gelu""" , class_embed_type="""timestep""" , mid_block_scale_factor=1.414 , time_embedding_act_fn="""gelu""" , time_embedding_dim=32 , )
unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests
torch.manual_seed(0 )
UpperCAmelCase = DDPMScheduler(
num_train_timesteps=10_00 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0_001 , beta_end=0.02 , thresholding=snake_case__ , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type="""epsilon""" , variance_type="""learned_range""" , )
torch.manual_seed(0 )
UpperCAmelCase = DDPMScheduler(
num_train_timesteps=10_00 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0_001 , beta_end=0.02 , )
torch.manual_seed(0 )
UpperCAmelCase = IFWatermarker()
return {
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"unet": unet,
"scheduler": scheduler,
"image_noising_scheduler": image_noising_scheduler,
"watermarker": watermarker,
"safety_checker": None,
"feature_extractor": None,
}
def UpperCamelCase_ ( self ) -> Tuple:
"""simple docstring"""
UpperCAmelCase = self.get_dummy_components()
UpperCAmelCase = self.pipeline_class(**snake_case__ )
pipe.to(snake_case__ )
pipe.set_progress_bar_config(disable=snake_case__ )
UpperCAmelCase = self.get_dummy_inputs(snake_case__ )
UpperCAmelCase = inputs["""prompt"""]
UpperCAmelCase = inputs["""generator"""]
UpperCAmelCase = inputs["""num_inference_steps"""]
UpperCAmelCase = inputs["""output_type"""]
if "image" in inputs:
UpperCAmelCase = inputs["""image"""]
else:
UpperCAmelCase = None
if "mask_image" in inputs:
UpperCAmelCase = inputs["""mask_image"""]
else:
UpperCAmelCase = None
if "original_image" in inputs:
UpperCAmelCase = inputs["""original_image"""]
else:
UpperCAmelCase = None
UpperCAmelCase , UpperCAmelCase = pipe.encode_prompt(snake_case__ )
# inputs with prompt converted to embeddings
UpperCAmelCase = {
"""prompt_embeds""": prompt_embeds,
"""negative_prompt_embeds""": negative_prompt_embeds,
"""generator""": generator,
"""num_inference_steps""": num_inference_steps,
"""output_type""": output_type,
}
if image is not None:
UpperCAmelCase = image
if mask_image is not None:
UpperCAmelCase = mask_image
if original_image is not None:
UpperCAmelCase = original_image
# set all optional components to None
for optional_component in pipe._optional_components:
setattr(snake_case__ , snake_case__ , snake_case__ )
UpperCAmelCase = pipe(**snake_case__ )[0]
with tempfile.TemporaryDirectory() as tmpdir:
pipe.save_pretrained(snake_case__ )
UpperCAmelCase = self.pipeline_class.from_pretrained(snake_case__ )
pipe_loaded.to(snake_case__ )
pipe_loaded.set_progress_bar_config(disable=snake_case__ )
pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests
for optional_component in pipe._optional_components:
self.assertTrue(
getattr(snake_case__ , snake_case__ ) is None , f'''`{optional_component}` did not stay set to None after loading.''' , )
UpperCAmelCase = self.get_dummy_inputs(snake_case__ )
UpperCAmelCase = inputs["""generator"""]
UpperCAmelCase = inputs["""num_inference_steps"""]
UpperCAmelCase = inputs["""output_type"""]
# inputs with prompt converted to embeddings
UpperCAmelCase = {
"""prompt_embeds""": prompt_embeds,
"""negative_prompt_embeds""": negative_prompt_embeds,
"""generator""": generator,
"""num_inference_steps""": num_inference_steps,
"""output_type""": output_type,
}
if image is not None:
UpperCAmelCase = image
if mask_image is not None:
UpperCAmelCase = mask_image
if original_image is not None:
UpperCAmelCase = original_image
UpperCAmelCase = pipe_loaded(**snake_case__ )[0]
UpperCAmelCase = np.abs(to_np(snake_case__ ) - to_np(snake_case__ ) ).max()
self.assertLess(snake_case__ , 1e-4 )
def UpperCamelCase_ ( self ) -> int:
"""simple docstring"""
UpperCAmelCase = self.get_dummy_components()
UpperCAmelCase = self.pipeline_class(**snake_case__ )
pipe.to(snake_case__ )
pipe.set_progress_bar_config(disable=snake_case__ )
UpperCAmelCase = self.get_dummy_inputs(snake_case__ )
UpperCAmelCase = pipe(**snake_case__ )[0]
with tempfile.TemporaryDirectory() as tmpdir:
pipe.save_pretrained(snake_case__ )
UpperCAmelCase = self.pipeline_class.from_pretrained(snake_case__ )
pipe_loaded.to(snake_case__ )
pipe_loaded.set_progress_bar_config(disable=snake_case__ )
pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests
UpperCAmelCase = self.get_dummy_inputs(snake_case__ )
UpperCAmelCase = pipe_loaded(**snake_case__ )[0]
UpperCAmelCase = np.abs(to_np(snake_case__ ) - to_np(snake_case__ ) ).max()
self.assertLess(snake_case__ , 1e-4 )
| 378 | 0 |
'''simple docstring'''
import os
import re
import shutil
import sys
import tempfile
import unittest
import black
UpperCAmelCase__ : Optional[int] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))
import check_copies # noqa: E402
# This is the reference code that will be used in the tests.
# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.
UpperCAmelCase__ : List[str] = " def __init__(self, config):\n super().__init__()\n self.transform = BertPredictionHeadTransform(config)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`\n self.decoder.bias = self.bias\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = self.decoder(hidden_states)\n return hidden_states\n"
class A ( unittest.TestCase ):
def __SCREAMING_SNAKE_CASE ( self : Any ):
"""simple docstring"""
lowerCAmelCase__ = tempfile.mkdtemp()
os.makedirs(os.path.join(self.transformer_dir , "models/bert/" ) )
lowerCAmelCase__ = self.transformer_dir
shutil.copy(
os.path.join(__magic_name__ , "src/transformers/models/bert/modeling_bert.py" ) , os.path.join(self.transformer_dir , "models/bert/modeling_bert.py" ) , )
def __SCREAMING_SNAKE_CASE ( self : List[str] ):
"""simple docstring"""
lowerCAmelCase__ = "src/transformers"
shutil.rmtree(self.transformer_dir )
def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : int , __magic_name__ : Tuple=None ):
"""simple docstring"""
lowerCAmelCase__ = comment + f"""\nclass {class_name}(nn.Module):\n""" + class_code
if overwrite_result is not None:
lowerCAmelCase__ = comment + f"""\nclass {class_name}(nn.Module):\n""" + overwrite_result
lowerCAmelCase__ = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 )
lowerCAmelCase__ = black.format_str(__magic_name__ , mode=__magic_name__ )
lowerCAmelCase__ = os.path.join(self.transformer_dir , "new_code.py" )
with open(__magic_name__ , "w" , newline="\n" ) as f:
f.write(__magic_name__ )
if overwrite_result is None:
self.assertTrue(len(check_copies.is_copy_consistent(__magic_name__ ) ) == 0 )
else:
check_copies.is_copy_consistent(f.name , overwrite=__magic_name__ )
with open(__magic_name__ , "r" ) as f:
self.assertTrue(f.read() , __magic_name__ )
def __SCREAMING_SNAKE_CASE ( self : Dict ):
"""simple docstring"""
lowerCAmelCase__ = check_copies.find_code_in_transformers("models.bert.modeling_bert.BertLMPredictionHead" )
self.assertEqual(__magic_name__ , __magic_name__ )
def __SCREAMING_SNAKE_CASE ( self : Tuple ):
"""simple docstring"""
self.check_copy_consistency(
"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead" , "BertLMPredictionHead" , REFERENCE_CODE + "\n" , )
# With no empty line at the end
self.check_copy_consistency(
"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead" , "BertLMPredictionHead" , __magic_name__ , )
# Copy consistency with rename
self.check_copy_consistency(
"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel" , "TestModelLMPredictionHead" , re.sub("Bert" , "TestModel" , __magic_name__ ) , )
# Copy consistency with a really long name
lowerCAmelCase__ = "TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason"
self.check_copy_consistency(
f"""# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}""" , f"""{long_class_name}LMPredictionHead""" , re.sub("Bert" , __magic_name__ , __magic_name__ ) , )
# Copy consistency with overwrite
self.check_copy_consistency(
"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel" , "TestModelLMPredictionHead" , __magic_name__ , overwrite_result=re.sub("Bert" , "TestModel" , __magic_name__ ) , )
def __SCREAMING_SNAKE_CASE ( self : List[str] ):
"""simple docstring"""
lowerCAmelCase__ = check_copies.LOCALIZED_READMES["README_zh-hans.md"]
lowerCAmelCase__ = (
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"
" Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"
" Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"
" Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1."
" **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),"
" released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"
" lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same"
" method has been applied to compress GPT2 into"
" [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"
" [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"
" Multilingual BERT into"
" [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"
" version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**"
" (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders"
" as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang"
" Luong, Quoc V. Le, Christopher D. Manning."
)
lowerCAmelCase__ = (
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
" Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
" Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
" Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
)
lowerCAmelCase__ = (
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
" Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
" Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
" Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1."
" **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文"
" [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"
" lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same"
" method has been applied to compress GPT2 into"
" [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"
" [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"
" Multilingual BERT into"
" [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"
" version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自"
" Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather"
" than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,"
" Christopher D. Manning 发布。\n"
)
lowerCAmelCase__ ,lowerCAmelCase__ = check_copies.convert_to_localized_md(
__magic_name__ , __magic_name__ , localized_readme["format_model_list"] )
self.assertFalse(__magic_name__ )
self.assertEqual(__magic_name__ , __magic_name__ )
lowerCAmelCase__ ,lowerCAmelCase__ = check_copies.convert_to_localized_md(
__magic_name__ , __magic_name__ , localized_readme["format_model_list"] )
# Check whether the number of models is equal to README.md after conversion.
self.assertTrue(__magic_name__ )
lowerCAmelCase__ = (
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"
" Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"
" Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"
" Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut."
)
lowerCAmelCase__ = (
"1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and"
" the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
" Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
" Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
)
lowerCAmelCase__ = (
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
" Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
" Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
" Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
)
lowerCAmelCase__ ,lowerCAmelCase__ = check_copies.convert_to_localized_md(
__magic_name__ , __magic_name__ , localized_readme["format_model_list"] )
# Check if the model link is synchronized.
self.assertEqual(__magic_name__ , __magic_name__ )
| 48 |
"""simple docstring"""
lowercase_ = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n"
lowercase_ = [{"type": "code", "content": INSTALL_CONTENT}]
lowercase_ = {
"{processor_class}": "FakeProcessorClass",
"{model_class}": "FakeModelClass",
"{object_class}": "FakeObjectClass",
}
| 470 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_torch_available,
is_vision_available,
)
UpperCAmelCase = {
'configuration_blip': [
'BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP',
'BlipConfig',
'BlipTextConfig',
'BlipVisionConfig',
],
'processing_blip': ['BlipProcessor'],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase = ['BlipImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase = [
'BLIP_PRETRAINED_MODEL_ARCHIVE_LIST',
'BlipModel',
'BlipPreTrainedModel',
'BlipForConditionalGeneration',
'BlipForQuestionAnswering',
'BlipVisionModel',
'BlipTextModel',
'BlipForImageTextRetrieval',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase = [
'TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFBlipModel',
'TFBlipPreTrainedModel',
'TFBlipForConditionalGeneration',
'TFBlipForQuestionAnswering',
'TFBlipVisionModel',
'TFBlipTextModel',
'TFBlipForImageTextRetrieval',
]
if TYPE_CHECKING:
from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig
from .processing_blip import BlipProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_blip import BlipImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_blip import (
BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
BlipForConditionalGeneration,
BlipForImageTextRetrieval,
BlipForQuestionAnswering,
BlipModel,
BlipPreTrainedModel,
BlipTextModel,
BlipVisionModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_blip import (
TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
TFBlipForConditionalGeneration,
TFBlipForImageTextRetrieval,
TFBlipForQuestionAnswering,
TFBlipModel,
TFBlipPreTrainedModel,
TFBlipTextModel,
TFBlipVisionModel,
)
else:
import sys
UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 715 |
'''simple docstring'''
import copy
import tempfile
import unittest
from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder
def _snake_case ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[Any]=None , _SCREAMING_SNAKE_CASE : Dict=None , _SCREAMING_SNAKE_CASE : List[str]=None , _SCREAMING_SNAKE_CASE : List[str]=None , _SCREAMING_SNAKE_CASE : Optional[int]=None , ) -> Optional[Any]:
"""simple docstring"""
if attention_mask is None:
lowerCAmelCase = input_ids.ne(config.pad_token_id )
if decoder_attention_mask is None:
lowerCAmelCase = decoder_input_ids.ne(config.pad_token_id )
if head_mask is None:
lowerCAmelCase = torch.ones(config.encoder_layers , config.encoder_attention_heads , device=_SCREAMING_SNAKE_CASE )
if decoder_head_mask is None:
lowerCAmelCase = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=_SCREAMING_SNAKE_CASE )
if cross_attn_head_mask is None:
lowerCAmelCase = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=_SCREAMING_SNAKE_CASE )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
class __snake_case:
'''simple docstring'''
def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=False , A_=99 , A_=16 , A_=2 , A_=4 , A_=4 , A_="relu" , A_=0.1 , A_=0.1 , A_=0.0 , A_=0.0 , A_=20 , A_=2 , A_=1 , A_=0 , ) -> Union[str, Any]:
lowerCAmelCase = parent
lowerCAmelCase = batch_size
lowerCAmelCase = seq_length
lowerCAmelCase = is_training
lowerCAmelCase = use_labels
lowerCAmelCase = vocab_size
lowerCAmelCase = hidden_size
lowerCAmelCase = num_hidden_layers
lowerCAmelCase = num_attention_heads
lowerCAmelCase = intermediate_size
lowerCAmelCase = hidden_act
lowerCAmelCase = hidden_dropout_prob
lowerCAmelCase = attention_probs_dropout_prob
lowerCAmelCase = encoder_layerdrop
lowerCAmelCase = decoder_layerdrop
lowerCAmelCase = max_position_embeddings
lowerCAmelCase = eos_token_id
lowerCAmelCase = pad_token_id
lowerCAmelCase = bos_token_id
def __snake_case ( self ) -> Tuple:
lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
lowerCAmelCase = self.eos_token_id # Eos Token
lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
# we need to clamp the input ids here to avoid having pad token in between
# this is because for M2M100 the position_ids are prepared such that
# all pad tokens have pos id = 2 and rest are between 2..seq_length
# and the seq_length here is seq_length - num_pad_tokens
# but when using past, there is no way of knowing if the past input ids had
# pad tokens in them, which results in incorrect seq_lenth and which in turn results in
# position_ids being off by num_pad_tokens in past input
lowerCAmelCase = input_ids.clamp(self.pad_token_id + 1 )
lowerCAmelCase = decoder_input_ids.clamp(self.pad_token_id + 1 )
lowerCAmelCase = self.get_config()
lowerCAmelCase = prepare_mam_aaa_inputs_dict(A_ , A_ , A_ )
return config, inputs_dict
def __snake_case ( self ) -> Optional[Any]:
return MaMaaaConfig(
vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , encoder_layerdrop=self.encoder_layerdrop , decoder_layerdrop=self.decoder_layerdrop , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , )
def __snake_case ( self ) -> str:
lowerCAmelCase, lowerCAmelCase = self.prepare_config_and_inputs()
return config, inputs_dict
def __snake_case ( self , A_ , A_ ) -> Tuple:
lowerCAmelCase = MaMaaaModel(config=A_ ).get_decoder().to(A_ ).eval()
lowerCAmelCase = inputs_dict["""input_ids"""]
lowerCAmelCase = inputs_dict["""attention_mask"""]
lowerCAmelCase = inputs_dict["""head_mask"""]
# first forward pass
lowerCAmelCase = model(A_ , attention_mask=A_ , head_mask=A_ , use_cache=A_ )
lowerCAmelCase, lowerCAmelCase = outputs.to_tuple()
# create hypothetical multiple next token and extent to next_input_ids
lowerCAmelCase = ids_tensor((self.batch_size, 3) , config.vocab_size )
lowerCAmelCase = ids_tensor((self.batch_size, 3) , 2 )
# append to next input_ids and
lowerCAmelCase = torch.cat([input_ids, next_tokens] , dim=-1 )
lowerCAmelCase = torch.cat([attention_mask, next_attn_mask] , dim=-1 )
lowerCAmelCase = model(A_ , attention_mask=A_ )["""last_hidden_state"""]
lowerCAmelCase = model(A_ , attention_mask=A_ , past_key_values=A_ )[
"""last_hidden_state"""
]
# select random slice
lowerCAmelCase = ids_tensor((1,) , output_from_past.shape[-1] ).item()
lowerCAmelCase = output_from_no_past[:, -3:, random_slice_idx].detach()
lowerCAmelCase = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(A_ , A_ , atol=1e-2 ) )
def __snake_case ( self , A_ , A_ ) -> Any:
lowerCAmelCase = MaMaaaModel(config=A_ ).to(A_ ).eval()
lowerCAmelCase = model(**A_ )
lowerCAmelCase = outputs.encoder_last_hidden_state
lowerCAmelCase = outputs.last_hidden_state
with tempfile.TemporaryDirectory() as tmpdirname:
lowerCAmelCase = model.get_encoder()
encoder.save_pretrained(A_ )
lowerCAmelCase = MaMaaaEncoder.from_pretrained(A_ ).to(A_ )
lowerCAmelCase = encoder(inputs_dict["""input_ids"""] , attention_mask=inputs_dict["""attention_mask"""] )[
0
]
self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3 )
with tempfile.TemporaryDirectory() as tmpdirname:
lowerCAmelCase = model.get_decoder()
decoder.save_pretrained(A_ )
lowerCAmelCase = MaMaaaDecoder.from_pretrained(A_ ).to(A_ )
lowerCAmelCase = decoder(
input_ids=inputs_dict["""decoder_input_ids"""] , attention_mask=inputs_dict["""decoder_attention_mask"""] , encoder_hidden_states=A_ , encoder_attention_mask=inputs_dict["""attention_mask"""] , )[0]
self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3 )
@require_torch
class __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ):
'''simple docstring'''
UpperCAmelCase : int = (
(
MaMaaaModel,
MaMaaaForConditionalGeneration,
)
if is_torch_available()
else ()
)
UpperCAmelCase : Tuple = (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
UpperCAmelCase : Any = (
{
"conversational": MaMaaaForConditionalGeneration,
"feature-extraction": MaMaaaModel,
"summarization": MaMaaaForConditionalGeneration,
"text2text-generation": MaMaaaForConditionalGeneration,
"translation": MaMaaaForConditionalGeneration,
}
if is_torch_available()
else {}
)
UpperCAmelCase : str = True
UpperCAmelCase : Optional[int] = True
UpperCAmelCase : Dict = False
UpperCAmelCase : Dict = False
def __snake_case ( self , A_ , A_ , A_ , A_ , A_ ) -> int:
if pipeline_test_casse_name == "TranslationPipelineTests":
# Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
# `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
return True
return False
def __snake_case ( self ) -> int:
lowerCAmelCase = MaMaaaModelTester(self )
lowerCAmelCase = ConfigTester(self , config_class=A_ )
def __snake_case ( self ) -> Tuple:
self.config_tester.run_common_tests()
def __snake_case ( self ) -> List[Any]:
lowerCAmelCase, lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
lowerCAmelCase = model_class(A_ )
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(A_ )
lowerCAmelCase, lowerCAmelCase = model_class.from_pretrained(A_ , output_loading_info=A_ )
self.assertEqual(info["""missing_keys"""] , [] )
def __snake_case ( self ) -> Any:
lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past_large_inputs(*A_ )
def __snake_case ( self ) -> int:
lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_encoder_decoder_model_standalone(*A_ )
def __snake_case ( self ) -> Tuple:
lowerCAmelCase, lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
lowerCAmelCase = model_class(A_ )
model.to(A_ )
model.eval()
lowerCAmelCase = copy.deepcopy(self._prepare_for_class(A_ , A_ ) )
if not self.is_encoder_decoder:
lowerCAmelCase = inputs["""input_ids"""]
del inputs["input_ids"]
else:
lowerCAmelCase = inputs["""input_ids"""]
lowerCAmelCase = inputs.get("""decoder_input_ids""" , A_ )
del inputs["input_ids"]
inputs.pop("""decoder_input_ids""" , A_ )
lowerCAmelCase = model.get_input_embeddings()
if not self.is_encoder_decoder:
lowerCAmelCase = wte(A_ )
else:
lowerCAmelCase = wte(A_ )
lowerCAmelCase = wte(A_ )
with torch.no_grad():
model(**A_ )[0]
def __snake_case ( self ) -> str:
lowerCAmelCase, lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
lowerCAmelCase = input_dict["""input_ids"""]
lowerCAmelCase = input_ids.ne(1 ).to(A_ )
lowerCAmelCase = MaMaaaForConditionalGeneration(A_ ).eval().to(A_ )
if torch_device == "cuda":
model.half()
model.generate(A_ , attention_mask=A_ )
model.generate(num_beams=4 , do_sample=A_ , early_stopping=A_ , num_return_sequences=3 )
def _snake_case ( _SCREAMING_SNAKE_CASE : Any ) -> Union[str, Any]:
"""simple docstring"""
return torch.tensor(_SCREAMING_SNAKE_CASE , dtype=torch.long , device=_SCREAMING_SNAKE_CASE )
UpperCAmelCase = 1e-4
@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class __snake_case( unittest.TestCase ):
'''simple docstring'''
@cached_property
def __snake_case ( self ) -> List[Any]:
return MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M""" )
def __snake_case ( self ) -> str:
lowerCAmelCase = MaMaaaModel.from_pretrained("""facebook/m2m100_418M""" ).to(A_ )
lowerCAmelCase = _long_tensor([[12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38, 2]] )
lowerCAmelCase = _long_tensor([[2, 12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38]] )
lowerCAmelCase = prepare_mam_aaa_inputs_dict(model.config , A_ , A_ )
with torch.no_grad():
lowerCAmelCase = model(**A_ )[0]
lowerCAmelCase = torch.Size((1, 11, 1024) )
self.assertEqual(output.shape , A_ )
# change to expected output here
lowerCAmelCase = torch.tensor(
[[-0.7_7_8_0, -0.1_6_7_6, 0.1_0_3_8], [-6.7_5_5_6, -1.3_9_9_2, 0.0_5_6_7], [-7.5_3_8_3, -0.5_9_2_0, -0.2_7_7_9]] , device=A_ )
self.assertTrue(torch.allclose(output[:, :3, :3] , A_ , atol=A_ ) )
def __snake_case ( self ) -> Dict:
lowerCAmelCase = MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""" ).to(A_ )
# change to intended input
lowerCAmelCase = _long_tensor([[12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38, 2]] )
lowerCAmelCase = _long_tensor([[2, 12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38]] )
lowerCAmelCase = prepare_mam_aaa_inputs_dict(model.config , A_ , A_ )
with torch.no_grad():
lowerCAmelCase = model(**A_ )[0]
lowerCAmelCase = torch.Size((1, 11, model.config.vocab_size) )
self.assertEqual(output.shape , A_ )
# change to expected output here
lowerCAmelCase = torch.tensor(
[[-1.0_4_4_8, -1.0_4_1_1, 3.7_9_9_2], [-3.2_1_9_1, -3.2_3_8_6, -1.3_4_5_1], [-3.6_2_1_0, -3.5_9_9_3, 0.4_9_2_5]] , device=A_ )
self.assertTrue(torch.allclose(output[:, :3, :3] , A_ , atol=A_ ) )
def __snake_case ( self ) -> Union[str, Any]:
lowerCAmelCase = MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""" ).to(A_ )
lowerCAmelCase = MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M""" , src_lang="""fr""" , tgt_lang="""en""" )
lowerCAmelCase = [
"""L'affaire NSA souligne l'absence totale de débat sur le renseignement""",
"""Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""",
"""Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent"""
""" Fabius convoque l'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de"""
""" l'ampleur de la surveillance américaine sur l'ensemble des communications en France.""",
]
# The below article tests that we don't add any hypotheses outside of the top n_beams
lowerCAmelCase = tokenizer(A_ , padding=A_ , return_tensors="""pt""" )
lowerCAmelCase = model.generate(
input_ids=dct["""input_ids"""].to(A_ ) , attention_mask=dct["""attention_mask"""].to(A_ ) , num_beams=5 , forced_bos_token_id=tokenizer.get_lang_id("""en""" ) , )
lowerCAmelCase = [
"""The NSA case highlights the total absence of intelligence debate""",
"""I think there are two levels of response from the French government.""",
"""When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S."""
""" Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all"""
""" communications in France.""",
]
lowerCAmelCase = tokenizer.batch_decode(
hypotheses_batch.tolist() , clean_up_tokenization_spaces=A_ , skip_special_tokens=A_ )
assert generated == expected_en | 344 | 0 |
def __lowercase ( _UpperCamelCase ) ->List[Any]: # noqa: E741
"""simple docstring"""
lowercase : str = len(_UpperCamelCase )
lowercase : Dict = 0
lowercase : int = [0] * n
lowercase : Tuple = [False] * n
lowercase : Any = [False] * n
def dfs(_UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ):
if parent == root:
out_edge_count += 1
lowercase : Any = True
lowercase : str = at
for to in l[at]:
if to == parent:
pass
elif not visited[to]:
lowercase : Any = dfs(_UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase )
lowercase : int = min(low[at], low[to] )
# AP found via bridge
if at < low[to]:
lowercase : Union[str, Any] = True
# AP found via cycle
if at == low[to]:
lowercase : Tuple = True
else:
lowercase : Tuple = min(low[at], _UpperCamelCase )
return out_edge_count
for i in range(_UpperCamelCase ):
if not visited[i]:
lowercase : Optional[int] = 0
lowercase : int = dfs(_UpperCamelCase, _UpperCamelCase, -1, _UpperCamelCase )
lowercase : str = out_edge_count > 1
for x in range(len(_UpperCamelCase ) ):
if is_art[x] is True:
print(_UpperCamelCase )
# Adjacency list of graph
__a = {
0: [1, 2],
1: [0, 2],
2: [0, 1, 3, 5],
3: [2, 4],
4: [3],
5: [2, 6, 8],
6: [5, 7],
7: [6, 8],
8: [5, 7],
}
compute_ap(data)
| 319 |
import functools
import logging
import os
import sys
import threading
from logging import (
CRITICAL, # NOQA
DEBUG, # NOQA
ERROR, # NOQA
FATAL, # NOQA
INFO, # NOQA
NOTSET, # NOQA
WARN, # NOQA
WARNING, # NOQA
)
from typing import Optional
import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib
__a = threading.Lock()
__a = None
__a = {
'''debug''': logging.DEBUG,
'''info''': logging.INFO,
'''warning''': logging.WARNING,
'''error''': logging.ERROR,
'''critical''': logging.CRITICAL,
}
__a = logging.WARNING
__a = True
def __lowercase ( ) ->str:
"""simple docstring"""
lowercase : Optional[int] = os.getenv('''TRANSFORMERS_VERBOSITY''', _UpperCamelCase )
if env_level_str:
if env_level_str in log_levels:
return log_levels[env_level_str]
else:
logging.getLogger().warning(
f"""Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, """
f"""has to be one of: { ', '.join(log_levels.keys() ) }""" )
return _default_log_level
def __lowercase ( ) ->str:
"""simple docstring"""
return __name__.split('''.''' )[0]
def __lowercase ( ) ->logging.Logger:
"""simple docstring"""
return logging.getLogger(_get_library_name() )
def __lowercase ( ) ->None:
"""simple docstring"""
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
lowercase : List[str] = logging.StreamHandler() # Set sys.stderr as stream.
lowercase : Any = sys.stderr.flush
# Apply our default configuration to the library root logger.
lowercase : Optional[Any] = _get_library_root_logger()
library_root_logger.addHandler(_default_handler )
library_root_logger.setLevel(_get_default_logging_level() )
lowercase : Dict = False
def __lowercase ( ) ->None:
"""simple docstring"""
global _default_handler
with _lock:
if not _default_handler:
return
lowercase : Optional[Any] = _get_library_root_logger()
library_root_logger.removeHandler(_default_handler )
library_root_logger.setLevel(logging.NOTSET )
lowercase : Tuple = None
def __lowercase ( ) ->int:
"""simple docstring"""
return log_levels
def __lowercase ( _UpperCamelCase = None ) ->logging.Logger:
"""simple docstring"""
if name is None:
lowercase : List[Any] = _get_library_name()
_configure_library_root_logger()
return logging.getLogger(_UpperCamelCase )
def __lowercase ( ) ->int:
"""simple docstring"""
_configure_library_root_logger()
return _get_library_root_logger().getEffectiveLevel()
def __lowercase ( _UpperCamelCase ) ->None:
"""simple docstring"""
_configure_library_root_logger()
_get_library_root_logger().setLevel(_UpperCamelCase )
def __lowercase ( ) ->str:
"""simple docstring"""
return set_verbosity(_UpperCamelCase )
def __lowercase ( ) ->List[Any]:
"""simple docstring"""
return set_verbosity(_UpperCamelCase )
def __lowercase ( ) ->Optional[Any]:
"""simple docstring"""
return set_verbosity(_UpperCamelCase )
def __lowercase ( ) ->Optional[Any]:
"""simple docstring"""
return set_verbosity(_UpperCamelCase )
def __lowercase ( ) ->None:
"""simple docstring"""
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().removeHandler(_default_handler )
def __lowercase ( ) ->None:
"""simple docstring"""
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().addHandler(_default_handler )
def __lowercase ( _UpperCamelCase ) ->None:
"""simple docstring"""
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(_UpperCamelCase )
def __lowercase ( _UpperCamelCase ) ->None:
"""simple docstring"""
_configure_library_root_logger()
assert handler is not None and handler not in _get_library_root_logger().handlers
_get_library_root_logger().removeHandler(_UpperCamelCase )
def __lowercase ( ) ->None:
"""simple docstring"""
_configure_library_root_logger()
lowercase : Union[str, Any] = False
def __lowercase ( ) ->None:
"""simple docstring"""
_configure_library_root_logger()
lowercase : Optional[int] = True
def __lowercase ( ) ->None:
"""simple docstring"""
lowercase : Any = _get_library_root_logger().handlers
for handler in handlers:
lowercase : int = logging.Formatter('''[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s''' )
handler.setFormatter(_UpperCamelCase )
def __lowercase ( ) ->None:
"""simple docstring"""
lowercase : Any = _get_library_root_logger().handlers
for handler in handlers:
handler.setFormatter(_UpperCamelCase )
def __lowercase ( self, *_UpperCamelCase, **_UpperCamelCase ) ->List[Any]:
"""simple docstring"""
lowercase : Optional[int] = os.getenv('''TRANSFORMERS_NO_ADVISORY_WARNINGS''', _UpperCamelCase )
if no_advisory_warnings:
return
self.warning(*_UpperCamelCase, **_UpperCamelCase )
__a = warning_advice
@functools.lru_cache(_UpperCamelCase )
def __lowercase ( self, *_UpperCamelCase, **_UpperCamelCase ) ->Optional[Any]:
"""simple docstring"""
self.warning(*_UpperCamelCase, **_UpperCamelCase )
__a = warning_once
class __SCREAMING_SNAKE_CASE :
def __init__( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): # pylint: disable=unused-argument
lowercase : Optional[int] = args[0] if args else None
def __iter__( self ):
return iter(self._iterator )
def __getattr__( self , SCREAMING_SNAKE_CASE__ ):
def empty_fn(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): # pylint: disable=unused-argument
return
return empty_fn
def __enter__( self ):
return self
def __exit__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
return
class __SCREAMING_SNAKE_CASE :
def __call__( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ):
if _tqdm_active:
return tqdm_lib.tqdm(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
else:
return EmptyTqdm(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
def __lowerCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ):
lowercase : Optional[Any] = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
def __lowerCamelCase ( self ):
if _tqdm_active:
return tqdm_lib.tqdm.get_lock()
__a = _tqdm_cls()
def __lowercase ( ) ->bool:
"""simple docstring"""
global _tqdm_active
return bool(_tqdm_active )
def __lowercase ( ) ->str:
"""simple docstring"""
global _tqdm_active
lowercase : Optional[Any] = True
hf_hub_utils.enable_progress_bars()
def __lowercase ( ) ->List[Any]:
"""simple docstring"""
global _tqdm_active
lowercase : Optional[int] = False
hf_hub_utils.disable_progress_bars()
| 319 | 1 |
'''simple docstring'''
def _lowerCAmelCase ( _lowerCAmelCase )-> float:
return 10 - x * x
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase )-> float:
# Bolzano theory in order to find if there is a root between a and b
if equation(_lowerCAmelCase ) * equation(_lowerCAmelCase ) >= 0:
raise ValueError('Wrong space!' )
__UpperCAmelCase = a
while (b - a) >= 0.01:
# Find middle point
__UpperCAmelCase = (a + b) / 2
# Check if middle point is root
if equation(_lowerCAmelCase ) == 0.0:
break
# Decide the side to repeat the steps
if equation(_lowerCAmelCase ) * equation(_lowerCAmelCase ) < 0:
__UpperCAmelCase = c
else:
__UpperCAmelCase = c
return c
if __name__ == "__main__":
import doctest
doctest.testmod()
print(bisection(-2, 5))
print(bisection(0, 6))
| 617 |
'''simple docstring'''
import collections
from typing import List, Optional, Union
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
from ..bert.tokenization_bert import BertTokenizer
_A: List[str] = logging.get_logger(__name__)
_A: Dict = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}
_A: int = {
"""vocab_file""": {
"""facebook/dpr-ctx_encoder-single-nq-base""": (
"""https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt"""
),
"""facebook/dpr-ctx_encoder-multiset-base""": (
"""https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt"""
),
},
"""tokenizer_file""": {
"""facebook/dpr-ctx_encoder-single-nq-base""": (
"""https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json"""
),
"""facebook/dpr-ctx_encoder-multiset-base""": (
"""https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json"""
),
},
}
_A: int = {
"""vocab_file""": {
"""facebook/dpr-question_encoder-single-nq-base""": (
"""https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt"""
),
"""facebook/dpr-question_encoder-multiset-base""": (
"""https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt"""
),
},
"""tokenizer_file""": {
"""facebook/dpr-question_encoder-single-nq-base""": (
"""https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json"""
),
"""facebook/dpr-question_encoder-multiset-base""": (
"""https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json"""
),
},
}
_A: Dict = {
"""vocab_file""": {
"""facebook/dpr-reader-single-nq-base""": (
"""https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt"""
),
"""facebook/dpr-reader-multiset-base""": (
"""https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt"""
),
},
"""tokenizer_file""": {
"""facebook/dpr-reader-single-nq-base""": (
"""https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json"""
),
"""facebook/dpr-reader-multiset-base""": (
"""https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json"""
),
},
}
_A: Any = {
"""facebook/dpr-ctx_encoder-single-nq-base""": 512,
"""facebook/dpr-ctx_encoder-multiset-base""": 512,
}
_A: Tuple = {
"""facebook/dpr-question_encoder-single-nq-base""": 512,
"""facebook/dpr-question_encoder-multiset-base""": 512,
}
_A: int = {
"""facebook/dpr-reader-single-nq-base""": 512,
"""facebook/dpr-reader-multiset-base""": 512,
}
_A: Union[str, Any] = {
"""facebook/dpr-ctx_encoder-single-nq-base""": {"""do_lower_case""": True},
"""facebook/dpr-ctx_encoder-multiset-base""": {"""do_lower_case""": True},
}
_A: List[Any] = {
"""facebook/dpr-question_encoder-single-nq-base""": {"""do_lower_case""": True},
"""facebook/dpr-question_encoder-multiset-base""": {"""do_lower_case""": True},
}
_A: Dict = {
"""facebook/dpr-reader-single-nq-base""": {"""do_lower_case""": True},
"""facebook/dpr-reader-multiset-base""": {"""do_lower_case""": True},
}
class UpperCAmelCase ( UpperCAmelCase_ ):
_A : Tuple = VOCAB_FILES_NAMES
_A : Dict = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
_A : Any = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_A : Optional[Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION
class UpperCAmelCase ( UpperCAmelCase_ ):
_A : List[str] = VOCAB_FILES_NAMES
_A : str = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
_A : Union[str, Any] = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_A : int = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION
_A: Any = collections.namedtuple(
"""DPRSpanPrediction""", ["""span_score""", """relevance_score""", """doc_id""", """start_index""", """end_index""", """text"""]
)
_A: Tuple = collections.namedtuple("""DPRReaderOutput""", ["""start_logits""", """end_logits""", """relevance_logits"""])
_A: Optional[Any] = r"""
Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.
It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),
using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`
with the format:
```
[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>
```
Args:
questions (`str` or `List[str]`):
The questions to be encoded. You can specify one question for many passages. In this case, the question
will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in
`titles` or `texts`.
titles (`str` or `List[str]`):
The passages titles to be encoded. This can be a string or a list of strings if there are several passages.
texts (`str` or `List[str]`):
The passages texts to be encoded. This can be a string or a list of strings if there are several passages.
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
Activates and controls padding. Accepts the following values:
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence
if provided).
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
acceptable input length for the model if that argument is not provided.
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
lengths).
truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
Activates and controls truncation. Accepts the following values:
- `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to
the maximum acceptable input length for the model if that argument is not provided. This will truncate
token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch
of pairs) is provided.
- `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
acceptable input length for the model if that argument is not provided. This will only truncate the first
sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
- `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
acceptable input length for the model if that argument is not provided. This will only truncate the
second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
- `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
greater than the model maximum admissible input size).
max_length (`int`, *optional*):
Controls the maximum length to use by one of the truncation/padding parameters.
If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
is required by one of the truncation/padding parameters. If the model has no specific maximum input
length (like XLNet) truncation/padding to a maximum length will be deactivated.
return_tensors (`str` or [`~utils.TensorType`], *optional*):
If set, will return tensors instead of list of python integers. Acceptable values are:
- `'tf'`: Return TensorFlow `tf.constant` objects.
- `'pt'`: Return PyTorch `torch.Tensor` objects.
- `'np'`: Return Numpy `np.ndarray` objects.
return_attention_mask (`bool`, *optional*):
Whether or not to return the attention mask. If not set, will return the attention mask according to the
specific tokenizer's default, defined by the `return_outputs` attribute.
[What are attention masks?](../glossary#attention-mask)
Returns:
`Dict[str, List[List[int]]]`: A dictionary with the following keys:
- `input_ids`: List of token ids to be fed to a model.
- `attention_mask`: List of indices specifying which tokens should be attended to by the model.
"""
@add_start_docstrings(UpperCAmelCase_ )
class UpperCAmelCase :
def __call__( self , __A , __A = None , __A = None , __A = False , __A = False , __A = None , __A = None , __A = None , **__A , ):
if titles is None and texts is None:
return super().__call__(
__A , padding=__A , truncation=__A , max_length=__A , return_tensors=__A , return_attention_mask=__A , **__A , )
elif titles is None or texts is None:
__UpperCAmelCase = titles if texts is None else texts
return super().__call__(
__A , __A , padding=__A , truncation=__A , max_length=__A , return_tensors=__A , return_attention_mask=__A , **__A , )
__UpperCAmelCase = titles if not isinstance(__A , __A ) else [titles]
__UpperCAmelCase = texts if not isinstance(__A , __A ) else [texts]
__UpperCAmelCase = len(__A )
__UpperCAmelCase = questions if not isinstance(__A , __A ) else [questions] * n_passages
if len(__A ) != len(__A ):
raise ValueError(
f'There should be as many titles than texts but got {len(__A )} titles and {len(__A )} texts.' )
__UpperCAmelCase = super().__call__(__A , __A , padding=__A , truncation=__A )['input_ids']
__UpperCAmelCase = super().__call__(__A , add_special_tokens=__A , padding=__A , truncation=__A )['input_ids']
__UpperCAmelCase = {
'input_ids': [
(encoded_question_and_title + encoded_text)[:max_length]
if max_length is not None and truncation
else encoded_question_and_title + encoded_text
for encoded_question_and_title, encoded_text in zip(__A , __A )
]
}
if return_attention_mask is not False:
__UpperCAmelCase = []
for input_ids in encoded_inputs["input_ids"]:
attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] )
__UpperCAmelCase = attention_mask
return self.pad(__A , padding=__A , max_length=__A , return_tensors=__A )
def __lowerCamelCase ( self , __A , __A , __A = 16 , __A = 64 , __A = 4 , ):
__UpperCAmelCase = reader_input['input_ids']
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = reader_output[:3]
__UpperCAmelCase = len(__A )
__UpperCAmelCase = sorted(range(__A ) , reverse=__A , key=relevance_logits.__getitem__ )
__UpperCAmelCase = []
for doc_id in sorted_docs:
__UpperCAmelCase = list(input_ids[doc_id] )
# assuming question & title information is at the beginning of the sequence
__UpperCAmelCase = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id
if sequence_ids[-1] == self.pad_token_id:
__UpperCAmelCase = sequence_ids.index(self.pad_token_id )
else:
__UpperCAmelCase = len(__A )
__UpperCAmelCase = self._get_best_spans(
start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=__A , top_spans=__A , )
for start_index, end_index in best_spans:
start_index += passage_offset
end_index += passage_offset
nbest_spans_predictions.append(
DPRSpanPrediction(
span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=__A , start_index=__A , end_index=__A , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) )
if len(__A ) >= num_spans:
break
return nbest_spans_predictions[:num_spans]
def __lowerCamelCase ( self , __A , __A , __A , __A , ):
__UpperCAmelCase = []
for start_index, start_score in enumerate(__A ):
for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ):
scores.append(((start_index, start_index + answer_length), start_score + end_score) )
__UpperCAmelCase = sorted(__A , key=lambda __A : x[1] , reverse=__A )
__UpperCAmelCase = []
for (start_index, end_index), score in scores:
if start_index > end_index:
raise ValueError(f'Wrong span indices: [{start_index}:{end_index}]' )
__UpperCAmelCase = end_index - start_index + 1
if length > max_answer_length:
raise ValueError(f'Span is too long: {length} > {max_answer_length}' )
if any(
start_index <= prev_start_index <= prev_end_index <= end_index
or prev_start_index <= start_index <= end_index <= prev_end_index
for (prev_start_index, prev_end_index) in chosen_span_intervals ):
continue
chosen_span_intervals.append((start_index, end_index) )
if len(__A ) == top_spans:
break
return chosen_span_intervals
@add_end_docstrings(UpperCAmelCase_ )
class UpperCAmelCase ( UpperCAmelCase_ , UpperCAmelCase_ ):
_A : Optional[int] = VOCAB_FILES_NAMES
_A : Optional[int] = READER_PRETRAINED_VOCAB_FILES_MAP
_A : Dict = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_A : Union[str, Any] = READER_PRETRAINED_INIT_CONFIGURATION
_A : List[Any] = ["""input_ids""", """attention_mask"""]
| 617 | 1 |
"""simple docstring"""
import argparse
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt
if __name__ == "__main__":
SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser()
parser.add_argument(
'--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.'
)
parser.add_argument(
'--original_config_file',
type=str,
required=True,
help='The YAML config file corresponding to the original architecture.',
)
parser.add_argument(
'--num_in_channels',
default=None,
type=int,
help='The number of input channels. If `None` number of input channels will be automatically inferred.',
)
parser.add_argument(
'--image_size',
default=512,
type=int,
help=(
'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2'
' Base. Use 768 for Stable Diffusion v2.'
),
)
parser.add_argument(
'--extract_ema',
action='store_true',
help=(
'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights'
' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield'
' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.'
),
)
parser.add_argument(
'--upcast_attention',
action='store_true',
help=(
'Whether the attention computation should always be upcasted. This is necessary when running stable'
' diffusion 2.1.'
),
)
parser.add_argument(
'--from_safetensors',
action='store_true',
help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.',
)
parser.add_argument(
'--to_safetensors',
action='store_true',
help='Whether to store pipeline in safetensors format or not.',
)
parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.')
parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)')
def __snake_case ( _lowercase ):
"""simple docstring"""
if string == "True":
return True
elif string == "False":
return False
else:
raise ValueError(f'could not parse string as bool {string}' )
parser.add_argument(
'--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool
)
parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int)
SCREAMING_SNAKE_CASE_ = parser.parse_args()
SCREAMING_SNAKE_CASE_ = download_controlnet_from_original_ckpt(
checkpoint_path=args.checkpoint_path,
original_config_file=args.original_config_file,
image_size=args.image_size,
extract_ema=args.extract_ema,
num_in_channels=args.num_in_channels,
upcast_attention=args.upcast_attention,
from_safetensors=args.from_safetensors,
device=args.device,
use_linear_projection=args.use_linear_projection,
cross_attention_dim=args.cross_attention_dim,
)
controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) | 34 |
import argparse
import torch
from transformers import RemBertConfig, RemBertModel, load_tf_weights_in_rembert
from transformers.utils import logging
logging.set_verbosity_info()
def __lowerCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Optional[Any]:
# Initialise PyTorch model
_UpperCAmelCase = RemBertConfig.from_json_file(_lowerCAmelCase )
print("Building PyTorch model from configuration: {}".format(str(_lowerCAmelCase ) ) )
_UpperCAmelCase = RemBertModel(_lowerCAmelCase )
# Load weights from tf checkpoint
load_tf_weights_in_rembert(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
# Save pytorch-model
print("Save PyTorch model to {}".format(_lowerCAmelCase ) )
torch.save(model.state_dict() , _lowerCAmelCase )
if __name__ == "__main__":
__lowerCAmelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
)
parser.add_argument(
"--rembert_config_file",
default=None,
type=str,
required=True,
help=(
"The config json file corresponding to the pre-trained RemBERT model. \n"
"This specifies the model architecture."
),
)
parser.add_argument(
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
__lowerCAmelCase = parser.parse_args()
convert_rembert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.rembert_config_file, args.pytorch_dump_path)
| 684 | 0 |
'''simple docstring'''
from __future__ import annotations
def __lowerCAmelCase ( snake_case__ = 4 ):
__UpperCamelCase : Optional[Any] = abs(snake_case__ ) or 4
return [[1 + x + y * row_size for x in range(snake_case__ )] for y in range(snake_case__ )]
def __lowerCAmelCase ( snake_case__ ):
return reverse_row(transpose(snake_case__ ) )
# OR.. transpose(reverse_column(matrix))
def __lowerCAmelCase ( snake_case__ ):
return reverse_row(reverse_column(snake_case__ ) )
# OR.. reverse_column(reverse_row(matrix))
def __lowerCAmelCase ( snake_case__ ):
return reverse_column(transpose(snake_case__ ) )
# OR.. transpose(reverse_row(matrix))
def __lowerCAmelCase ( snake_case__ ):
__UpperCamelCase : Any = [list(snake_case__ ) for x in zip(*snake_case__ )]
return matrix
def __lowerCAmelCase ( snake_case__ ):
__UpperCamelCase : Dict = matrix[::-1]
return matrix
def __lowerCAmelCase ( snake_case__ ):
__UpperCamelCase : Optional[Any] = [x[::-1] for x in matrix]
return matrix
def __lowerCAmelCase ( snake_case__ ):
for i in matrix:
print(*snake_case__ )
if __name__ == "__main__":
_lowerCAmelCase = make_matrix()
print('''\norigin:\n''')
print_matrix(matrix)
print('''\nrotate 90 counterclockwise:\n''')
print_matrix(rotate_aa(matrix))
_lowerCAmelCase = make_matrix()
print('''\norigin:\n''')
print_matrix(matrix)
print('''\nrotate 180:\n''')
print_matrix(rotate_aaa(matrix))
_lowerCAmelCase = make_matrix()
print('''\norigin:\n''')
print_matrix(matrix)
print('''\nrotate 270 counterclockwise:\n''')
print_matrix(rotate_aaa(matrix))
| 399 |
'''simple docstring'''
def __lowerCAmelCase ( snake_case__ ):
if not grid or not grid[0]:
raise TypeError("The grid does not contain the appropriate information" )
for cell_n in range(1 , len(grid[0] ) ):
grid[0][cell_n] += grid[0][cell_n - 1]
__UpperCamelCase : List[str] = grid[0]
for row_n in range(1 , len(snake_case__ ) ):
__UpperCamelCase : Tuple = grid[row_n]
__UpperCamelCase : int = fill_row(snake_case__ , snake_case__ )
__UpperCamelCase : List[str] = grid[row_n]
return grid[-1][-1]
def __lowerCAmelCase ( snake_case__ , snake_case__ ):
current_row[0] += row_above[0]
for cell_n in range(1 , len(snake_case__ ) ):
current_row[cell_n] += min(current_row[cell_n - 1] , row_above[cell_n] )
return current_row
if __name__ == "__main__":
import doctest
doctest.testmod()
| 399 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.