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
|
---|---|---|---|---|
from math import factorial
def a ( A__ = 2_0 ) -> int:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Tuple = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1,
# 2, 3,...
SCREAMING_SNAKE_CASE__ : Dict = n // 2
return int(factorial(A__ ) / (factorial(A__ ) * factorial(n - k )) )
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
print(solution(20))
else:
try:
a_ :str = int(sys.argv[1])
print(solution(n))
except ValueError:
print('Invalid entry - please enter a number.')
| 35 |
lowerCAmelCase_ = {
"A": ["B", "C", "E"],
"B": ["A", "D", "E"],
"C": ["A", "F", "G"],
"D": ["B"],
"E": ["A", "B", "D"],
"F": ["C"],
"G": ["C"],
}
def A_ ( lowercase_ , lowercase_ , lowercase_ ) -> list[str]:
_snake_case : List[Any] = set()
# keep track of all the paths to be checked
_snake_case : Union[str, Any] = [[start]]
# return path if start is goal
if start == goal:
return [start]
# keeps looping until all possible paths have been checked
while queue:
# pop the first path from the queue
_snake_case : Optional[int] = queue.pop(0 )
# get the last node from the path
_snake_case : Any = path[-1]
if node not in explored:
_snake_case : List[Any] = graph[node]
# go through all neighbour nodes, construct a new path and
# push it into the queue
for neighbour in neighbours:
_snake_case : List[Any] = list(lowercase_ )
new_path.append(lowercase_ )
queue.append(lowercase_ )
# return path if neighbour is goal
if neighbour == goal:
return new_path
# mark node as explored
explored.add(lowercase_ )
# in case there's no path between the 2 nodes
return []
def A_ ( lowercase_ , lowercase_ , lowercase_ ) -> int:
if not graph or start not in graph or target not in graph:
return -1
if start == target:
return 0
_snake_case : Optional[int] = [start]
_snake_case : Optional[Any] = set(lowercase_ )
# Keep tab on distances from `start` node.
_snake_case : Tuple = {start: 0, target: -1}
while queue:
_snake_case : List[Any] = queue.pop(0 )
if node == target:
_snake_case : int = (
dist[node] if dist[target] == -1 else min(dist[target] , dist[node] )
)
for adjacent in graph[node]:
if adjacent not in visited:
visited.add(lowercase_ )
queue.append(lowercase_ )
_snake_case : int = dist[node] + 1
return dist[target]
if __name__ == "__main__":
print(bfs_shortest_path(demo_graph, "G", "D")) # returns ['G', 'C', 'A', 'B', 'D']
print(bfs_shortest_path_distance(demo_graph, "G", "D")) # returns 4
| 326 | 0 |
import json
import logging
import os
import sys
from time import time
from unittest.mock import patch
from transformers.testing_utils import TestCasePlus, require_torch_tpu
logging.basicConfig(level=logging.DEBUG)
snake_case__ : List[Any] = logging.getLogger()
def _snake_case (__lowercase):
UpperCamelCase_ = {}
UpperCamelCase_ = os.path.join(__lowercase , 'all_results.json')
if os.path.exists(__lowercase):
with open(__lowercase , 'r') as f:
UpperCamelCase_ = json.load(__lowercase)
else:
raise ValueError(f"""can't find {path}""")
return results
snake_case__ : Optional[int] = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
@require_torch_tpu
class _a ( UpperCAmelCase__ ):
"""simple docstring"""
def _UpperCAmelCase ( self ) -> str:
import xla_spawn
UpperCamelCase_ = self.get_auto_remove_tmp_dir()
UpperCamelCase_ = f"""
./examples/pytorch/text-classification/run_glue.py
--num_cores=8
./examples/pytorch/text-classification/run_glue.py
--model_name_or_path distilbert-base-uncased
--output_dir {tmp_dir}
--overwrite_output_dir
--train_file ./tests/fixtures/tests_samples/MRPC/train.csv
--validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
--do_train
--do_eval
--debug tpu_metrics_debug
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--learning_rate=1e-4
--max_steps=10
--warmup_steps=2
--seed=42
--max_seq_length=128
""".split()
with patch.object(_UpperCAmelCase , 'argv' , _UpperCAmelCase ):
UpperCamelCase_ = time()
xla_spawn.main()
UpperCamelCase_ = time()
UpperCamelCase_ = get_results(_UpperCAmelCase )
self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 )
# Assert that the script takes less than 500 seconds to make sure it doesn't hang.
self.assertLess(end - start , 500 )
def _UpperCAmelCase ( self ) -> int:
import xla_spawn
UpperCamelCase_ = '\n ./tests/test_trainer_tpu.py\n --num_cores=8\n ./tests/test_trainer_tpu.py\n '.split()
with patch.object(_UpperCAmelCase , 'argv' , _UpperCAmelCase ):
xla_spawn.main()
| 719 |
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer
from transformers.testing_utils import require_tokenizers, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor
@require_tokenizers
@require_vision
class _a ( unittest.TestCase ):
"""simple docstring"""
def _UpperCAmelCase ( self ) -> Dict:
UpperCamelCase_ = tempfile.mkdtemp()
# fmt: off
UpperCamelCase_ = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest']
# fmt: on
UpperCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] )
with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer:
vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) )
UpperCamelCase_ = {
'do_resize': True,
'size': {'height': 18, 'width': 18},
'do_normalize': True,
'image_mean': [0.5, 0.5, 0.5],
'image_std': [0.5, 0.5, 0.5],
}
UpperCamelCase_ = os.path.join(self.tmpdirname , _UpperCAmelCase )
with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
def _UpperCAmelCase ( self , **_UpperCAmelCase ) -> Optional[Any]:
return BertTokenizer.from_pretrained(self.tmpdirname , **_UpperCAmelCase )
def _UpperCAmelCase ( self , **_UpperCAmelCase ) -> Optional[int]:
return ViTImageProcessor.from_pretrained(self.tmpdirname , **_UpperCAmelCase )
def _UpperCAmelCase ( self ) -> Any:
shutil.rmtree(self.tmpdirname )
def _UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
UpperCamelCase_ = [Image.fromarray(np.moveaxis(_UpperCAmelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def _UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase_ = self.get_tokenizer()
UpperCamelCase_ = self.get_image_processor()
UpperCamelCase_ = VisionTextDualEncoderProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
processor.save_pretrained(self.tmpdirname )
UpperCamelCase_ = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertIsInstance(processor.image_processor , _UpperCAmelCase )
def _UpperCAmelCase ( self ) -> Optional[Any]:
UpperCamelCase_ = VisionTextDualEncoderProcessor(
tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
UpperCamelCase_ = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' )
UpperCamelCase_ = self.get_image_processor(do_normalize=_UpperCAmelCase , padding_value=1.0 )
UpperCamelCase_ = VisionTextDualEncoderProcessor.from_pretrained(
self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_UpperCAmelCase , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _UpperCAmelCase )
def _UpperCAmelCase ( self ) -> str:
UpperCamelCase_ = self.get_image_processor()
UpperCamelCase_ = self.get_tokenizer()
UpperCamelCase_ = VisionTextDualEncoderProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
UpperCamelCase_ = self.prepare_image_inputs()
UpperCamelCase_ = image_processor(_UpperCAmelCase , return_tensors='np' )
UpperCamelCase_ = processor(images=_UpperCAmelCase , 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 _UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase_ = self.get_image_processor()
UpperCamelCase_ = self.get_tokenizer()
UpperCamelCase_ = VisionTextDualEncoderProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
UpperCamelCase_ = 'lower newer'
UpperCamelCase_ = processor(text=_UpperCAmelCase )
UpperCamelCase_ = tokenizer(_UpperCAmelCase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def _UpperCAmelCase ( self ) -> Any:
UpperCamelCase_ = self.get_image_processor()
UpperCamelCase_ = self.get_tokenizer()
UpperCamelCase_ = VisionTextDualEncoderProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
UpperCamelCase_ = 'lower newer'
UpperCamelCase_ = self.prepare_image_inputs()
UpperCamelCase_ = processor(text=_UpperCAmelCase , images=_UpperCAmelCase )
self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] )
# test if it raises when no input is passed
with self.assertRaises(_UpperCAmelCase ):
processor()
def _UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase_ = self.get_image_processor()
UpperCamelCase_ = self.get_tokenizer()
UpperCamelCase_ = VisionTextDualEncoderProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
UpperCamelCase_ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
UpperCamelCase_ = processor.batch_decode(_UpperCAmelCase )
UpperCamelCase_ = tokenizer.batch_decode(_UpperCAmelCase )
self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase )
def _UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase_ = self.get_image_processor()
UpperCamelCase_ = self.get_tokenizer()
UpperCamelCase_ = VisionTextDualEncoderProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
UpperCamelCase_ = 'lower newer'
UpperCamelCase_ = self.prepare_image_inputs()
UpperCamelCase_ = processor(text=_UpperCAmelCase , images=_UpperCAmelCase )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 618 | 0 |
import os
import re
import shutil
import sys
import tempfile
import unittest
import black
SCREAMING_SNAKE_CASE : List[Any] = 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.
SCREAMING_SNAKE_CASE : Optional[Any] = " 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 _lowerCamelCase( unittest.TestCase ):
def UpperCamelCase ( self) -> str:
"""simple docstring"""
_lowercase : Optional[Any] = tempfile.mkdtemp()
os.makedirs(os.path.join(self.transformer_dir, 'models/bert/'))
_lowercase : List[Any] = self.transformer_dir
shutil.copy(
os.path.join(lowerCamelCase, 'src/transformers/models/bert/modeling_bert.py'), os.path.join(self.transformer_dir, 'models/bert/modeling_bert.py'), )
def UpperCamelCase ( self) -> Any:
"""simple docstring"""
_lowercase : Optional[Any] = 'src/transformers'
shutil.rmtree(self.transformer_dir)
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=None) -> str:
"""simple docstring"""
_lowercase : Optional[Any] = comment + F'''\nclass {class_name}(nn.Module):\n''' + class_code
if overwrite_result is not None:
_lowercase : Optional[int] = comment + F'''\nclass {class_name}(nn.Module):\n''' + overwrite_result
_lowercase : Dict = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=1_19)
_lowercase : Union[str, Any] = black.format_str(lowerCamelCase, mode=lowerCamelCase)
_lowercase : Optional[int] = os.path.join(self.transformer_dir, 'new_code.py')
with open(lowerCamelCase, 'w', newline='\n') as f:
f.write(lowerCamelCase)
if overwrite_result is None:
self.assertTrue(len(check_copies.is_copy_consistent(lowerCamelCase)) == 0)
else:
check_copies.is_copy_consistent(f.name, overwrite=lowerCamelCase)
with open(lowerCamelCase, 'r') as f:
self.assertTrue(f.read(), lowerCamelCase)
def UpperCamelCase ( self) -> Dict:
"""simple docstring"""
_lowercase : Tuple = check_copies.find_code_in_transformers('models.bert.modeling_bert.BertLMPredictionHead')
self.assertEqual(lowerCamelCase, lowerCamelCase)
def UpperCamelCase ( self) -> Optional[Any]:
"""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', lowerCamelCase, )
# Copy consistency with rename
self.check_copy_consistency(
'# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel', 'TestModelLMPredictionHead', re.sub('Bert', 'TestModel', lowerCamelCase), )
# Copy consistency with a really long name
_lowercase : Tuple = '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', lowerCamelCase, lowerCamelCase), )
# Copy consistency with overwrite
self.check_copy_consistency(
'# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel', 'TestModelLMPredictionHead', lowerCamelCase, overwrite_result=re.sub('Bert', 'TestModel', lowerCamelCase), )
def UpperCamelCase ( self) -> Any:
"""simple docstring"""
_lowercase : Tuple = check_copies.LOCALIZED_READMES['README_zh-hans.md']
_lowercase : List[Any] = (
'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.'
)
_lowercase : Tuple = (
'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'
)
_lowercase : List[Any] = (
'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'
)
_lowercase , _lowercase : List[Any] = check_copies.convert_to_localized_md(
lowerCamelCase, lowerCamelCase, localized_readme['format_model_list'])
self.assertFalse(lowerCamelCase)
self.assertEqual(lowerCamelCase, lowerCamelCase)
_lowercase , _lowercase : List[str] = check_copies.convert_to_localized_md(
lowerCamelCase, lowerCamelCase, localized_readme['format_model_list'])
# Check whether the number of models is equal to README.md after conversion.
self.assertTrue(lowerCamelCase)
_lowercase : Union[str, Any] = (
'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.'
)
_lowercase : Tuple = (
'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'
)
_lowercase : Optional[int] = (
'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'
)
_lowercase , _lowercase : Dict = check_copies.convert_to_localized_md(
lowerCamelCase, lowerCamelCase, localized_readme['format_model_list'])
# Check if the model link is synchronized.
self.assertEqual(lowerCamelCase, lowerCamelCase)
| 89 |
'''simple docstring'''
import math
import numpy as np
import qiskit
from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute
def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = 3 ):
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
raise TypeError('number of qubits must be a integer.' )
if number_of_qubits <= 0:
raise ValueError('number of qubits must be > 0.' )
if math.floor(_SCREAMING_SNAKE_CASE ) != number_of_qubits:
raise ValueError('number of qubits must be exact integer.' )
if number_of_qubits > 10:
raise ValueError('number of qubits too large to simulate(>10).' )
__a : Dict = QuantumRegister(_SCREAMING_SNAKE_CASE , 'qr' )
__a : List[str] = ClassicalRegister(_SCREAMING_SNAKE_CASE , 'cr' )
__a : List[Any] = QuantumCircuit(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
__a : Optional[int] = number_of_qubits
for i in range(_SCREAMING_SNAKE_CASE ):
quantum_circuit.h(number_of_qubits - i - 1 )
counter -= 1
for j in range(_SCREAMING_SNAKE_CASE ):
quantum_circuit.cp(np.pi / 2 ** (counter - j) , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
for k in range(number_of_qubits // 2 ):
quantum_circuit.swap(_SCREAMING_SNAKE_CASE , number_of_qubits - k - 1 )
# measure all the qubits
quantum_circuit.measure(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# simulate with 10000 shots
__a : Union[str, Any] = Aer.get_backend('qasm_simulator' )
__a : Any = execute(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , shots=10_000 )
return job.result().get_counts(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
print(
f'''Total count for quantum fourier transform state is: \
{quantum_fourier_transform(3)}'''
)
| 476 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available
UpperCAmelCase__ : str = {
"configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase__ : Dict = [
"ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST",
"ErnieForCausalLM",
"ErnieForMaskedLM",
"ErnieForMultipleChoice",
"ErnieForNextSentencePrediction",
"ErnieForPreTraining",
"ErnieForQuestionAnswering",
"ErnieForSequenceClassification",
"ErnieForTokenClassification",
"ErnieModel",
"ErniePreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_ernie import (
ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,
ErnieForCausalLM,
ErnieForMaskedLM,
ErnieForMultipleChoice,
ErnieForNextSentencePrediction,
ErnieForPreTraining,
ErnieForQuestionAnswering,
ErnieForSequenceClassification,
ErnieForTokenClassification,
ErnieModel,
ErniePreTrainedModel,
)
else:
import sys
UpperCAmelCase__ : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 708 |
import importlib
import inspect
import json
import os
import re
import shutil
import sys
from pathlib import Path
from typing import Dict, Optional, Union
from urllib import request
from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info
from packaging import version
from .. import __version__
from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging
UpperCAmelCase__ : List[str] = (
"""https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py"""
)
UpperCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name
def __lowercase ( ) -> List[Any]:
SCREAMING_SNAKE_CASE : Optional[int] = """https://pypi.org/pypi/diffusers/json"""
SCREAMING_SNAKE_CASE : Dict = json.loads(request.urlopen(_A ).read() )["""releases"""].keys()
return sorted(_A , key=lambda _A : version.Version(_A ) )
def __lowercase ( ) -> Any:
# This function has already been executed if HF_MODULES_CACHE already is in the Python path.
if HF_MODULES_CACHE in sys.path:
return
sys.path.append(_A )
os.makedirs(_A , exist_ok=_A )
SCREAMING_SNAKE_CASE : Dict = Path(_A ) / """__init__.py"""
if not init_path.exists():
init_path.touch()
def __lowercase ( _A ) -> Any:
init_hf_modules()
SCREAMING_SNAKE_CASE : Any = Path(_A ) / name
# If the parent module does not exist yet, recursively create it.
if not dynamic_module_path.parent.exists():
create_dynamic_module(dynamic_module_path.parent )
os.makedirs(_A , exist_ok=_A )
SCREAMING_SNAKE_CASE : str = dynamic_module_path / """__init__.py"""
if not init_path.exists():
init_path.touch()
def __lowercase ( _A ) -> Optional[int]:
with open(_A , """r""" , encoding="""utf-8""" ) as f:
SCREAMING_SNAKE_CASE : Any = f.read()
# Imports of the form `import .xxx`
SCREAMING_SNAKE_CASE : List[str] = re.findall("""^\s*import\s+\.(\S+)\s*$""" , _A , flags=re.MULTILINE )
# Imports of the form `from .xxx import yyy`
relative_imports += re.findall("""^\s*from\s+\.(\S+)\s+import""" , _A , flags=re.MULTILINE )
# Unique-ify
return list(set(_A ) )
def __lowercase ( _A ) -> Optional[Any]:
SCREAMING_SNAKE_CASE : Union[str, Any] = False
SCREAMING_SNAKE_CASE : List[Any] = [module_file]
SCREAMING_SNAKE_CASE : Any = []
# Let's recurse through all relative imports
while not no_change:
SCREAMING_SNAKE_CASE : List[str] = []
for f in files_to_check:
new_imports.extend(get_relative_imports(_A ) )
SCREAMING_SNAKE_CASE : List[str] = Path(_A ).parent
SCREAMING_SNAKE_CASE : int = [str(module_path / m ) for m in new_imports]
SCREAMING_SNAKE_CASE : int = [f for f in new_import_files if f not in all_relative_imports]
SCREAMING_SNAKE_CASE : Optional[Any] = [F"{f}.py" for f in new_import_files]
SCREAMING_SNAKE_CASE : List[Any] = len(_A ) == 0
all_relative_imports.extend(_A )
return all_relative_imports
def __lowercase ( _A ) -> Union[str, Any]:
with open(_A , """r""" , encoding="""utf-8""" ) as f:
SCREAMING_SNAKE_CASE : List[Any] = f.read()
# Imports of the form `import xxx`
SCREAMING_SNAKE_CASE : Any = re.findall("""^\s*import\s+(\S+)\s*$""" , _A , flags=re.MULTILINE )
# Imports of the form `from xxx import yyy`
imports += re.findall("""^\s*from\s+(\S+)\s+import""" , _A , flags=re.MULTILINE )
# Only keep the top-level module
SCREAMING_SNAKE_CASE : List[Any] = [imp.split(""".""" )[0] for imp in imports if not imp.startswith(""".""" )]
# Unique-ify and test we got them all
SCREAMING_SNAKE_CASE : Dict = list(set(_A ) )
SCREAMING_SNAKE_CASE : Dict = []
for imp in imports:
try:
importlib.import_module(_A )
except ImportError:
missing_packages.append(_A )
if len(_A ) > 0:
raise ImportError(
"""This modeling file requires the following packages that were not found in your environment: """
F"{', '.join(_A )}. Run `pip install {' '.join(_A )}`" )
return get_relative_imports(_A )
def __lowercase ( _A , _A ) -> List[str]:
SCREAMING_SNAKE_CASE : int = module_path.replace(os.path.sep , """.""" )
SCREAMING_SNAKE_CASE : List[str] = importlib.import_module(_A )
if class_name is None:
return find_pipeline_class(_A )
return getattr(_A , _A )
def __lowercase ( _A ) -> Optional[int]:
from ..pipelines import DiffusionPipeline
SCREAMING_SNAKE_CASE : Tuple = dict(inspect.getmembers(_A , inspect.isclass ) )
SCREAMING_SNAKE_CASE : Dict = None
for cls_name, cls in cls_members.items():
if (
cls_name != DiffusionPipeline.__name__
and issubclass(cls , _A )
and cls.__module__.split(""".""" )[0] != "diffusers"
):
if pipeline_class is not None:
raise ValueError(
F"Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:"
F" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in"
F" {loaded_module}." )
SCREAMING_SNAKE_CASE : List[str] = cls
return pipeline_class
def __lowercase ( _A , _A , _A = None , _A = False , _A = False , _A = None , _A = None , _A = None , _A = False , ) -> List[str]:
SCREAMING_SNAKE_CASE : List[str] = str(_A )
SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_A , _A )
if os.path.isfile(_A ):
SCREAMING_SNAKE_CASE : Union[str, Any] = module_file_or_url
SCREAMING_SNAKE_CASE : Dict = """local"""
elif pretrained_model_name_or_path.count("""/""" ) == 0:
SCREAMING_SNAKE_CASE : Tuple = get_diffusers_versions()
# cut ".dev0"
SCREAMING_SNAKE_CASE : str = """v""" + """.""".join(__version__.split(""".""" )[:3] )
# retrieve github version that matches
if revision is None:
SCREAMING_SNAKE_CASE : Any = latest_version if latest_version[1:] in available_versions else """main"""
logger.info(F"Defaulting to latest_version: {revision}." )
elif revision in available_versions:
SCREAMING_SNAKE_CASE : List[Any] = F"v{revision}"
elif revision == "main":
SCREAMING_SNAKE_CASE : Union[str, Any] = revision
else:
raise ValueError(
F"`custom_revision`: {revision} does not exist. Please make sure to choose one of"
F" {', '.join(available_versions + ['main'] )}." )
# community pipeline on GitHub
SCREAMING_SNAKE_CASE : Tuple = COMMUNITY_PIPELINES_URL.format(revision=_A , pipeline=_A )
try:
SCREAMING_SNAKE_CASE : str = cached_download(
_A , cache_dir=_A , force_download=_A , proxies=_A , resume_download=_A , local_files_only=_A , use_auth_token=_A , )
SCREAMING_SNAKE_CASE : Tuple = """git"""
SCREAMING_SNAKE_CASE : Optional[int] = pretrained_model_name_or_path + """.py"""
except EnvironmentError:
logger.error(F"Could not locate the {module_file} inside {pretrained_model_name_or_path}." )
raise
else:
try:
# Load from URL or cache if already cached
SCREAMING_SNAKE_CASE : int = hf_hub_download(
_A , _A , cache_dir=_A , force_download=_A , proxies=_A , resume_download=_A , local_files_only=_A , use_auth_token=_A , )
SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join("""local""" , """--""".join(pretrained_model_name_or_path.split("""/""" ) ) )
except EnvironmentError:
logger.error(F"Could not locate the {module_file} inside {pretrained_model_name_or_path}." )
raise
# Check we have all the requirements in our environment
SCREAMING_SNAKE_CASE : int = check_imports(_A )
# Now we move the module inside our cached dynamic modules.
SCREAMING_SNAKE_CASE : List[Any] = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
create_dynamic_module(_A )
SCREAMING_SNAKE_CASE : Tuple = Path(_A ) / full_submodule
if submodule == "local" or submodule == "git":
# We always copy local files (we could hash the file to see if there was a change, and give them the name of
# that hash, to only copy when there is a modification but it seems overkill for now).
# The only reason we do the copy is to avoid putting too many folders in sys.path.
shutil.copy(_A , submodule_path / module_file )
for module_needed in modules_needed:
SCREAMING_SNAKE_CASE : Optional[int] = F"{module_needed}.py"
shutil.copy(os.path.join(_A , _A ) , submodule_path / module_needed )
else:
# Get the commit hash
# TODO: we will get this info in the etag soon, so retrieve it from there and not here.
if isinstance(_A , _A ):
SCREAMING_SNAKE_CASE : Tuple = use_auth_token
elif use_auth_token is True:
SCREAMING_SNAKE_CASE : str = HfFolder.get_token()
else:
SCREAMING_SNAKE_CASE : Optional[int] = None
SCREAMING_SNAKE_CASE : List[Any] = model_info(_A , revision=_A , token=_A ).sha
# The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
# benefit of versioning.
SCREAMING_SNAKE_CASE : int = submodule_path / commit_hash
SCREAMING_SNAKE_CASE : Tuple = full_submodule + os.path.sep + commit_hash
create_dynamic_module(_A )
if not (submodule_path / module_file).exists():
shutil.copy(_A , submodule_path / module_file )
# Make sure we also have every file with relative
for module_needed in modules_needed:
if not (submodule_path / module_needed).exists():
get_cached_module_file(
_A , F"{module_needed}.py" , cache_dir=_A , force_download=_A , resume_download=_A , proxies=_A , use_auth_token=_A , revision=_A , local_files_only=_A , )
return os.path.join(_A , _A )
def __lowercase ( _A , _A , _A = None , _A = None , _A = False , _A = False , _A = None , _A = None , _A = None , _A = False , **_A , ) -> Tuple:
SCREAMING_SNAKE_CASE : Dict = get_cached_module_file(
_A , _A , cache_dir=_A , force_download=_A , resume_download=_A , proxies=_A , use_auth_token=_A , revision=_A , local_files_only=_A , )
return get_class_in_module(_A , final_module.replace(""".py""" , """""" ) )
| 446 | 0 |
from __future__ import annotations
import numpy as np
from numpy import floataa
from numpy.typing import NDArray
def UpperCAmelCase ( a_ , a_ , a_ , a_ , ) -> list[float]:
"""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(a_ )
if colsa != 1:
__A = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}'''
raise ValueError(a_ )
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(a_ )
if len(a_ ) != rowsa:
__A = (
"Number of initial values must be equal to number of rows in coefficient "
F'''matrix but received {len(a_ )} and {rowsa}'''
)
raise ValueError(a_ )
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(a_ )
# Iterates the whole matrix for given number of times
for _ in range(a_ ):
__A = []
for row in range(a_ ):
__A = 0
for col in range(a_ ):
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(a_ )
__A = new_val
return [float(a_ ) for i in new_val]
def UpperCAmelCase ( a_ ) -> bool:
"""simple docstring"""
__A , __A = table.shape
__A = True
for i in range(0 , a_ ):
__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()
| 55 |
from math import sqrt
def UpperCAmelCase ( a_ ) -> bool:
"""simple docstring"""
assert isinstance(a_ , a_ ) and (
number >= 0
), "'number' must been an int and positive"
__A = True
# 0 and 1 are none primes.
if number <= 1:
__A = False
for divisor in range(2 , int(round(sqrt(a_ ) ) ) + 1 ):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
__A = False
break
# precondition
assert isinstance(a_ , a_ ), "'status' must been from type bool"
return status
def UpperCAmelCase ( a_ ) -> Any:
"""simple docstring"""
assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
__A = list(range(2 , n + 1 ) )
__A = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(a_ ) ):
for j in range(i + 1 , len(a_ ) ):
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
__A = 0
# filters actual prime numbers.
__A = [x for x in begin_list if x != 0]
# precondition
assert isinstance(a_ , a_ ), "'ans' must been from type list"
return ans
def UpperCAmelCase ( a_ ) -> Optional[int]:
"""simple docstring"""
assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2"
__A = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2 , n + 1 ):
if is_prime(a_ ):
ans.append(a_ )
# precondition
assert isinstance(a_ , a_ ), "'ans' must been from type list"
return ans
def UpperCAmelCase ( a_ ) -> Optional[int]:
"""simple docstring"""
assert isinstance(a_ , a_ ) and number >= 0, "'number' must been an int and >= 0"
__A = [] # this list will be returns of the function.
# potential prime number factors.
__A = 2
__A = number
if number == 0 or number == 1:
ans.append(a_ )
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(a_ ):
while quotient != 1:
if is_prime(a_ ) and (quotient % factor == 0):
ans.append(a_ )
quotient /= factor
else:
factor += 1
else:
ans.append(a_ )
# precondition
assert isinstance(a_ , a_ ), "'ans' must been from type list"
return ans
def UpperCAmelCase ( a_ ) -> Any:
"""simple docstring"""
assert isinstance(a_ , a_ ) and (
number >= 0
), "'number' bust been an int and >= 0"
__A = 0
# prime factorization of 'number'
__A = prime_factorization(a_ )
__A = max(a_ )
# precondition
assert isinstance(a_ , a_ ), "'ans' must been from type int"
return ans
def UpperCAmelCase ( a_ ) -> Optional[Any]:
"""simple docstring"""
assert isinstance(a_ , a_ ) and (
number >= 0
), "'number' bust been an int and >= 0"
__A = 0
# prime factorization of 'number'
__A = prime_factorization(a_ )
__A = min(a_ )
# precondition
assert isinstance(a_ , a_ ), "'ans' must been from type int"
return ans
def UpperCAmelCase ( a_ ) -> int:
"""simple docstring"""
assert isinstance(a_ , a_ ), "'number' must been an int"
assert isinstance(number % 2 == 0 , a_ ), "compare bust been from type bool"
return number % 2 == 0
def UpperCAmelCase ( a_ ) -> List[Any]:
"""simple docstring"""
assert isinstance(a_ , a_ ), "'number' must been an int"
assert isinstance(number % 2 != 0 , a_ ), "compare bust been from type bool"
return number % 2 != 0
def UpperCAmelCase ( a_ ) -> Optional[Any]:
"""simple docstring"""
assert (
isinstance(a_ , a_ ) and (number > 2) and is_even(a_ )
), "'number' must been an int, even and > 2"
__A = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
__A = get_prime_numbers(a_ )
__A = len(a_ )
# run variable for while-loops.
__A = 0
__A = None
# exit variable. for break up the loops
__A = True
while i < len_pn and loop:
__A = i + 1
while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number:
__A = False
ans.append(prime_numbers[i] )
ans.append(prime_numbers[j] )
j += 1
i += 1
# precondition
assert (
isinstance(a_ , a_ )
and (len(a_ ) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0] )
and is_prime(ans[1] )
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
def UpperCAmelCase ( a_ , a_ ) -> Optional[Any]:
"""simple docstring"""
assert (
isinstance(a_ , a_ )
and isinstance(a_ , a_ )
and (numbera >= 0)
and (numbera >= 0)
), "'number1' and 'number2' must been positive integer."
__A = 0
while numbera != 0:
__A = numbera % numbera
__A = numbera
__A = rest
# precondition
assert isinstance(a_ , a_ ) and (
numbera >= 0
), "'number' must been from type int and positive"
return numbera
def UpperCAmelCase ( a_ , a_ ) -> List[str]:
"""simple docstring"""
assert (
isinstance(a_ , a_ )
and isinstance(a_ , a_ )
and (numbera >= 1)
and (numbera >= 1)
), "'number1' and 'number2' must been positive integer."
__A = 1 # actual answer that will be return.
# for kgV (x,1)
if numbera > 1 and numbera > 1:
# builds the prime factorization of 'number1' and 'number2'
__A = prime_factorization(a_ )
__A = prime_factorization(a_ )
elif numbera == 1 or numbera == 1:
__A = []
__A = []
__A = max(a_ , a_ )
__A = 0
__A = 0
__A = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in prime_fac_a:
if n not in done:
if n in prime_fac_a:
__A = prime_fac_a.count(a_ )
__A = prime_fac_a.count(a_ )
for _ in range(max(a_ , a_ ) ):
ans *= n
else:
__A = prime_fac_a.count(a_ )
for _ in range(a_ ):
ans *= n
done.append(a_ )
# iterates through primeFac2
for n in prime_fac_a:
if n not in done:
__A = prime_fac_a.count(a_ )
for _ in range(a_ ):
ans *= n
done.append(a_ )
# precondition
assert isinstance(a_ , a_ ) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
def UpperCAmelCase ( a_ ) -> str:
"""simple docstring"""
assert isinstance(a_ , a_ ) and (n >= 0), "'number' must been a positive int"
__A = 0
__A = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(a_ ):
ans += 1
# precondition
assert isinstance(a_ , a_ ) and is_prime(
a_ ), "'ans' must been a prime number and from type int"
return ans
def UpperCAmelCase ( a_ , a_ ) -> Tuple:
"""simple docstring"""
assert (
is_prime(a_ ) and is_prime(a_ ) and (p_number_a < p_number_a)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
__A = p_number_a + 1 # jump to the next number
__A = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(a_ ):
number += 1
while number < p_number_a:
ans.append(a_ )
number += 1
# fetch the next prime number.
while not is_prime(a_ ):
number += 1
# precondition
assert (
isinstance(a_ , a_ )
and ans[0] != p_number_a
and ans[len(a_ ) - 1] != p_number_a
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
def UpperCAmelCase ( a_ ) -> str:
"""simple docstring"""
assert isinstance(a_ , a_ ) and (n >= 1), "'n' must been int and >= 1"
__A = [] # will be returned.
for divisor in range(1 , n + 1 ):
if n % divisor == 0:
ans.append(a_ )
# precondition
assert ans[0] == 1 and ans[len(a_ ) - 1] == n, "Error in function getDivisiors(...)"
return ans
def UpperCAmelCase ( a_ ) -> Dict:
"""simple docstring"""
assert isinstance(a_ , a_ ) and (
number > 1
), "'number' must been an int and >= 1"
__A = get_divisors(a_ )
# precondition
assert (
isinstance(a_ , a_ )
and (divisors[0] == 1)
and (divisors[len(a_ ) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1] ) == number
def UpperCAmelCase ( a_ , a_ ) -> str:
"""simple docstring"""
assert (
isinstance(a_ , a_ )
and isinstance(a_ , a_ )
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
__A = gcd(abs(a_ ) , abs(a_ ) )
# precondition
assert (
isinstance(a_ , a_ )
and (numerator % gcd_of_fraction == 0)
and (denominator % gcd_of_fraction == 0)
), "Error in function gcd(...,...)"
return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
def UpperCAmelCase ( a_ ) -> Optional[int]:
"""simple docstring"""
assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been a int and >= 0"
__A = 1 # this will be return.
for factor in range(1 , n + 1 ):
ans *= factor
return ans
def UpperCAmelCase ( a_ ) -> List[Any]:
"""simple docstring"""
assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been an int and >= 0"
__A = 0
__A = 1
__A = 1 # this will be return
for _ in range(n - 1 ):
__A = ans
ans += fiba
__A = tmp
return ans
| 55 | 1 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.testing_utils import require_flax, require_tf, require_torch
from transformers.utils import (
expand_dims,
flatten_dict,
is_flax_available,
is_tf_available,
is_torch_available,
reshape,
squeeze,
transpose,
)
if is_flax_available():
import jax.numpy as jnp
if is_tf_available():
import tensorflow as tf
if is_torch_available():
import torch
class snake_case (unittest.TestCase ):
def _a ( self ) -> str:
lowercase__ = {
"task_specific_params": {
"summarization": {"length_penalty": 1.0, "max_length": 128, "min_length": 12, "num_beams": 4},
"summarization_cnn": {"length_penalty": 2.0, "max_length": 142, "min_length": 56, "num_beams": 4},
"summarization_xsum": {"length_penalty": 1.0, "max_length": 62, "min_length": 11, "num_beams": 6},
}
}
lowercase__ = {
"task_specific_params.summarization.length_penalty": 1.0,
"task_specific_params.summarization.max_length": 128,
"task_specific_params.summarization.min_length": 12,
"task_specific_params.summarization.num_beams": 4,
"task_specific_params.summarization_cnn.length_penalty": 2.0,
"task_specific_params.summarization_cnn.max_length": 142,
"task_specific_params.summarization_cnn.min_length": 56,
"task_specific_params.summarization_cnn.num_beams": 4,
"task_specific_params.summarization_xsum.length_penalty": 1.0,
"task_specific_params.summarization_xsum.max_length": 62,
"task_specific_params.summarization_xsum.min_length": 11,
"task_specific_params.summarization_xsum.num_beams": 6,
}
self.assertEqual(flatten_dict(UpperCAmelCase_ ) ,UpperCAmelCase_ )
def _a ( self ) -> int:
lowercase__ = np.random.randn(3 ,4 )
self.assertTrue(np.allclose(transpose(UpperCAmelCase_ ) ,x.transpose() ) )
lowercase__ = np.random.randn(3 ,4 ,5 )
self.assertTrue(np.allclose(transpose(UpperCAmelCase_ ,axes=(1, 2, 0) ) ,x.transpose((1, 2, 0) ) ) )
@require_torch
def _a ( self ) -> Optional[Any]:
lowercase__ = np.random.randn(3 ,4 )
lowercase__ = torch.tensor(UpperCAmelCase_ )
self.assertTrue(np.allclose(transpose(UpperCAmelCase_ ) ,transpose(UpperCAmelCase_ ).numpy() ) )
lowercase__ = np.random.randn(3 ,4 ,5 )
lowercase__ = torch.tensor(UpperCAmelCase_ )
self.assertTrue(np.allclose(transpose(UpperCAmelCase_ ,axes=(1, 2, 0) ) ,transpose(UpperCAmelCase_ ,axes=(1, 2, 0) ).numpy() ) )
@require_tf
def _a ( self ) -> List[Any]:
lowercase__ = np.random.randn(3 ,4 )
lowercase__ = tf.constant(UpperCAmelCase_ )
self.assertTrue(np.allclose(transpose(UpperCAmelCase_ ) ,transpose(UpperCAmelCase_ ).numpy() ) )
lowercase__ = np.random.randn(3 ,4 ,5 )
lowercase__ = tf.constant(UpperCAmelCase_ )
self.assertTrue(np.allclose(transpose(UpperCAmelCase_ ,axes=(1, 2, 0) ) ,transpose(UpperCAmelCase_ ,axes=(1, 2, 0) ).numpy() ) )
@require_flax
def _a ( self ) -> Any:
lowercase__ = np.random.randn(3 ,4 )
lowercase__ = jnp.array(UpperCAmelCase_ )
self.assertTrue(np.allclose(transpose(UpperCAmelCase_ ) ,np.asarray(transpose(UpperCAmelCase_ ) ) ) )
lowercase__ = np.random.randn(3 ,4 ,5 )
lowercase__ = jnp.array(UpperCAmelCase_ )
self.assertTrue(np.allclose(transpose(UpperCAmelCase_ ,axes=(1, 2, 0) ) ,np.asarray(transpose(UpperCAmelCase_ ,axes=(1, 2, 0) ) ) ) )
def _a ( self ) -> Optional[int]:
lowercase__ = np.random.randn(3 ,4 )
self.assertTrue(np.allclose(reshape(UpperCAmelCase_ ,(4, 3) ) ,np.reshape(UpperCAmelCase_ ,(4, 3) ) ) )
lowercase__ = np.random.randn(3 ,4 ,5 )
self.assertTrue(np.allclose(reshape(UpperCAmelCase_ ,(12, 5) ) ,np.reshape(UpperCAmelCase_ ,(12, 5) ) ) )
@require_torch
def _a ( self ) -> int:
lowercase__ = np.random.randn(3 ,4 )
lowercase__ = torch.tensor(UpperCAmelCase_ )
self.assertTrue(np.allclose(reshape(UpperCAmelCase_ ,(4, 3) ) ,reshape(UpperCAmelCase_ ,(4, 3) ).numpy() ) )
lowercase__ = np.random.randn(3 ,4 ,5 )
lowercase__ = torch.tensor(UpperCAmelCase_ )
self.assertTrue(np.allclose(reshape(UpperCAmelCase_ ,(12, 5) ) ,reshape(UpperCAmelCase_ ,(12, 5) ).numpy() ) )
@require_tf
def _a ( self ) -> List[Any]:
lowercase__ = np.random.randn(3 ,4 )
lowercase__ = tf.constant(UpperCAmelCase_ )
self.assertTrue(np.allclose(reshape(UpperCAmelCase_ ,(4, 3) ) ,reshape(UpperCAmelCase_ ,(4, 3) ).numpy() ) )
lowercase__ = np.random.randn(3 ,4 ,5 )
lowercase__ = tf.constant(UpperCAmelCase_ )
self.assertTrue(np.allclose(reshape(UpperCAmelCase_ ,(12, 5) ) ,reshape(UpperCAmelCase_ ,(12, 5) ).numpy() ) )
@require_flax
def _a ( self ) -> Union[str, Any]:
lowercase__ = np.random.randn(3 ,4 )
lowercase__ = jnp.array(UpperCAmelCase_ )
self.assertTrue(np.allclose(reshape(UpperCAmelCase_ ,(4, 3) ) ,np.asarray(reshape(UpperCAmelCase_ ,(4, 3) ) ) ) )
lowercase__ = np.random.randn(3 ,4 ,5 )
lowercase__ = jnp.array(UpperCAmelCase_ )
self.assertTrue(np.allclose(reshape(UpperCAmelCase_ ,(12, 5) ) ,np.asarray(reshape(UpperCAmelCase_ ,(12, 5) ) ) ) )
def _a ( self ) -> List[Any]:
lowercase__ = np.random.randn(1 ,3 ,4 )
self.assertTrue(np.allclose(squeeze(UpperCAmelCase_ ) ,np.squeeze(UpperCAmelCase_ ) ) )
lowercase__ = np.random.randn(1 ,4 ,1 ,5 )
self.assertTrue(np.allclose(squeeze(UpperCAmelCase_ ,axis=2 ) ,np.squeeze(UpperCAmelCase_ ,axis=2 ) ) )
@require_torch
def _a ( self ) -> int:
lowercase__ = np.random.randn(1 ,3 ,4 )
lowercase__ = torch.tensor(UpperCAmelCase_ )
self.assertTrue(np.allclose(squeeze(UpperCAmelCase_ ) ,squeeze(UpperCAmelCase_ ).numpy() ) )
lowercase__ = np.random.randn(1 ,4 ,1 ,5 )
lowercase__ = torch.tensor(UpperCAmelCase_ )
self.assertTrue(np.allclose(squeeze(UpperCAmelCase_ ,axis=2 ) ,squeeze(UpperCAmelCase_ ,axis=2 ).numpy() ) )
@require_tf
def _a ( self ) -> List[str]:
lowercase__ = np.random.randn(1 ,3 ,4 )
lowercase__ = tf.constant(UpperCAmelCase_ )
self.assertTrue(np.allclose(squeeze(UpperCAmelCase_ ) ,squeeze(UpperCAmelCase_ ).numpy() ) )
lowercase__ = np.random.randn(1 ,4 ,1 ,5 )
lowercase__ = tf.constant(UpperCAmelCase_ )
self.assertTrue(np.allclose(squeeze(UpperCAmelCase_ ,axis=2 ) ,squeeze(UpperCAmelCase_ ,axis=2 ).numpy() ) )
@require_flax
def _a ( self ) -> Any:
lowercase__ = np.random.randn(1 ,3 ,4 )
lowercase__ = jnp.array(UpperCAmelCase_ )
self.assertTrue(np.allclose(squeeze(UpperCAmelCase_ ) ,np.asarray(squeeze(UpperCAmelCase_ ) ) ) )
lowercase__ = np.random.randn(1 ,4 ,1 ,5 )
lowercase__ = jnp.array(UpperCAmelCase_ )
self.assertTrue(np.allclose(squeeze(UpperCAmelCase_ ,axis=2 ) ,np.asarray(squeeze(UpperCAmelCase_ ,axis=2 ) ) ) )
def _a ( self ) -> int:
lowercase__ = np.random.randn(3 ,4 )
self.assertTrue(np.allclose(expand_dims(UpperCAmelCase_ ,axis=1 ) ,np.expand_dims(UpperCAmelCase_ ,axis=1 ) ) )
@require_torch
def _a ( self ) -> Dict:
lowercase__ = np.random.randn(3 ,4 )
lowercase__ = torch.tensor(UpperCAmelCase_ )
self.assertTrue(np.allclose(expand_dims(UpperCAmelCase_ ,axis=1 ) ,expand_dims(UpperCAmelCase_ ,axis=1 ).numpy() ) )
@require_tf
def _a ( self ) -> Any:
lowercase__ = np.random.randn(3 ,4 )
lowercase__ = tf.constant(UpperCAmelCase_ )
self.assertTrue(np.allclose(expand_dims(UpperCAmelCase_ ,axis=1 ) ,expand_dims(UpperCAmelCase_ ,axis=1 ).numpy() ) )
@require_flax
def _a ( self ) -> Dict:
lowercase__ = np.random.randn(3 ,4 )
lowercase__ = jnp.array(UpperCAmelCase_ )
self.assertTrue(np.allclose(expand_dims(UpperCAmelCase_ ,axis=1 ) ,np.asarray(expand_dims(UpperCAmelCase_ ,axis=1 ) ) ) )
| 539 |
'''simple docstring'''
import copy
import os
from typing import TYPE_CHECKING, List, Union
if TYPE_CHECKING:
pass
from ...configuration_utils import PretrainedConfig
from ...utils import logging
SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE__ = {
"kakaobrain/align-base": "https://huggingface.co/kakaobrain/align-base/resolve/main/config.json",
}
class snake_case (UpperCamelCase ):
lowerCAmelCase__ :Optional[int] = "align_text_model"
def __init__( self ,UpperCAmelCase_=30_522 ,UpperCAmelCase_=768 ,UpperCAmelCase_=12 ,UpperCAmelCase_=12 ,UpperCAmelCase_=3_072 ,UpperCAmelCase_="gelu" ,UpperCAmelCase_=0.1 ,UpperCAmelCase_=0.1 ,UpperCAmelCase_=512 ,UpperCAmelCase_=2 ,UpperCAmelCase_=0.02 ,UpperCAmelCase_=1E-1_2 ,UpperCAmelCase_=0 ,UpperCAmelCase_="absolute" ,UpperCAmelCase_=True ,**UpperCAmelCase_ ,) -> List[str]:
super().__init__(**UpperCAmelCase_ )
lowercase__ = vocab_size
lowercase__ = hidden_size
lowercase__ = num_hidden_layers
lowercase__ = num_attention_heads
lowercase__ = hidden_act
lowercase__ = intermediate_size
lowercase__ = hidden_dropout_prob
lowercase__ = attention_probs_dropout_prob
lowercase__ = max_position_embeddings
lowercase__ = type_vocab_size
lowercase__ = initializer_range
lowercase__ = layer_norm_eps
lowercase__ = position_embedding_type
lowercase__ = use_cache
lowercase__ = pad_token_id
@classmethod
def _a ( cls ,UpperCAmelCase_ ,**UpperCAmelCase_ ) -> "PretrainedConfig":
cls._set_token_in_kwargs(UpperCAmelCase_ )
lowercase__ , lowercase__ = cls.get_config_dict(UpperCAmelCase_ ,**UpperCAmelCase_ )
# get the text config dict if we are loading from AlignConfig
if config_dict.get("model_type" ) == "align":
lowercase__ = config_dict["text_config"]
if "model_type" in config_dict and hasattr(cls ,"model_type" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type '''
F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' )
return cls.from_dict(UpperCAmelCase_ ,**UpperCAmelCase_ )
class snake_case (UpperCamelCase ):
lowerCAmelCase__ :Tuple = "align_vision_model"
def __init__( self ,UpperCAmelCase_ = 3 ,UpperCAmelCase_ = 600 ,UpperCAmelCase_ = 2.0 ,UpperCAmelCase_ = 3.1 ,UpperCAmelCase_ = 8 ,UpperCAmelCase_ = [3, 3, 5, 3, 5, 5, 3] ,UpperCAmelCase_ = [32, 16, 24, 40, 80, 112, 192] ,UpperCAmelCase_ = [16, 24, 40, 80, 112, 192, 320] ,UpperCAmelCase_ = [] ,UpperCAmelCase_ = [1, 2, 2, 2, 1, 2, 1] ,UpperCAmelCase_ = [1, 2, 2, 3, 3, 4, 1] ,UpperCAmelCase_ = [1, 6, 6, 6, 6, 6, 6] ,UpperCAmelCase_ = 0.25 ,UpperCAmelCase_ = "swish" ,UpperCAmelCase_ = 2_560 ,UpperCAmelCase_ = "mean" ,UpperCAmelCase_ = 0.02 ,UpperCAmelCase_ = 0.0_01 ,UpperCAmelCase_ = 0.99 ,UpperCAmelCase_ = 0.2 ,**UpperCAmelCase_ ,) -> Union[str, Any]:
super().__init__(**UpperCAmelCase_ )
lowercase__ = num_channels
lowercase__ = image_size
lowercase__ = width_coefficient
lowercase__ = depth_coefficient
lowercase__ = depth_divisor
lowercase__ = kernel_sizes
lowercase__ = in_channels
lowercase__ = out_channels
lowercase__ = depthwise_padding
lowercase__ = strides
lowercase__ = num_block_repeats
lowercase__ = expand_ratios
lowercase__ = squeeze_expansion_ratio
lowercase__ = hidden_act
lowercase__ = hidden_dim
lowercase__ = pooling_type
lowercase__ = initializer_range
lowercase__ = batch_norm_eps
lowercase__ = batch_norm_momentum
lowercase__ = drop_connect_rate
lowercase__ = sum(UpperCAmelCase_ ) * 4
@classmethod
def _a ( cls ,UpperCAmelCase_ ,**UpperCAmelCase_ ) -> "PretrainedConfig":
cls._set_token_in_kwargs(UpperCAmelCase_ )
lowercase__ , lowercase__ = cls.get_config_dict(UpperCAmelCase_ ,**UpperCAmelCase_ )
# get the vision config dict if we are loading from AlignConfig
if config_dict.get("model_type" ) == "align":
lowercase__ = config_dict["vision_config"]
if "model_type" in config_dict and hasattr(cls ,"model_type" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type '''
F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' )
return cls.from_dict(UpperCAmelCase_ ,**UpperCAmelCase_ )
class snake_case (UpperCamelCase ):
lowerCAmelCase__ :Union[str, Any] = "align"
lowerCAmelCase__ :Tuple = True
def __init__( self ,UpperCAmelCase_=None ,UpperCAmelCase_=None ,UpperCAmelCase_=640 ,UpperCAmelCase_=1.0 ,UpperCAmelCase_=0.02 ,**UpperCAmelCase_ ,) -> Union[str, Any]:
super().__init__(**UpperCAmelCase_ )
if text_config is None:
lowercase__ = {}
logger.info("text_config is None. Initializing the AlignTextConfig with default values." )
if vision_config is None:
lowercase__ = {}
logger.info("vision_config is None. Initializing the AlignVisionConfig with default values." )
lowercase__ = AlignTextConfig(**UpperCAmelCase_ )
lowercase__ = AlignVisionConfig(**UpperCAmelCase_ )
lowercase__ = projection_dim
lowercase__ = temperature_init_value
lowercase__ = initializer_range
@classmethod
def _a ( cls ,UpperCAmelCase_ ,UpperCAmelCase_ ,**UpperCAmelCase_ ) -> List[str]:
return cls(text_config=text_config.to_dict() ,vision_config=vision_config.to_dict() ,**UpperCAmelCase_ )
def _a ( self ) -> List[Any]:
lowercase__ = copy.deepcopy(self.__dict__ )
lowercase__ = self.text_config.to_dict()
lowercase__ = self.vision_config.to_dict()
lowercase__ = self.__class__.model_type
return output
| 539 | 1 |
import pickle
import numpy as np
from matplotlib import pyplot as plt
class __UpperCamelCase :
"""simple docstring"""
def __init__( self : Optional[int] , _A : Dict , _A : List[Any] , _A : Optional[Any] , _A : Optional[int] , _A : Union[str, Any] , _A : Optional[int]=0.2 , _A : Tuple=0.2 ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Optional[int] = bp_numa
__SCREAMING_SNAKE_CASE : Tuple = bp_numa
__SCREAMING_SNAKE_CASE : int = bp_numa
__SCREAMING_SNAKE_CASE : Tuple = conva_get[:2]
__SCREAMING_SNAKE_CASE : Optional[int] = conva_get[2]
__SCREAMING_SNAKE_CASE : List[Any] = size_pa
__SCREAMING_SNAKE_CASE : Any = rate_w
__SCREAMING_SNAKE_CASE : Union[str, Any] = rate_t
__SCREAMING_SNAKE_CASE : Dict = [
np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 )
for i in range(self.conva[1] )
]
__SCREAMING_SNAKE_CASE : Optional[int] = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 )
__SCREAMING_SNAKE_CASE : Dict = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 )
__SCREAMING_SNAKE_CASE : Dict = -2 * np.random.rand(self.conva[1] ) + 1
__SCREAMING_SNAKE_CASE : int = -2 * np.random.rand(self.num_bpa ) + 1
__SCREAMING_SNAKE_CASE : Optional[int] = -2 * np.random.rand(self.num_bpa ) + 1
def UpperCAmelCase__ ( self : Optional[int] , _A : int ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Optional[Any] = {
'''num_bp1''': self.num_bpa,
'''num_bp2''': self.num_bpa,
'''num_bp3''': self.num_bpa,
'''conv1''': self.conva,
'''step_conv1''': self.step_conva,
'''size_pooling1''': self.size_poolinga,
'''rate_weight''': self.rate_weight,
'''rate_thre''': self.rate_thre,
'''w_conv1''': self.w_conva,
'''wkj''': self.wkj,
'''vji''': self.vji,
'''thre_conv1''': self.thre_conva,
'''thre_bp2''': self.thre_bpa,
'''thre_bp3''': self.thre_bpa,
}
with open(_A , '''wb''' ) as f:
pickle.dump(_A , _A )
print(F'''Model saved: {save_path}''' )
@classmethod
def UpperCAmelCase__ ( cls : List[str] , _A : int ):
"""simple docstring"""
with open(_A , '''rb''' ) as f:
__SCREAMING_SNAKE_CASE : Tuple = pickle.load(_A ) # noqa: S301
__SCREAMING_SNAKE_CASE : str = model_dic.get('''conv1''' )
conv_get.append(model_dic.get('''step_conv1''' ) )
__SCREAMING_SNAKE_CASE : Dict = model_dic.get('''size_pooling1''' )
__SCREAMING_SNAKE_CASE : List[Any] = model_dic.get('''num_bp1''' )
__SCREAMING_SNAKE_CASE : Union[str, Any] = model_dic.get('''num_bp2''' )
__SCREAMING_SNAKE_CASE : Any = model_dic.get('''num_bp3''' )
__SCREAMING_SNAKE_CASE : Any = model_dic.get('''rate_weight''' )
__SCREAMING_SNAKE_CASE : int = model_dic.get('''rate_thre''' )
# create model instance
__SCREAMING_SNAKE_CASE : Tuple = CNN(_A , _A , _A , _A , _A , _A , _A )
# modify model parameter
__SCREAMING_SNAKE_CASE : Optional[int] = model_dic.get('''w_conv1''' )
__SCREAMING_SNAKE_CASE : Dict = model_dic.get('''wkj''' )
__SCREAMING_SNAKE_CASE : Any = model_dic.get('''vji''' )
__SCREAMING_SNAKE_CASE : str = model_dic.get('''thre_conv1''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = model_dic.get('''thre_bp2''' )
__SCREAMING_SNAKE_CASE : Union[str, Any] = model_dic.get('''thre_bp3''' )
return conv_ins
def UpperCAmelCase__ ( self : List[Any] , _A : List[Any] ):
"""simple docstring"""
return 1 / (1 + np.exp(-1 * x ))
def UpperCAmelCase__ ( self : str , _A : List[str] ):
"""simple docstring"""
return round(_A , 3 )
def UpperCAmelCase__ ( self : int , _A : int , _A : str , _A : List[Any] , _A : Tuple , _A : List[Any] ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Union[str, Any] = convs[0]
__SCREAMING_SNAKE_CASE : Any = convs[1]
__SCREAMING_SNAKE_CASE : int = np.shape(_A )[0]
# get the data slice of original image data, data_focus
__SCREAMING_SNAKE_CASE : Union[str, Any] = []
for i_focus in range(0 , size_data - size_conv + 1 , _A ):
for j_focus in range(0 , size_data - size_conv + 1 , _A ):
__SCREAMING_SNAKE_CASE : Optional[int] = data[
i_focus : i_focus + size_conv, j_focus : j_focus + size_conv
]
data_focus.append(_A )
# calculate the feature map of every single kernel, and saved as list of matrix
__SCREAMING_SNAKE_CASE : Dict = []
__SCREAMING_SNAKE_CASE : List[str] = int((size_data - size_conv) / conv_step + 1 )
for i_map in range(_A ):
__SCREAMING_SNAKE_CASE : List[Any] = []
for i_focus in range(len(_A ) ):
__SCREAMING_SNAKE_CASE : int = (
np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) )
- thre_convs[i_map]
)
featuremap.append(self.sig(_A ) )
__SCREAMING_SNAKE_CASE : str = np.asmatrix(_A ).reshape(
_A , _A )
data_featuremap.append(_A )
# expanding the data slice to One dimenssion
__SCREAMING_SNAKE_CASE : int = []
for each_focus in data_focus:
focusa_list.extend(self.Expand_Mat(_A ) )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(_A )
return focus_list, data_featuremap
def UpperCAmelCase__ ( self : List[str] , _A : str , _A : Union[str, Any] , _A : Optional[int]="average_pool" ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Any = len(featuremaps[0] )
__SCREAMING_SNAKE_CASE : List[Any] = int(size_map / size_pooling )
__SCREAMING_SNAKE_CASE : Optional[Any] = []
for i_map in range(len(_A ) ):
__SCREAMING_SNAKE_CASE : Tuple = featuremaps[i_map]
__SCREAMING_SNAKE_CASE : Dict = []
for i_focus in range(0 , _A , _A ):
for j_focus in range(0 , _A , _A ):
__SCREAMING_SNAKE_CASE : Tuple = feature_map[
i_focus : i_focus + size_pooling,
j_focus : j_focus + size_pooling,
]
if pooling_type == "average_pool":
# average pooling
map_pooled.append(np.average(_A ) )
elif pooling_type == "max_pooling":
# max pooling
map_pooled.append(np.max(_A ) )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asmatrix(_A ).reshape(_A , _A )
featuremap_pooled.append(_A )
return featuremap_pooled
def UpperCAmelCase__ ( self : Dict , _A : str ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Tuple = []
for i in range(len(_A ) ):
__SCREAMING_SNAKE_CASE : Optional[int] = np.shape(data[i] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = data[i].reshape(1 , shapes[0] * shapes[1] )
__SCREAMING_SNAKE_CASE : List[Any] = data_listed.getA().tolist()[0]
data_expanded.extend(_A )
__SCREAMING_SNAKE_CASE : Tuple = np.asarray(_A )
return data_expanded
def UpperCAmelCase__ ( self : List[Any] , _A : Dict ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Any = np.asarray(_A )
__SCREAMING_SNAKE_CASE : List[str] = np.shape(_A )
__SCREAMING_SNAKE_CASE : Optional[int] = data_mat.reshape(1 , shapes[0] * shapes[1] )
return data_expanded
def UpperCAmelCase__ ( self : Dict , _A : Any , _A : Optional[Any] , _A : List[Any] , _A : Tuple , _A : Optional[Any] ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : int = []
__SCREAMING_SNAKE_CASE : List[str] = 0
for i_map in range(_A ):
__SCREAMING_SNAKE_CASE : Dict = np.ones((size_map, size_map) )
for i in range(0 , _A , _A ):
for j in range(0 , _A , _A ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = pd_pool[
i_pool
]
__SCREAMING_SNAKE_CASE : List[str] = i_pool + 1
__SCREAMING_SNAKE_CASE : Optional[Any] = np.multiply(
_A , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) )
pd_all.append(_A )
return pd_all
def UpperCAmelCase__ ( self : List[str] , _A : List[Any] , _A : str , _A : Any , _A : Union[str, Any] , _A : List[Any] , _A : Any=bool ):
"""simple docstring"""
print('''----------------------Start Training-------------------------''' )
print((''' - - Shape: Train_Data ''', np.shape(_A )) )
print((''' - - Shape: Teach_Data ''', np.shape(_A )) )
__SCREAMING_SNAKE_CASE : int = 0
__SCREAMING_SNAKE_CASE : int = []
__SCREAMING_SNAKE_CASE : str = 1_0000
while rp < n_repeat and mse >= error_accuracy:
__SCREAMING_SNAKE_CASE : Union[str, Any] = 0
print(F'''-------------Learning Time {rp}--------------''' )
for p in range(len(_A ) ):
# print('------------Learning Image: %d--------------'%p)
__SCREAMING_SNAKE_CASE : Tuple = np.asmatrix(datas_train[p] )
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(datas_teach[p] )
__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : str = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
__SCREAMING_SNAKE_CASE : Optional[Any] = self.pooling(_A , self.size_poolinga )
__SCREAMING_SNAKE_CASE : List[str] = np.shape(_A )
__SCREAMING_SNAKE_CASE : Optional[Any] = self._expand(_A )
__SCREAMING_SNAKE_CASE : Union[str, Any] = data_bp_input
__SCREAMING_SNAKE_CASE : Tuple = np.dot(_A , self.vji.T ) - self.thre_bpa
__SCREAMING_SNAKE_CASE : Optional[Any] = self.sig(_A )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.dot(_A , self.wkj.T ) - self.thre_bpa
__SCREAMING_SNAKE_CASE : Dict = self.sig(_A )
# --------------Model Leaning ------------------------
# calculate error and gradient---------------
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.multiply(
(data_teach - bp_outa) , np.multiply(_A , (1 - bp_outa) ) )
__SCREAMING_SNAKE_CASE : str = np.multiply(
np.dot(_A , self.wkj ) , np.multiply(_A , (1 - bp_outa) ) )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.dot(_A , self.vji )
__SCREAMING_SNAKE_CASE : List[Any] = pd_i_all / (self.size_poolinga * self.size_poolinga)
__SCREAMING_SNAKE_CASE : Dict = pd_conva_pooled.T.getA().tolist()
__SCREAMING_SNAKE_CASE : Optional[Any] = self._calculate_gradient_from_pool(
_A , _A , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , )
# weight and threshold learning process---------
# convolution layer
for k_conv in range(self.conva[1] ):
__SCREAMING_SNAKE_CASE : str = self._expand_mat(pd_conva_all[k_conv] )
__SCREAMING_SNAKE_CASE : Any = self.rate_weight * np.dot(_A , _A )
__SCREAMING_SNAKE_CASE : Any = self.w_conva[k_conv] + delta_w.reshape(
(self.conva[0], self.conva[0]) )
__SCREAMING_SNAKE_CASE : str = (
self.thre_conva[k_conv]
- np.sum(pd_conva_all[k_conv] ) * self.rate_thre
)
# all connected layer
__SCREAMING_SNAKE_CASE : List[Any] = self.wkj + pd_k_all.T * bp_outa * self.rate_weight
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.vji + pd_j_all.T * bp_outa * self.rate_weight
__SCREAMING_SNAKE_CASE : Optional[Any] = self.thre_bpa - pd_k_all * self.rate_thre
__SCREAMING_SNAKE_CASE : int = self.thre_bpa - pd_j_all * self.rate_thre
# calculate the sum error of all single image
__SCREAMING_SNAKE_CASE : Dict = np.sum(abs(data_teach - bp_outa ) )
error_count += errors
# print(' ----Teach ',data_teach)
# print(' ----BP_output ',bp_out3)
__SCREAMING_SNAKE_CASE : List[str] = rp + 1
__SCREAMING_SNAKE_CASE : List[Any] = error_count / patterns
all_mse.append(_A )
def draw_error():
__SCREAMING_SNAKE_CASE : Optional[Any] = [error_accuracy for i in range(int(n_repeat * 1.2 ) )]
plt.plot(_A , '''+-''' )
plt.plot(_A , '''r--''' )
plt.xlabel('''Learning Times''' )
plt.ylabel('''All_mse''' )
plt.grid(_A , alpha=0.5 )
plt.show()
print('''------------------Training Complished---------------------''' )
print((''' - - Training epoch: ''', rp, F''' - - Mse: {mse:.6f}''') )
if draw_e:
draw_error()
return mse
def UpperCAmelCase__ ( self : Tuple , _A : Dict ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Optional[Any] = []
print('''-------------------Start Testing-------------------------''' )
print((''' - - Shape: Test_Data ''', np.shape(_A )) )
for p in range(len(_A ) ):
__SCREAMING_SNAKE_CASE : int = np.asmatrix(datas_test[p] )
__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[Any] = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
__SCREAMING_SNAKE_CASE : Optional[Any] = self.pooling(_A , self.size_poolinga )
__SCREAMING_SNAKE_CASE : Dict = self._expand(_A )
__SCREAMING_SNAKE_CASE : str = data_bp_input
__SCREAMING_SNAKE_CASE : Any = bp_outa * self.vji.T - self.thre_bpa
__SCREAMING_SNAKE_CASE : Optional[int] = self.sig(_A )
__SCREAMING_SNAKE_CASE : Union[str, Any] = bp_outa * self.wkj.T - self.thre_bpa
__SCREAMING_SNAKE_CASE : Optional[Any] = self.sig(_A )
produce_out.extend(bp_outa.getA().tolist() )
__SCREAMING_SNAKE_CASE : int = [list(map(self.do_round , _A ) ) for each in produce_out]
return np.asarray(_A )
def UpperCAmelCase__ ( self : Union[str, Any] , _A : Optional[int] ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Tuple = np.asmatrix(_A )
__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
__SCREAMING_SNAKE_CASE : Optional[Any] = self.pooling(_A , self.size_poolinga )
return data_conveda, data_pooleda
if __name__ == "__main__":
pass
| 74 |
"""simple docstring"""
import requests
def a__ ( lowerCAmelCase , lowerCAmelCase ) -> None:
UpperCAmelCase__ : List[str] = {"""Content-Type""": """application/json"""}
UpperCAmelCase__ : List[str] = requests.post(lowerCAmelCase , json={"""text""": message_body} , headers=lowerCAmelCase )
if response.status_code != 2_00:
UpperCAmelCase__ : str = (
"""Request to slack returned an error """
F"""{response.status_code}, the response is:\n{response.text}"""
)
raise ValueError(lowerCAmelCase )
if __name__ == "__main__":
# Set the slack url to the one provided by Slack when you create the webhook at
# https://my.slack.com/services/new/incoming-webhook/
send_slack_message("""<YOUR MESSAGE BODY>""", """<SLACK CHANNEL URL>""")
| 182 | 0 |
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import Features, Value
from .base import TaskTemplate
@dataclass(frozen=lowerCAmelCase__ )
class __a ( lowerCAmelCase__ ):
# `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization
SCREAMING_SNAKE_CASE__ : str = field(default="summarization" , metadata={"include_in_asdict_even_if_is_default": True} )
SCREAMING_SNAKE_CASE__ : ClassVar[Features] = Features({"text": Value("string" )} )
SCREAMING_SNAKE_CASE__ : ClassVar[Features] = Features({"summary": Value("string" )} )
SCREAMING_SNAKE_CASE__ : str = "text"
SCREAMING_SNAKE_CASE__ : str = "summary"
@property
def snake_case_ ( self ):
return {self.text_column: "text", self.summary_column: "summary"}
| 714 |
"""simple docstring"""
import logging
from pathlib import Path
import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only
from utils_rag import save_json
def SCREAMING_SNAKE_CASE_ ( snake_case : Any )-> str:
_lowerCamelCase = filter(lambda snake_case : p.requires_grad , model.parameters() )
_lowerCamelCase = sum([np.prod(p.size() ) for p in model_parameters] )
return params
A_ : List[str] =logging.getLogger(__name__)
def SCREAMING_SNAKE_CASE_ ( snake_case : Optional[int] , snake_case : Union[str, Any] )-> Tuple:
if metric == "rouge2":
_lowerCamelCase = '{val_avg_rouge2:.4f}-{step_count}'
elif metric == "bleu":
_lowerCamelCase = '{val_avg_bleu:.4f}-{step_count}'
elif metric == "em":
_lowerCamelCase = '{val_avg_em:.4f}-{step_count}'
else:
raise NotImplementedError(
f'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this'
' function.' )
_lowerCamelCase = ModelCheckpoint(
dirpath=snake_case , filename=snake_case , monitor=f'val_{metric}' , mode='max' , save_top_k=3 , every_n_epochs=1 , )
return checkpoint_callback
def SCREAMING_SNAKE_CASE_ ( snake_case : Union[str, Any] , snake_case : Tuple )-> Optional[Any]:
return EarlyStopping(
monitor=f'val_{metric}' , mode='min' if 'loss' in metric else 'max' , patience=snake_case , verbose=snake_case , )
class __a ( pl.Callback ):
def snake_case_ ( self , a__ , a__ ):
_lowerCamelCase = {F'lr_group_{i}': param['lr'] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )}
pl_module.logger.log_metrics(a__ )
@rank_zero_only
def snake_case_ ( self , a__ , a__ , a__ , a__=True ):
logger.info(F'***** {type_path} results at step {trainer.global_step:05d} *****' )
_lowerCamelCase = trainer.callback_metrics
trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['log', 'progress_bar', 'preds']} )
# Log results
_lowerCamelCase = Path(pl_module.hparams.output_dir )
if type_path == "test":
_lowerCamelCase = od / 'test_results.txt'
_lowerCamelCase = od / 'test_generations.txt'
else:
# this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json
# If people want this it will be easy enough to add back.
_lowerCamelCase = od / F'{type_path}_results/{trainer.global_step:05d}.txt'
_lowerCamelCase = od / F'{type_path}_generations/{trainer.global_step:05d}.txt'
results_file.parent.mkdir(exist_ok=a__ )
generations_file.parent.mkdir(exist_ok=a__ )
with open(a__ , 'a+' ) as writer:
for key in sorted(a__ ):
if key in ["log", "progress_bar", "preds"]:
continue
_lowerCamelCase = metrics[key]
if isinstance(a__ , torch.Tensor ):
_lowerCamelCase = val.item()
_lowerCamelCase = F'{key}: {val:.6f}\n'
writer.write(a__ )
if not save_generations:
return
if "preds" in metrics:
_lowerCamelCase = '\n'.join(metrics['preds'] )
generations_file.open('w+' ).write(a__ )
@rank_zero_only
def snake_case_ ( self , a__ , a__ ):
try:
_lowerCamelCase = pl_module.model.model.num_parameters()
except AttributeError:
_lowerCamelCase = pl_module.model.num_parameters()
_lowerCamelCase = count_trainable_parameters(a__ )
# mp stands for million parameters
trainer.logger.log_metrics({'n_params': npars, 'mp': npars / 1e6, 'grad_mp': n_trainable_pars / 1e6} )
@rank_zero_only
def snake_case_ ( self , a__ , a__ ):
save_json(pl_module.metrics , pl_module.metrics_save_path )
return self._write_logs(a__ , a__ , 'test' )
@rank_zero_only
def snake_case_ ( self , a__ , a__ ):
save_json(pl_module.metrics , pl_module.metrics_save_path )
# Uncommenting this will save val generations
# return self._write_logs(trainer, pl_module, "valid")
| 222 | 0 |
'''simple docstring'''
import tempfile
import unittest
import numpy as np
import transformers
from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow
from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
if is_flax_available():
import jax
import jax.numpy as jnp
from transformers.modeling_flax_pytorch_utils import (
convert_pytorch_state_dict_to_flax,
load_flax_weights_in_pytorch_model,
)
from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel
if is_torch_available():
import torch
class _snake_case :
"""simple docstring"""
def __init__( self , UpperCAmelCase__ , UpperCAmelCase__=14 , UpperCAmelCase__=7 , UpperCAmelCase__=True , UpperCAmelCase__=True , UpperCAmelCase__=False , UpperCAmelCase__=True , UpperCAmelCase__=99 , UpperCAmelCase__=32 , UpperCAmelCase__=4 , UpperCAmelCase__=4 , UpperCAmelCase__=4 , UpperCAmelCase__=37 , UpperCAmelCase__="gelu" , UpperCAmelCase__=0.1 , UpperCAmelCase__=0.1 , UpperCAmelCase__=512 , UpperCAmelCase__=0.0_2 , ) -> List[str]:
a_ = parent
a_ = batch_size
a_ = seq_length
a_ = is_training
a_ = use_input_mask
a_ = use_token_type_ids
a_ = use_labels
a_ = vocab_size
a_ = hidden_size
a_ = rotary_dim
a_ = num_hidden_layers
a_ = num_attention_heads
a_ = intermediate_size
a_ = hidden_act
a_ = hidden_dropout_prob
a_ = attention_probs_dropout_prob
a_ = max_position_embeddings
a_ = initializer_range
a_ = None
a_ = vocab_size - 1
a_ = vocab_size - 1
a_ = vocab_size - 1
def __SCREAMING_SNAKE_CASE ( self ) -> Any:
a_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
a_ = None
if self.use_input_mask:
a_ = random_attention_mask([self.batch_size, self.seq_length] )
a_ = GPTJConfig(
vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=_A , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , )
return (config, input_ids, input_mask)
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
a_ = self.prepare_config_and_inputs()
a_ , a_ , a_ = config_and_inputs
a_ = {'input_ids': input_ids, 'attention_mask': attention_mask}
return config, inputs_dict
def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> str:
a_ = 20
a_ = model_class_name(_A )
a_ = model.init_cache(input_ids.shape[0] , _A )
a_ = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='i4' )
a_ = jnp.broadcast_to(
jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) )
a_ = model(
input_ids[:, :-1] , attention_mask=_A , past_key_values=_A , position_ids=_A , )
a_ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' )
a_ = model(
input_ids[:, -1:] , attention_mask=_A , past_key_values=outputs_cache.past_key_values , position_ids=_A , )
a_ = model(_A )
a_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) )
self.parent.assertTrue(diff < 1e-3 , msg=F'''Max diff is {diff}''' )
def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> int:
a_ = 20
a_ = model_class_name(_A )
a_ = jnp.concatenate(
[attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , )
a_ = model.init_cache(input_ids.shape[0] , _A )
a_ = jnp.broadcast_to(
jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) )
a_ = model(
input_ids[:, :-1] , attention_mask=_A , past_key_values=_A , position_ids=_A , )
a_ = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' )
a_ = model(
input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=_A , position_ids=_A , )
a_ = model(_A , attention_mask=_A )
a_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) )
self.parent.assertTrue(diff < 1e-3 , msg=F'''Max diff is {diff}''' )
@require_flax
class _snake_case ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase ):
"""simple docstring"""
_UpperCamelCase = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else ()
_UpperCamelCase = (FlaxGPTJForCausalLM,) if is_flax_available() else ()
def __SCREAMING_SNAKE_CASE ( self ) -> str:
a_ = FlaxGPTJModelTester(self )
def __SCREAMING_SNAKE_CASE ( self ) -> Tuple:
for model_class_name in self.all_model_classes:
a_ , a_ , a_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_use_cache_forward(_A , _A , _A , _A )
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
for model_class_name in self.all_model_classes:
a_ , a_ , a_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_use_cache_forward_with_attn_mask(
_A , _A , _A , _A )
@tooslow
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
a_ = GPTaTokenizer.from_pretrained('gpt2' , pad_token='<|endoftext|>' , padding_side='left' )
a_ = tokenizer(['Hello this is a long string', 'Hey'] , return_tensors='np' , padding=_A , truncation=_A )
a_ = FlaxGPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B' )
a_ = False
a_ = model.config.eos_token_id
a_ = jax.jit(model.generate )
a_ = jit_generate(
inputs['input_ids'] , attention_mask=inputs['attention_mask'] , pad_token_id=tokenizer.pad_token_id ).sequences
a_ = tokenizer.batch_decode(_A , skip_special_tokens=_A )
a_ = [
'Hello this is a long string of text.\n\nI\'m trying to get the text of the',
'Hey, I\'m a little late to the party. I\'m going to',
]
self.assertListEqual(_A , _A )
@is_pt_flax_cross_test
def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
a_ , a_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__ ):
# prepare inputs
a_ = self._prepare_for_class(_A , _A )
a_ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()}
# load corresponding PyTorch class
a_ = model_class.__name__[4:] # Skip the "Flax" at the beginning
a_ = getattr(_A , _A )
a_ , a_ = pt_inputs['input_ids'].shape
a_ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) )
for batch_idx, start_index in enumerate(_A ):
a_ = 0
a_ = 1
a_ = 0
a_ = 1
a_ = pt_model_class(_A ).eval()
a_ = model_class(_A , dtype=jnp.floataa )
a_ = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , _A )
a_ = fx_state
with torch.no_grad():
a_ = pt_model(**_A ).to_tuple()
a_ = fx_model(**_A ).to_tuple()
self.assertEqual(len(_A ) , len(_A ) , 'Output lengths differ between Flax and PyTorch' )
for fx_output, pt_output in zip(_A , _A ):
self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 )
with tempfile.TemporaryDirectory() as tmpdirname:
pt_model.save_pretrained(_A )
a_ = model_class.from_pretrained(_A , from_pt=_A )
a_ = fx_model_loaded(**_A ).to_tuple()
self.assertEqual(
len(_A ) , len(_A ) , 'Output lengths differ between Flax and PyTorch' )
for fx_output_loaded, pt_output in zip(_A , _A ):
self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4e-2 )
@is_pt_flax_cross_test
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
a_ , a_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__ ):
# prepare inputs
a_ = self._prepare_for_class(_A , _A )
a_ = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()}
# load corresponding PyTorch class
a_ = model_class.__name__[4:] # Skip the "Flax" at the beginning
a_ = getattr(_A , _A )
a_ = pt_model_class(_A ).eval()
a_ = model_class(_A , dtype=jnp.floataa )
a_ = load_flax_weights_in_pytorch_model(_A , fx_model.params )
a_ , a_ = pt_inputs['input_ids'].shape
a_ = np.random.randint(0 , seq_length - 1 , size=(batch_size,) )
for batch_idx, start_index in enumerate(_A ):
a_ = 0
a_ = 1
a_ = 0
a_ = 1
# make sure weights are tied in PyTorch
pt_model.tie_weights()
with torch.no_grad():
a_ = pt_model(**_A ).to_tuple()
a_ = fx_model(**_A ).to_tuple()
self.assertEqual(len(_A ) , len(_A ) , 'Output lengths differ between Flax and PyTorch' )
for fx_output, pt_output in zip(_A , _A ):
self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 )
with tempfile.TemporaryDirectory() as tmpdirname:
fx_model.save_pretrained(_A )
a_ = pt_model_class.from_pretrained(_A , from_flax=_A )
with torch.no_grad():
a_ = pt_model_loaded(**_A ).to_tuple()
self.assertEqual(
len(_A ) , len(_A ) , 'Output lengths differ between Flax and PyTorch' )
for fx_output, pt_output in zip(_A , _A ):
self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 )
@tooslow
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]:
for model_class_name in self.all_model_classes:
a_ = model_class_name.from_pretrained('EleutherAI/gpt-j-6B' )
a_ = model(np.ones((1, 1) ) )
self.assertIsNotNone(_A )
| 697 |
"""simple docstring"""
from __future__ import annotations
import numpy as np
def _lowerCAmelCase(a : list[float] ) -> Any:
return np.maximum(0 , a )
if __name__ == "__main__":
print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
| 255 | 0 |
from collections import OrderedDict
from typing import Any, List, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging
lowercase = logging.get_logger(__name__)
lowercase = {
"""EleutherAI/gpt-j-6B""": """https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json""",
# See all GPT-J models at https://huggingface.co/models?filter=gpt_j
}
class __lowercase ( A ):
'''simple docstring'''
_A : Union[str, Any] = '''gptj'''
_A : Any = {
'''max_position_embeddings''': '''n_positions''',
'''hidden_size''': '''n_embd''',
'''num_attention_heads''': '''n_head''',
'''num_hidden_layers''': '''n_layer''',
}
def __init__( self : Dict , _a : Tuple=50_400 , _a : Optional[int]=2_048 , _a : Dict=4_096 , _a : Tuple=28 , _a : str=16 , _a : str=64 , _a : Optional[Any]=None , _a : List[str]="gelu_new" , _a : Any=0.0 , _a : Optional[Any]=0.0 , _a : Optional[int]=0.0 , _a : Any=1E-5 , _a : Any=0.02 , _a : Union[str, Any]=True , _a : Dict=50_256 , _a : Dict=50_256 , _a : Tuple=False , **_a : Optional[int] , ):
UpperCamelCase__ = vocab_size
UpperCamelCase__ = n_positions
UpperCamelCase__ = n_embd
UpperCamelCase__ = n_layer
UpperCamelCase__ = n_head
UpperCamelCase__ = n_inner
UpperCamelCase__ = rotary_dim
UpperCamelCase__ = activation_function
UpperCamelCase__ = resid_pdrop
UpperCamelCase__ = embd_pdrop
UpperCamelCase__ = attn_pdrop
UpperCamelCase__ = layer_norm_epsilon
UpperCamelCase__ = initializer_range
UpperCamelCase__ = use_cache
UpperCamelCase__ = bos_token_id
UpperCamelCase__ = eos_token_id
super().__init__(
bos_token_id=_a , eos_token_id=_a , tie_word_embeddings=_a , **_a )
class __lowercase ( A ):
'''simple docstring'''
def __init__( self : Union[str, Any] , _a : PretrainedConfig , _a : str = "default" , _a : List[PatchingSpec] = None , _a : bool = False , ):
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__ = 0
@property
def A_ ( self : Any ):
UpperCamelCase__ = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} )
if self.use_past:
self.fill_with_past_key_values_(_a , direction='''inputs''' )
UpperCamelCase__ = {0: '''batch''', 1: '''past_sequence + sequence'''}
else:
UpperCamelCase__ = {0: '''batch''', 1: '''sequence'''}
return common_inputs
@property
def A_ ( self : List[Any] ):
return self._config.n_layer
@property
def A_ ( self : List[Any] ):
return self._config.n_head
def A_ ( self : Dict , _a : PreTrainedTokenizer , _a : int = -1 , _a : int = -1 , _a : bool = False , _a : Optional[TensorType] = None , ):
UpperCamelCase__ = 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__ = 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__ = common_inputs['''input_ids'''].shape
# Not using the same length for past_key_values
UpperCamelCase__ = seqlen + 2
UpperCamelCase__ = (
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
UpperCamelCase__ = [
(torch.zeros(_a ), torch.zeros(_a )) for _ in range(self.num_layers )
]
UpperCamelCase__ = common_inputs['''attention_mask''']
if self.use_past:
UpperCamelCase__ = ordered_inputs['''attention_mask'''].dtype
UpperCamelCase__ = torch.cat(
[ordered_inputs['''attention_mask'''], torch.ones(_a , _a , dtype=_a )] , dim=1 )
return ordered_inputs
@property
def A_ ( self : Dict ):
return 13
| 591 | from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available
lowercase = {
"""configuration_audio_spectrogram_transformer""": [
"""AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""ASTConfig""",
]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase = [
"""AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""ASTForAudioClassification""",
"""ASTModel""",
"""ASTPreTrainedModel""",
]
try:
if not is_speech_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase = ["""ASTFeatureExtractor"""]
if TYPE_CHECKING:
from .configuration_audio_spectrogram_transformer import (
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
ASTConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_audio_spectrogram_transformer import (
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
ASTForAudioClassification,
ASTModel,
ASTPreTrainedModel,
)
try:
if not is_speech_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor
else:
import sys
lowercase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 591 | 1 |
import os
import string
import sys
UpperCamelCase = 1 << 8
UpperCamelCase = {
'tab': ord('\t'),
'newline': ord('\r'),
'esc': 27,
'up': 65 + ARROW_KEY_FLAG,
'down': 66 + ARROW_KEY_FLAG,
'right': 67 + ARROW_KEY_FLAG,
'left': 68 + ARROW_KEY_FLAG,
'mod_int': 91,
'undefined': sys.maxsize,
'interrupt': 3,
'insert': 50,
'delete': 51,
'pg_up': 53,
'pg_down': 54,
}
UpperCamelCase = KEYMAP['up']
UpperCamelCase = KEYMAP['left']
if sys.platform == "win32":
UpperCamelCase = []
UpperCamelCase = {
b'\xe0H': KEYMAP['up'] - ARROW_KEY_FLAG,
b'\x00H': KEYMAP['up'] - ARROW_KEY_FLAG,
b'\xe0P': KEYMAP['down'] - ARROW_KEY_FLAG,
b'\x00P': KEYMAP['down'] - ARROW_KEY_FLAG,
b'\xe0M': KEYMAP['right'] - ARROW_KEY_FLAG,
b'\x00M': KEYMAP['right'] - ARROW_KEY_FLAG,
b'\xe0K': KEYMAP['left'] - ARROW_KEY_FLAG,
b'\x00K': KEYMAP['left'] - ARROW_KEY_FLAG,
}
for i in range(10):
UpperCamelCase = ord(str(i))
def lowerCamelCase_ ( ) -> Tuple:
if os.name == "nt":
import msvcrt
__A : Union[str, Any] = "mbcs"
# Flush the keyboard buffer
while msvcrt.kbhit():
msvcrt.getch()
if len(_lowercase ) == 0:
# Read the keystroke
__A : List[str] = msvcrt.getch()
# If it is a prefix char, get second part
if ch in (b"\x00", b"\xe0"):
__A : Dict = ch + msvcrt.getch()
# Translate actual Win chars to bullet char types
try:
__A : Tuple = chr(WIN_KEYMAP[cha] )
WIN_CH_BUFFER.append(chr(KEYMAP["mod_int"] ) )
WIN_CH_BUFFER.append(_lowercase )
if ord(_lowercase ) in (
KEYMAP["insert"] - 1 << 9,
KEYMAP["delete"] - 1 << 9,
KEYMAP["pg_up"] - 1 << 9,
KEYMAP["pg_down"] - 1 << 9,
):
WIN_CH_BUFFER.append(chr(126 ) )
__A : Union[str, Any] = chr(KEYMAP["esc"] )
except KeyError:
__A : Union[str, Any] = cha[1]
else:
__A : List[Any] = ch.decode(_lowercase )
else:
__A : Any = WIN_CH_BUFFER.pop(0 )
elif os.name == "posix":
import termios
import tty
__A : Dict = sys.stdin.fileno()
__A : str = termios.tcgetattr(_lowercase )
try:
tty.setraw(_lowercase )
__A : int = sys.stdin.read(1 )
finally:
termios.tcsetattr(_lowercase , termios.TCSADRAIN , _lowercase )
return ch
def lowerCamelCase_ ( ) -> Optional[Any]:
__A : str = get_raw_chars()
if ord(_lowercase ) in [KEYMAP["interrupt"], KEYMAP["newline"]]:
return char
elif ord(_lowercase ) == KEYMAP["esc"]:
__A : List[Any] = get_raw_chars()
if ord(_lowercase ) == KEYMAP["mod_int"]:
__A : Any = get_raw_chars()
if ord(_lowercase ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(_lowercase ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG:
return chr(ord(_lowercase ) + ARROW_KEY_FLAG )
else:
return KEYMAP["undefined"]
else:
return get_raw_chars()
else:
if char in string.printable:
return char
else:
return KEYMAP["undefined"]
| 520 | class _a :
'''simple docstring'''
def __init__( self , __UpperCAmelCase ):
__A : List[str] = val
__A : str = None
__A : List[Any] = None
def __UpperCAmelCase( self , __UpperCAmelCase ):
if self.val:
if val < self.val:
if self.left is None:
__A : int = Node(__UpperCAmelCase )
else:
self.left.insert(__UpperCAmelCase )
elif val > self.val:
if self.right is None:
__A : int = Node(__UpperCAmelCase )
else:
self.right.insert(__UpperCAmelCase )
else:
__A : Any = val
def lowerCamelCase_ ( _lowercase , _lowercase ) -> Tuple:
# Recursive traversal
if root:
inorder(root.left , _lowercase )
res.append(root.val )
inorder(root.right , _lowercase )
def lowerCamelCase_ ( _lowercase ) -> str:
# Build BST
if len(_lowercase ) == 0:
return arr
__A : Union[str, Any] = Node(arr[0] )
for i in range(1 , len(_lowercase ) ):
root.insert(arr[i] )
# Traverse BST in order.
__A : str = []
inorder(_lowercase , _lowercase )
return res
if __name__ == "__main__":
print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
| 520 | 1 |
"""simple docstring"""
_a : Tuple = {
"""meter""": """m""",
"""kilometer""": """km""",
"""megametre""": """Mm""",
"""gigametre""": """Gm""",
"""terametre""": """Tm""",
"""petametre""": """Pm""",
"""exametre""": """Em""",
"""zettametre""": """Zm""",
"""yottametre""": """Ym""",
}
# Exponent of the factor(meter)
_a : List[Any] = {
"""m""": 0,
"""km""": 3,
"""Mm""": 6,
"""Gm""": 9,
"""Tm""": 12,
"""Pm""": 15,
"""Em""": 18,
"""Zm""": 21,
"""Ym""": 24,
}
def a__ ( a : float , a : str , a : str ):
"""simple docstring"""
_snake_case : List[Any] = from_type.lower().strip("s" )
_snake_case : Dict = to_type.lower().strip("s" )
_snake_case : Tuple = UNIT_SYMBOL.get(a , a )
_snake_case : Optional[int] = UNIT_SYMBOL.get(a , a )
if from_sanitized not in METRIC_CONVERSION:
_snake_case : Tuple = (
f'Invalid \'from_type\' value: {from_type!r}.\n'
f'Conversion abbreviations are: {", ".join(a )}'
)
raise ValueError(a )
if to_sanitized not in METRIC_CONVERSION:
_snake_case : int = (
f'Invalid \'to_type\' value: {to_type!r}.\n'
f'Conversion abbreviations are: {", ".join(a )}'
)
raise ValueError(a )
_snake_case : Dict = METRIC_CONVERSION[from_sanitized]
_snake_case : Union[str, Any] = METRIC_CONVERSION[to_sanitized]
_snake_case : Dict = 1
if from_exponent > to_exponent:
_snake_case : Union[str, Any] = from_exponent - to_exponent
else:
_snake_case : Tuple = -(to_exponent - from_exponent)
return value * pow(10 , a )
if __name__ == "__main__":
from doctest import testmod
testmod()
| 87 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
_a : Optional[int] = {
"""configuration_pix2struct""": [
"""PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""Pix2StructConfig""",
"""Pix2StructTextConfig""",
"""Pix2StructVisionConfig""",
],
"""processing_pix2struct""": ["""Pix2StructProcessor"""],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a : List[Any] = ["""Pix2StructImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a : Dict = [
"""PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""Pix2StructPreTrainedModel""",
"""Pix2StructForConditionalGeneration""",
"""Pix2StructVisionModel""",
"""Pix2StructTextModel""",
]
if TYPE_CHECKING:
from .configuration_pixastruct import (
PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP,
PixaStructConfig,
PixaStructTextConfig,
PixaStructVisionConfig,
)
from .processing_pixastruct import PixaStructProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_pixastruct import PixaStructImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_pixastruct import (
PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST,
PixaStructForConditionalGeneration,
PixaStructPreTrainedModel,
PixaStructTextModel,
PixaStructVisionModel,
)
else:
import sys
_a : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 87 | 1 |
from math import pow, sqrt
def _A ( *_lowercase ) -> bool:
"""simple docstring"""
__UpperCamelCase = len(_lowercase ) > 0 and all(value > 0.0 for value in values )
return result
def _A ( _lowercase , _lowercase ) -> float | ValueError:
"""simple docstring"""
return (
round(sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(_lowercase , _lowercase )
else ValueError('Input Error: Molar mass values must greater than 0.' )
)
def _A ( _lowercase , _lowercase , _lowercase ) -> float | ValueError:
"""simple docstring"""
return (
round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(_lowercase , _lowercase , _lowercase )
else ValueError(
'Input Error: Molar mass and effusion rate values must greater than 0.' )
)
def _A ( _lowercase , _lowercase , _lowercase ) -> float | ValueError:
"""simple docstring"""
return (
round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(_lowercase , _lowercase , _lowercase )
else ValueError(
'Input Error: Molar mass and effusion rate values must greater than 0.' )
)
def _A ( _lowercase , _lowercase , _lowercase ) -> float | ValueError:
"""simple docstring"""
return (
round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 )
if validate(_lowercase , _lowercase , _lowercase )
else ValueError(
'Input Error: Molar mass and effusion rate values must greater than 0.' )
)
def _A ( _lowercase , _lowercase , _lowercase ) -> float | ValueError:
"""simple docstring"""
return (
round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 )
if validate(_lowercase , _lowercase , _lowercase )
else ValueError(
'Input Error: Molar mass and effusion rate values must greater than 0.' )
)
| 1 |
import math
import os
from copy import deepcopy
import datasets
import evaluate
import torch
import transformers
from datasets import load_dataset
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from accelerate import Accelerator
from accelerate.test_utils import RegressionDataset, RegressionModel
from accelerate.utils import is_tpu_available, set_seed
a_ : Any = 'true'
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=16):
set_seed(42)
SCREAMING_SNAKE_CASE = RegressionModel()
SCREAMING_SNAKE_CASE = deepcopy(_UpperCAmelCase)
SCREAMING_SNAKE_CASE = RegressionDataset(length=_UpperCAmelCase)
SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , batch_size=_UpperCAmelCase)
model.to(accelerator.device)
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase)
return model, ddp_model, dataloader
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False):
SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased')
SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation')
def tokenize_function(_UpperCAmelCase):
SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase)
return outputs
with accelerator.main_process_first():
SCREAMING_SNAKE_CASE = dataset.map(
_UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , )
SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels')
def collate_fn(_UpperCAmelCase):
if use_longest:
return tokenizer.pad(_UpperCAmelCase , padding='longest' , return_tensors='pt')
return tokenizer.pad(_UpperCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt')
return DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=16)
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase):
SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=_UpperCAmelCase , split_batches=_UpperCAmelCase)
SCREAMING_SNAKE_CASE = get_dataloader(_UpperCAmelCase , not dispatch_batches)
SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained(
'hf-internal-testing/mrpc-bert-base-cased' , return_dict=_UpperCAmelCase)
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase)
return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase):
SCREAMING_SNAKE_CASE = []
for batch in dataloader:
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values()
with torch.no_grad():
SCREAMING_SNAKE_CASE = model(_UpperCAmelCase)
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target))
logits_and_targets.append((logit, target))
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], []
for logit, targ in logits_and_targets:
logits.append(_UpperCAmelCase)
targs.append(_UpperCAmelCase)
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(_UpperCAmelCase), torch.cat(_UpperCAmelCase)
return logits, targs
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=False , _UpperCAmelCase=False , _UpperCAmelCase=16):
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase)
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase)
assert (
len(_UpperCAmelCase) == num_samples
), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCAmelCase)}'''
def lowerCamelCase__ (_UpperCAmelCase = False , _UpperCAmelCase = False):
SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc')
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(_UpperCAmelCase , _UpperCAmelCase)
# First do baseline
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no']
model.to(_UpperCAmelCase)
model.eval()
for batch in dataloader:
batch.to(_UpperCAmelCase)
with torch.inference_mode():
SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase)
SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1)
metric.add_batch(predictions=_UpperCAmelCase , references=batch['labels'])
SCREAMING_SNAKE_CASE = metric.compute()
# Then do distributed
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp']
model.eval()
for batch in dataloader:
with torch.inference_mode():
SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase)
SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1)
SCREAMING_SNAKE_CASE = batch['labels']
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references))
metric.add_batch(predictions=_UpperCAmelCase , references=_UpperCAmelCase)
SCREAMING_SNAKE_CASE = metric.compute()
for key in "accuracy f1".split():
assert math.isclose(
baseline[key] , distributed[key]), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n'''
def lowerCamelCase__ ():
SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase)
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_warning()
transformers.utils.logging.set_verbosity_warning()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# These are a bit slower so they should only be ran on the GPU or TPU
if torch.cuda.is_available() or is_tpu_available():
if accelerator.is_local_main_process:
print('**Testing gather_for_metrics**')
for split_batches in [True, False]:
for dispatch_batches in [True, False]:
if accelerator.is_local_main_process:
print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''')
test_mrpc(_UpperCAmelCase , _UpperCAmelCase)
accelerator.state._reset_state()
if accelerator.is_local_main_process:
print('**Test torch metrics**')
for split_batches in [True, False]:
for dispatch_batches in [True, False]:
SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase)
if accelerator.is_local_main_process:
print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''')
test_torch_metrics(_UpperCAmelCase , 99)
accelerator.state._reset_state()
if accelerator.is_local_main_process:
print('**Test last batch is not dropped when perfectly divisible**')
SCREAMING_SNAKE_CASE = Accelerator()
test_torch_metrics(_UpperCAmelCase , 512)
accelerator.state._reset_state()
def lowerCamelCase__ (_UpperCAmelCase):
# For xla_spawn (TPUs)
main()
if __name__ == "__main__":
main()
| 73 | 0 |
_lowerCAmelCase = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0],
]
def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ):
'''simple docstring'''
A_ : Tuple = [False] * len(_lowerCAmelCase )
A_ : Optional[int] = [s]
A_ : str = True
while queue:
A_ : Union[str, Any] = queue.pop(0 )
for ind in range(len(graph[u] ) ):
if visited[ind] is False and graph[u][ind] > 0:
queue.append(_lowerCAmelCase )
A_ : Optional[int] = True
A_ : Tuple = u
return visited[t]
def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ):
'''simple docstring'''
A_ : Optional[Any] = [-1] * (len(_lowerCAmelCase ))
A_ : List[str] = 0
A_ : Union[str, Any] = []
A_ : str = [i[:] for i in graph] # Record original cut, copy.
while bfs(_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ):
A_ : Optional[Any] = float("""Inf""" )
A_ : Dict = sink
while s != source:
# Find the minimum value in select path
A_ : str = min(_lowerCAmelCase ,graph[parent[s]][s] )
A_ : Optional[Any] = parent[s]
max_flow += path_flow
A_ : Dict = sink
while v != source:
A_ : Dict = parent[v]
graph[u][v] -= path_flow
graph[v][u] += path_flow
A_ : Optional[int] = parent[v]
for i in range(len(_lowerCAmelCase ) ):
for j in range(len(graph[0] ) ):
if graph[i][j] == 0 and temp[i][j] > 0:
res.append((i, j) )
return res
if __name__ == "__main__":
print(mincut(test_graph, source=0, sink=5))
| 709 |
import copy
import inspect
import unittest
import numpy as np
from huggingface_hub import hf_hub_download
from transformers import VideoMAEConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import (
MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
VideoMAEForPreTraining,
VideoMAEForVideoClassification,
VideoMAEModel,
)
from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from transformers import VideoMAEImageProcessor
class _UpperCAmelCase :
def __init__( self , a__ , a__=13 , a__=10 , a__=3 , a__=2 , a__=2 , a__=2 , a__=True , a__=True , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=10 , a__=0.02 , a__=0.9 , a__=None , ):
A_ : Tuple = parent
A_ : Union[str, Any] = batch_size
A_ : str = image_size
A_ : Union[str, Any] = num_channels
A_ : List[str] = patch_size
A_ : Optional[Any] = tubelet_size
A_ : List[Any] = num_frames
A_ : str = is_training
A_ : List[Any] = use_labels
A_ : List[str] = hidden_size
A_ : Optional[Any] = num_hidden_layers
A_ : str = num_attention_heads
A_ : Union[str, Any] = intermediate_size
A_ : Dict = hidden_act
A_ : int = hidden_dropout_prob
A_ : Union[str, Any] = attention_probs_dropout_prob
A_ : Union[str, Any] = type_sequence_label_size
A_ : int = initializer_range
A_ : Dict = mask_ratio
A_ : Optional[Any] = scope
# in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame
A_ : int = (image_size // patch_size) ** 2
A_ : Dict = (num_frames // tubelet_size) * self.num_patches_per_frame
# use this variable to define bool_masked_pos
A_ : Dict = int(mask_ratio * self.seq_length )
def _lowerCamelCase ( self ):
A_ : Any = floats_tensor(
[self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] )
A_ : Optional[int] = None
if self.use_labels:
A_ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size )
A_ : List[Any] = self.get_config()
return config, pixel_values, labels
def _lowerCamelCase ( self ):
return VideoMAEConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , tubelet_size=self.tubelet_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 , is_decoder=a__ , initializer_range=self.initializer_range , )
def _lowerCamelCase ( self , a__ , a__ , a__ ):
A_ : Dict = VideoMAEModel(config=a__ )
model.to(a__ )
model.eval()
A_ : Dict = model(a__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _lowerCamelCase ( self , a__ , a__ , a__ ):
A_ : Optional[Any] = VideoMAEForPreTraining(a__ )
model.to(a__ )
model.eval()
# important: each video needs to have the same number of masked patches
# hence we define a single mask, which we then repeat for each example in the batch
A_ : List[Any] = torch.ones((self.num_masks,) )
A_ : Dict = torch.cat([mask, torch.zeros(self.seq_length - mask.size(0 ) )] )
A_ : int = mask.expand(self.batch_size , -1 ).bool()
A_ : List[Any] = model(a__ , a__ )
# model only returns predictions for masked patches
A_ : Union[str, Any] = mask.sum().item()
A_ : Tuple = 3 * self.tubelet_size * self.patch_size**2
self.parent.assertEqual(result.logits.shape , (self.batch_size, num_masked_patches, decoder_num_labels) )
def _lowerCamelCase ( self ):
A_ : Union[str, Any] = self.prepare_config_and_inputs()
A_ , A_ , A_ : Optional[Any] = config_and_inputs
A_ : str = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_torch
class _UpperCAmelCase ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase ):
a = (
(VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
)
a = (
{'''feature-extraction''': VideoMAEModel, '''video-classification''': VideoMAEForVideoClassification}
if is_torch_available()
else {}
)
a = False
a = False
a = False
a = False
def _lowerCamelCase ( self ):
A_ : int = VideoMAEModelTester(self )
A_ : Any = ConfigTester(self , config_class=a__ , has_text_modality=a__ , hidden_size=37 )
def _lowerCamelCase ( self , a__ , a__ , a__=False ):
A_ : Optional[Any] = copy.deepcopy(a__ )
if model_class == VideoMAEForPreTraining:
# important: each video needs to have the same number of masked patches
# hence we define a single mask, which we then repeat for each example in the batch
A_ : List[Any] = torch.ones((self.model_tester.num_masks,) )
A_ : List[str] = torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0 ) )] )
A_ : Union[str, Any] = mask.expand(self.model_tester.batch_size , -1 ).bool()
A_ : int = bool_masked_pos.to(a__ )
if return_labels:
if model_class in [
*get_values(a__ ),
]:
A_ : List[str] = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=a__ )
return inputs_dict
def _lowerCamelCase ( self ):
self.config_tester.run_common_tests()
@unittest.skip(reason="""VideoMAE does not use inputs_embeds""" )
def _lowerCamelCase ( self ):
pass
def _lowerCamelCase ( self ):
A_ , A_ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
A_ : Tuple = model_class(a__ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
A_ : Union[str, Any] = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(a__ , nn.Linear ) )
def _lowerCamelCase ( self ):
A_ , A_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
A_ : List[str] = model_class(a__ )
A_ : List[Any] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
A_ : Dict = [*signature.parameters.keys()]
A_ : str = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] , a__ )
def _lowerCamelCase ( self ):
A_ : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a__ )
def _lowerCamelCase ( self ):
A_ : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*a__ )
@slow
def _lowerCamelCase ( self ):
for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
A_ : Any = VideoMAEModel.from_pretrained(a__ )
self.assertIsNotNone(a__ )
def _lowerCamelCase ( self ):
if not self.has_attentions:
pass
else:
A_ , A_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
A_ : Optional[int] = True
for model_class in self.all_model_classes:
A_ : str = self.model_tester.seq_length - self.model_tester.num_masks
A_ : List[Any] = (
num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
)
A_ : Optional[int] = True
A_ : Optional[Any] = False
A_ : List[Any] = True
A_ : List[str] = model_class(a__ )
model.to(a__ )
model.eval()
with torch.no_grad():
A_ : List[Any] = model(**self._prepare_for_class(a__ , a__ ) )
A_ : Dict = outputs.attentions
self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers )
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
A_ : List[Any] = True
A_ : List[str] = model_class(a__ )
model.to(a__ )
model.eval()
with torch.no_grad():
A_ : int = model(**self._prepare_for_class(a__ , a__ ) )
A_ : Any = outputs.attentions
self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , )
A_ : Union[str, Any] = len(a__ )
# Check attention is always last and order is fine
A_ : Optional[Any] = True
A_ : int = True
A_ : List[str] = model_class(a__ )
model.to(a__ )
model.eval()
with torch.no_grad():
A_ : Tuple = model(**self._prepare_for_class(a__ , a__ ) )
self.assertEqual(out_len + 1 , len(a__ ) )
A_ : Optional[Any] = outputs.attentions
self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , )
def _lowerCamelCase ( self ):
def check_hidden_states_output(a__ , a__ , a__ ):
A_ : str = model_class(a__ )
model.to(a__ )
model.eval()
with torch.no_grad():
A_ : Union[str, Any] = model(**self._prepare_for_class(a__ , a__ ) )
A_ : Optional[Any] = outputs.hidden_states
A_ : Union[str, Any] = self.model_tester.num_hidden_layers + 1
self.assertEqual(len(a__ ) , a__ )
A_ : str = self.model_tester.seq_length - self.model_tester.num_masks
A_ : str = num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , )
A_ , A_ : Any = 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(a__ , a__ , a__ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
A_ : Tuple = True
check_hidden_states_output(a__ , a__ , a__ )
@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" )
def _lowerCamelCase ( self ):
pass
def _lowerCAmelCase ( ):
'''simple docstring'''
A_ : int = hf_hub_download(
repo_id="""hf-internal-testing/spaghetti-video""" ,filename="""eating_spaghetti.npy""" ,repo_type="""dataset""" )
A_ : Optional[int] = np.load(_lowerCAmelCase )
return list(_lowerCAmelCase )
@require_torch
@require_vision
class _UpperCAmelCase ( unittest.TestCase ):
@cached_property
def _lowerCamelCase ( self ):
# logits were tested with a different mean and std, so we use the same here
return (
VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] )
if is_vision_available()
else None
)
@slow
def _lowerCamelCase ( self ):
A_ : List[str] = VideoMAEForVideoClassification.from_pretrained("""MCG-NJU/videomae-base-finetuned-kinetics""" ).to(
a__ )
A_ : Any = self.default_image_processor
A_ : Optional[Any] = prepare_video()
A_ : Union[str, Any] = image_processor(a__ , return_tensors="""pt""" ).to(a__ )
# forward pass
with torch.no_grad():
A_ : Any = model(**a__ )
# verify the logits
A_ : List[str] = torch.Size((1, 400) )
self.assertEqual(outputs.logits.shape , a__ )
A_ : Optional[Any] = torch.tensor([0.3669, -0.0688, -0.2421] ).to(a__ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , a__ , atol=1E-4 ) )
@slow
def _lowerCamelCase ( self ):
A_ : int = VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short""" ).to(a__ )
A_ : str = self.default_image_processor
A_ : Any = prepare_video()
A_ : Union[str, Any] = image_processor(a__ , return_tensors="""pt""" ).to(a__ )
# add boolean mask, indicating which patches to mask
A_ : Optional[Any] = hf_hub_download(repo_id="""hf-internal-testing/bool-masked-pos""" , filename="""bool_masked_pos.pt""" )
A_ : Dict = torch.load(a__ )
# forward pass
with torch.no_grad():
A_ : Optional[int] = model(**a__ )
# verify the logits
A_ : int = torch.Size([1, 1408, 1536] )
A_ : Union[str, Any] = torch.tensor(
[[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]] , device=a__ )
self.assertEqual(outputs.logits.shape , a__ )
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , a__ , atol=1E-4 ) )
# verify the loss (`config.norm_pix_loss` = `True`)
A_ : Optional[Any] = torch.tensor([0.5142] , device=a__ )
self.assertTrue(torch.allclose(outputs.loss , a__ , atol=1E-4 ) )
# verify the loss (`config.norm_pix_loss` = `False`)
A_ : Optional[int] = VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short""" , norm_pix_loss=a__ ).to(
a__ )
with torch.no_grad():
A_ : Optional[Any] = model(**a__ )
A_ : List[Any] = torch.tensor(torch.tensor([0.6469] ) , device=a__ )
self.assertTrue(torch.allclose(outputs.loss , a__ , atol=1E-4 ) )
| 481 | 0 |
import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
########################################################################
# This is a fully working simple example to use Accelerate
# and perform gradient accumulation
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
# - single CPU or single GPU
# - multi GPUS (using PyTorch distributed mode)
# - (multi) TPUs
# - fp16 (mixed-precision) or fp32 (normal precision)
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################
_UpperCAmelCase : Union[str, Any] = 16
_UpperCAmelCase : List[Any] = 32
def lowerCAmelCase_ (lowercase__ : Accelerator , lowercase__ : int = 16 ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase__ = AutoTokenizer.from_pretrained('''bert-base-cased''' )
lowerCAmelCase__ = load_dataset('''glue''' , '''mrpc''' )
def tokenize_function(lowercase__ : Optional[int] ):
# max_length=None => use the model max length (it's actually the default)
lowerCAmelCase__ = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=lowercase__ , max_length=lowercase__ )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
lowerCAmelCase__ = datasets.map(
lowercase__ , batched=lowercase__ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
lowerCAmelCase__ = tokenized_datasets.rename_column('''label''' , '''labels''' )
def collate_fn(lowercase__ : List[Any] ):
# On TPU it's best to pad everything to the same length or training will be very slow.
lowerCAmelCase__ = 1_28 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
lowerCAmelCase__ = 16
elif accelerator.mixed_precision != "no":
lowerCAmelCase__ = 8
else:
lowerCAmelCase__ = None
return tokenizer.pad(
lowercase__ , padding='''longest''' , max_length=lowercase__ , pad_to_multiple_of=lowercase__ , return_tensors='''pt''' , )
# Instantiate dataloaders.
lowerCAmelCase__ = DataLoader(
tokenized_datasets['''train'''] , shuffle=lowercase__ , collate_fn=lowercase__ , batch_size=lowercase__ )
lowerCAmelCase__ = DataLoader(
tokenized_datasets['''validation'''] , shuffle=lowercase__ , collate_fn=lowercase__ , batch_size=lowercase__ )
return train_dataloader, eval_dataloader
# For testing only
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
_UpperCAmelCase : Union[str, Any] = mocked_dataloaders # noqa: F811
def lowerCAmelCase_ (lowercase__ : List[str] , lowercase__ : str ) -> Optional[Any]:
'''simple docstring'''
if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , lowercase__ ) == "1":
lowerCAmelCase__ = 2
# New Code #
lowerCAmelCase__ = int(args.gradient_accumulation_steps )
# Initialize accelerator
lowerCAmelCase__ = Accelerator(
cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=lowercase__ )
if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1:
raise NotImplementedError(
'''Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`''' )
# 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__ = evaluate.load('''glue''' , '''mrpc''' )
set_seed(lowercase__ )
lowerCAmelCase__ , lowerCAmelCase__ = get_dataloaders(lowercase__ , lowercase__ )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
lowerCAmelCase__ = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=lowercase__ )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
lowerCAmelCase__ = model.to(accelerator.device )
# Instantiate optimizer
lowerCAmelCase__ = AdamW(params=model.parameters() , lr=lowercase__ )
# Instantiate scheduler
lowerCAmelCase__ = get_linear_schedule_with_warmup(
optimizer=lowercase__ , num_warmup_steps=1_00 , num_training_steps=(len(lowercase__ ) * num_epochs) , )
# 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(
lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )
# Now we train the model
for epoch in range(lowercase__ ):
model.train()
for step, batch in enumerate(lowercase__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
# New code #
# We use the new `accumulate` context manager to perform gradient accumulation
# We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests.
with accelerator.accumulate(lowercase__ ):
lowerCAmelCase__ = model(**lowercase__ )
lowerCAmelCase__ = output.loss
accelerator.backward(lowercase__ )
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(lowercase__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
lowerCAmelCase__ = model(**lowercase__ )
lowerCAmelCase__ = outputs.logits.argmax(dim=-1 )
lowerCAmelCase__ , lowerCAmelCase__ = accelerator.gather_for_metrics((predictions, batch['''labels''']) )
metric.add_batch(
predictions=lowercase__ , references=lowercase__ , )
lowerCAmelCase__ = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f'epoch {epoch}:' , lowercase__ )
def lowerCAmelCase_ () -> int:
'''simple docstring'''
lowerCAmelCase__ = argparse.ArgumentParser(description='''Simple example of training script.''' )
parser.add_argument(
'''--mixed_precision''' , type=lowercase__ , default=lowercase__ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose'''
'''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'''
'''and an Nvidia Ampere GPU.''' , )
# New Code #
parser.add_argument(
'''--gradient_accumulation_steps''' , type=lowercase__ , default=1 , help='''The number of minibatches to be ran before gradients are accumulated.''' , )
parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' )
lowerCAmelCase__ = parser.parse_args()
lowerCAmelCase__ = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
training_function(lowercase__ , lowercase__ )
if __name__ == "__main__":
main()
| 668 |
from typing import Dict
import numpy as np
import torch
from . import residue_constants as rc
from .tensor_utils import tensor_tree_map, tree_map
def _a ( a :Dict[str, torch.Tensor] ) -> Dict[str, torch.Tensor]:
a = []
a = []
a = []
for rt in rc.restypes:
a = rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]]
restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] )
a = {name: i for i, name in enumerate(a )}
restype_atomaa_to_atomaa_list.append(
[(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] )
restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] )
# Add dummy mapping for restype 'UNK'
restype_atomaa_to_atomaa_list.append([0] * 14 )
restype_atomaa_to_atomaa_list.append([0] * 37 )
restype_atomaa_mask_list.append([0.0] * 14 )
a = torch.tensor(
a , dtype=torch.intaa , device=protein['''aatype'''].device , )
a = torch.tensor(
a , dtype=torch.intaa , device=protein['''aatype'''].device , )
a = torch.tensor(
a , dtype=torch.floataa , device=protein['''aatype'''].device , )
a = protein['''aatype'''].to(torch.long )
# create the mapping for (residx, atom14) --> atom37, i.e. an array
# with shape (num_res, 14) containing the atom37 indices for this protein
a = restype_atomaa_to_atomaa[protein_aatype]
a = restype_atomaa_mask[protein_aatype]
a = residx_atomaa_mask
a = residx_atomaa_to_atomaa.long()
# create the gather indices for mapping back
a = restype_atomaa_to_atomaa[protein_aatype]
a = residx_atomaa_to_atomaa.long()
# create the corresponding mask
a = torch.zeros([21, 37] , dtype=torch.floataa , device=protein['''aatype'''].device )
for restype, restype_letter in enumerate(rc.restypes ):
a = rc.restype_atoa[restype_letter]
a = rc.residue_atoms[restype_name]
for atom_name in atom_names:
a = rc.atom_order[atom_name]
a = 1
a = restype_atomaa_mask[protein_aatype]
a = residx_atomaa_mask
return protein
def _a ( a :Dict[str, torch.Tensor] ) -> Dict[str, np.ndarray]:
a = tree_map(lambda a : torch.tensor(a , device=batch['''aatype'''].device ) , a , np.ndarray )
a = tensor_tree_map(lambda a : np.array(a ) , make_atomaa_masks(a ) )
return out
| 117 | 0 |
'''simple docstring'''
import warnings
from typing import Any, Dict, List, Optional, Union
import numpy as np
from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging
UpperCamelCase : List[Any] = logging.get_logger(__name__)
class UpperCamelCase__ (a ):
'''simple docstring'''
_UpperCamelCase = ['input_values', 'attention_mask']
def __init__( self ,_lowerCAmelCase = 1 ,_lowerCAmelCase = 1_60_00 ,_lowerCAmelCase = 0.0 ,_lowerCAmelCase = False ,_lowerCAmelCase = 80 ,_lowerCAmelCase = 16 ,_lowerCAmelCase = 64 ,_lowerCAmelCase = "hann_window" ,_lowerCAmelCase = 1.0 ,_lowerCAmelCase = 80 ,_lowerCAmelCase = 76_00 ,_lowerCAmelCase = 1E-10 ,_lowerCAmelCase = 2 ,_lowerCAmelCase = True ,**_lowerCAmelCase ,):
super().__init__(feature_size=_lowerCAmelCase ,sampling_rate=_lowerCAmelCase ,padding_value=_lowerCAmelCase ,**_lowerCAmelCase )
lowerCamelCase__ = do_normalize
lowerCamelCase__ = return_attention_mask
lowerCamelCase__ = num_mel_bins
lowerCamelCase__ = hop_length
lowerCamelCase__ = win_length
lowerCamelCase__ = win_function
lowerCamelCase__ = frame_signal_scale
lowerCamelCase__ = fmin
lowerCamelCase__ = fmax
lowerCamelCase__ = mel_floor
lowerCamelCase__ = reduction_factor
lowerCamelCase__ = win_length * sampling_rate // 10_00
lowerCamelCase__ = hop_length * sampling_rate // 10_00
lowerCamelCase__ = optimal_fft_length(self.sample_size )
lowerCamelCase__ = (self.n_fft // 2) + 1
lowerCamelCase__ = window_function(window_length=self.sample_size ,name=self.win_function ,periodic=_lowerCAmelCase )
lowerCamelCase__ = mel_filter_bank(
num_frequency_bins=self.n_freqs ,num_mel_filters=self.num_mel_bins ,min_frequency=self.fmin ,max_frequency=self.fmax ,sampling_rate=self.sampling_rate ,norm="""slaney""" ,mel_scale="""slaney""" ,)
if frame_signal_scale != 1.0:
warnings.warn(
"""The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers""" ,_lowerCAmelCase ,)
if reduction_factor != 2.0:
warnings.warn(
"""The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers""" ,_lowerCAmelCase ,)
@staticmethod
# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
def UpperCamelCase_ ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase = 0.0 ):
if attention_mask is not None:
lowerCamelCase__ = np.array(_lowerCAmelCase ,np.intaa )
lowerCamelCase__ = []
for vector, length in zip(_lowerCAmelCase ,attention_mask.sum(-1 ) ):
lowerCamelCase__ = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7 )
if length < normed_slice.shape[0]:
lowerCamelCase__ = padding_value
normed_input_values.append(_lowerCAmelCase )
else:
lowerCamelCase__ = [(x - x.mean()) / np.sqrt(x.var() + 1E-7 ) for x in input_values]
return normed_input_values
def UpperCamelCase_ ( self ,_lowerCAmelCase ,):
lowerCamelCase__ = spectrogram(
_lowerCAmelCase ,window=self.window ,frame_length=self.sample_size ,hop_length=self.sample_stride ,fft_length=self.n_fft ,mel_filters=self.mel_filters ,mel_floor=self.mel_floor ,log_mel="""log10""" ,)
return log_mel_spec.T
def __call__( self ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,_lowerCAmelCase = False ,_lowerCAmelCase = None ,_lowerCAmelCase = False ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,**_lowerCAmelCase ,):
if audio is None and audio_target is None:
raise ValueError("""You must provide either `audio` or `audio_target` values.""" )
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
F''' {self.sampling_rate}. Please make sure that the provided audio input was sampled with'''
F''' {self.sampling_rate} and not {sampling_rate}.''' )
else:
logger.warning(
"""It is strongly recommended to pass the ``sampling_rate`` argument to this function. """
"""Failing to do so can result in silent errors that might be hard to debug.""" )
if audio is not None:
lowerCamelCase__ = self._process_audio(
_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,**_lowerCAmelCase ,)
else:
lowerCamelCase__ = None
if audio_target is not None:
lowerCamelCase__ = self._process_audio(
_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,**_lowerCAmelCase ,)
if inputs is None:
return inputs_target
else:
lowerCamelCase__ = inputs_target["""input_values"""]
lowerCamelCase__ = inputs_target.get("""attention_mask""" )
if decoder_attention_mask is not None:
lowerCamelCase__ = decoder_attention_mask
return inputs
def UpperCamelCase_ ( self ,_lowerCAmelCase ,_lowerCAmelCase = False ,_lowerCAmelCase = False ,_lowerCAmelCase = None ,_lowerCAmelCase = False ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,**_lowerCAmelCase ,):
lowerCamelCase__ = isinstance(_lowerCAmelCase ,np.ndarray ) and len(speech.shape ) > 1
if is_batched_numpy and len(speech.shape ) > 2:
raise ValueError(F'''Only mono-channel audio is supported for input to {self}''' )
lowerCamelCase__ = is_batched_numpy or (
isinstance(_lowerCAmelCase ,(list, tuple) ) and (isinstance(speech[0] ,(np.ndarray, tuple, list) ))
)
if is_batched:
lowerCamelCase__ = [np.asarray(_lowerCAmelCase ,dtype=np.floataa ) for speech in speech]
elif not is_batched and not isinstance(_lowerCAmelCase ,np.ndarray ):
lowerCamelCase__ = np.asarray(_lowerCAmelCase ,dtype=np.floataa )
elif isinstance(_lowerCAmelCase ,np.ndarray ) and speech.dtype is np.dtype(np.floataa ):
lowerCamelCase__ = speech.astype(np.floataa )
# always return batch
if not is_batched:
lowerCamelCase__ = [speech]
# needed to make pad() work on spectrogram inputs
lowerCamelCase__ = self.feature_size
# convert into correct format for padding
if is_target:
lowerCamelCase__ = [self._extract_mel_features(_lowerCAmelCase ) for waveform in speech]
lowerCamelCase__ = BatchFeature({"""input_values""": features} )
lowerCamelCase__ = self.num_mel_bins
else:
lowerCamelCase__ = BatchFeature({"""input_values""": speech} )
lowerCamelCase__ = self.pad(
_lowerCAmelCase ,padding=_lowerCAmelCase ,max_length=_lowerCAmelCase ,truncation=_lowerCAmelCase ,pad_to_multiple_of=_lowerCAmelCase ,return_attention_mask=_lowerCAmelCase ,**_lowerCAmelCase ,)
lowerCamelCase__ = feature_size_hack
# convert input values to correct format
lowerCamelCase__ = padded_inputs["""input_values"""]
if not isinstance(input_values[0] ,np.ndarray ):
lowerCamelCase__ = [np.asarray(_lowerCAmelCase ,dtype=np.floataa ) for array in input_values]
elif (
not isinstance(_lowerCAmelCase ,np.ndarray )
and isinstance(input_values[0] ,np.ndarray )
and input_values[0].dtype is np.dtype(np.floataa )
):
lowerCamelCase__ = [array.astype(np.floataa ) for array in input_values]
elif isinstance(_lowerCAmelCase ,np.ndarray ) and input_values.dtype is np.dtype(np.floataa ):
lowerCamelCase__ = input_values.astype(np.floataa )
# convert attention_mask to correct format
lowerCamelCase__ = padded_inputs.get("""attention_mask""" )
if attention_mask is not None:
lowerCamelCase__ = [np.asarray(_lowerCAmelCase ,dtype=np.intaa ) for array in attention_mask]
# zero-mean and unit-variance normalization
if not is_target and self.do_normalize:
lowerCamelCase__ = (
attention_mask
if self._get_padding_strategies(_lowerCAmelCase ,max_length=_lowerCAmelCase ) is not PaddingStrategy.DO_NOT_PAD
else None
)
lowerCamelCase__ = self.zero_mean_unit_var_norm(
padded_inputs["""input_values"""] ,attention_mask=_lowerCAmelCase ,padding_value=self.padding_value )
if return_tensors is not None:
lowerCamelCase__ = padded_inputs.convert_to_tensors(_lowerCAmelCase )
return padded_inputs
def UpperCamelCase_ ( self ):
lowerCamelCase__ = super().to_dict()
# Don't serialize these as they are derived from the other properties.
lowerCamelCase__ = ["""window""", """mel_filters""", """sample_size""", """sample_stride""", """n_fft""", """n_freqs"""]
for name in names:
if name in output:
del output[name]
return output
| 9 |
'''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 UpperCamelCase__ (unittest.TestCase ):
'''simple docstring'''
def UpperCamelCase_ ( self ):
lowerCamelCase__ = tempfile.mkdtemp()
lowerCamelCase__ = BlipImageProcessor()
lowerCamelCase__ = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-BertModel""" )
lowerCamelCase__ = BlipProcessor(_lowerCAmelCase ,_lowerCAmelCase )
processor.save_pretrained(self.tmpdirname )
def UpperCamelCase_ ( self ,**_lowerCAmelCase ):
return AutoProcessor.from_pretrained(self.tmpdirname ,**_lowerCAmelCase ).tokenizer
def UpperCamelCase_ ( self ,**_lowerCAmelCase ):
return AutoProcessor.from_pretrained(self.tmpdirname ,**_lowerCAmelCase ).image_processor
def UpperCamelCase_ ( self ):
shutil.rmtree(self.tmpdirname )
def UpperCamelCase_ ( self ):
lowerCamelCase__ = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )]
lowerCamelCase__ = [Image.fromarray(np.moveaxis(_lowerCAmelCase ,0 ,-1 ) ) for x in image_inputs]
return image_inputs
def UpperCamelCase_ ( self ):
lowerCamelCase__ = BlipProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
lowerCamelCase__ = self.get_tokenizer(bos_token="""(BOS)""" ,eos_token="""(EOS)""" )
lowerCamelCase__ = self.get_image_processor(do_normalize=_lowerCAmelCase ,padding_value=1.0 )
lowerCamelCase__ = BlipProcessor.from_pretrained(
self.tmpdirname ,bos_token="""(BOS)""" ,eos_token="""(EOS)""" ,do_normalize=_lowerCAmelCase ,padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer ,_lowerCAmelCase )
self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor ,_lowerCAmelCase )
def UpperCamelCase_ ( self ):
lowerCamelCase__ = self.get_image_processor()
lowerCamelCase__ = self.get_tokenizer()
lowerCamelCase__ = BlipProcessor(tokenizer=_lowerCAmelCase ,image_processor=_lowerCAmelCase )
lowerCamelCase__ = self.prepare_image_inputs()
lowerCamelCase__ = image_processor(_lowerCAmelCase ,return_tensors="""np""" )
lowerCamelCase__ = processor(images=_lowerCAmelCase ,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 UpperCamelCase_ ( self ):
lowerCamelCase__ = self.get_image_processor()
lowerCamelCase__ = self.get_tokenizer()
lowerCamelCase__ = BlipProcessor(tokenizer=_lowerCAmelCase ,image_processor=_lowerCAmelCase )
lowerCamelCase__ = """lower newer"""
lowerCamelCase__ = processor(text=_lowerCAmelCase )
lowerCamelCase__ = tokenizer(_lowerCAmelCase ,return_token_type_ids=_lowerCAmelCase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] ,encoded_processor[key] )
def UpperCamelCase_ ( self ):
lowerCamelCase__ = self.get_image_processor()
lowerCamelCase__ = self.get_tokenizer()
lowerCamelCase__ = BlipProcessor(tokenizer=_lowerCAmelCase ,image_processor=_lowerCAmelCase )
lowerCamelCase__ = """lower newer"""
lowerCamelCase__ = self.prepare_image_inputs()
lowerCamelCase__ = processor(text=_lowerCAmelCase ,images=_lowerCAmelCase )
self.assertListEqual(list(inputs.keys() ) ,["""pixel_values""", """input_ids""", """attention_mask"""] )
# test if it raises when no input is passed
with pytest.raises(_lowerCAmelCase ):
processor()
def UpperCamelCase_ ( self ):
lowerCamelCase__ = self.get_image_processor()
lowerCamelCase__ = self.get_tokenizer()
lowerCamelCase__ = BlipProcessor(tokenizer=_lowerCAmelCase ,image_processor=_lowerCAmelCase )
lowerCamelCase__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
lowerCamelCase__ = processor.batch_decode(_lowerCAmelCase )
lowerCamelCase__ = tokenizer.batch_decode(_lowerCAmelCase )
self.assertListEqual(_lowerCAmelCase ,_lowerCAmelCase )
def UpperCamelCase_ ( self ):
lowerCamelCase__ = self.get_image_processor()
lowerCamelCase__ = self.get_tokenizer()
lowerCamelCase__ = BlipProcessor(tokenizer=_lowerCAmelCase ,image_processor=_lowerCAmelCase )
lowerCamelCase__ = """lower newer"""
lowerCamelCase__ = self.prepare_image_inputs()
lowerCamelCase__ = processor(text=_lowerCAmelCase ,images=_lowerCAmelCase )
# For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
self.assertListEqual(list(inputs.keys() ) ,["""pixel_values""", """input_ids""", """attention_mask"""] )
| 9 | 1 |
def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : Dict ) -> Any:
# if the collection is empty, returns empty
if collection == []:
return []
# get some information about the collection
SCREAMING_SNAKE_CASE_ : List[Any] =len(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE_ : Optional[Any] =max(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE_ : List[Any] =min(UpperCAmelCase_ )
# create the counting array
SCREAMING_SNAKE_CASE_ : List[Any] =coll_max + 1 - coll_min
SCREAMING_SNAKE_CASE_ : List[Any] =[0] * counting_arr_length
# count how much a number appears in the collection
for number in collection:
counting_arr[number - coll_min] += 1
# sum each position with it's predecessors. now, counting_arr[i] tells
# us how many elements <= i has in the collection
for i in range(1 , UpperCAmelCase_ ):
SCREAMING_SNAKE_CASE_ : Any =counting_arr[i] + counting_arr[i - 1]
# create the output collection
SCREAMING_SNAKE_CASE_ : Optional[Any] =[0] * coll_len
# place the elements in the output, respecting the original order (stable
# sort) from end to begin, updating counting_arr
for i in reversed(range(0 , UpperCAmelCase_ ) ):
SCREAMING_SNAKE_CASE_ : Union[str, Any] =collection[i]
counting_arr[collection[i] - coll_min] -= 1
return ordered
def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : List[str] ) -> Dict:
return "".join([chr(UpperCAmelCase_ ) for i in counting_sort([ord(UpperCAmelCase_ ) for c in string] )] )
if __name__ == "__main__":
# Test string sort
assert counting_sort_string("""thisisthestring""") == "eghhiiinrsssttt"
_lowercase = input("""Enter numbers separated by a comma:\n""").strip()
_lowercase = [int(item) for item in user_input.split(""",""")]
print(counting_sort(unsorted))
| 443 |
def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : list ) -> float:
SCREAMING_SNAKE_CASE_ : Dict =0
while len(UpperCAmelCase_ ) > 1:
SCREAMING_SNAKE_CASE_ : Tuple =0
# Consider two files with minimum cost to be merged
for _ in range(2 ):
SCREAMING_SNAKE_CASE_ : int =files.index(min(UpperCAmelCase_ ) )
temp += files[min_index]
files.pop(UpperCAmelCase_ )
files.append(UpperCAmelCase_ )
optimal_merge_cost += temp
return optimal_merge_cost
if __name__ == "__main__":
import doctest
doctest.testmod()
| 443 | 1 |
import inspect
import os
import unittest
from dataclasses import dataclass
import torch
from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs
from accelerate.state import AcceleratorState
from accelerate.test_utils import execute_subprocess_async, require_cuda, require_multi_gpu
from accelerate.utils import KwargsHandler
@dataclass
class UpperCAmelCase__ ( snake_case ):
"""simple docstring"""
lowerCAmelCase__ : int = 0
lowerCAmelCase__ : bool = False
lowerCAmelCase__ : float = 3.0
class UpperCAmelCase__ ( unittest.TestCase ):
"""simple docstring"""
def _UpperCAmelCase ( self: Optional[int] ) -> str:
'''simple docstring'''
self.assertDictEqual(MockClass().to_kwargs() , {} )
self.assertDictEqual(MockClass(a=2 ).to_kwargs() , {"a": 2} )
self.assertDictEqual(MockClass(a=2 , b=__lowerCAmelCase ).to_kwargs() , {"a": 2, "b": True} )
self.assertDictEqual(MockClass(a=2 , c=2.25 ).to_kwargs() , {"a": 2, "c": 2.25} )
@require_cuda
def _UpperCAmelCase ( self: str ) -> int:
'''simple docstring'''
__UpperCAmelCase = GradScalerKwargs(init_scale=1_024 , growth_factor=2 )
AcceleratorState._reset_state()
__UpperCAmelCase = Accelerator(mixed_precision="fp16" , kwargs_handlers=[scaler_handler] )
print(accelerator.use_fpaa )
__UpperCAmelCase = accelerator.scaler
# Check the kwargs have been applied
self.assertEqual(scaler._init_scale , 1024.0 )
self.assertEqual(scaler._growth_factor , 2.0 )
# Check the other values are at the default
self.assertEqual(scaler._backoff_factor , 0.5 )
self.assertEqual(scaler._growth_interval , 2_000 )
self.assertEqual(scaler._enabled , __lowerCAmelCase )
@require_multi_gpu
def _UpperCAmelCase ( self: List[Any] ) -> List[str]:
'''simple docstring'''
__UpperCAmelCase = ["torchrun", F'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )]
execute_subprocess_async(__lowerCAmelCase , env=os.environ.copy() )
if __name__ == "__main__":
a_ = DistributedDataParallelKwargs(bucket_cap_mb=15, find_unused_parameters=True)
a_ = Accelerator(kwargs_handlers=[ddp_scaler])
a_ = torch.nn.Linear(100, 200)
a_ = accelerator.prepare(model)
# Check the values changed in kwargs
a_ = """"""
a_ = model.bucket_bytes_cap // (1024 * 1024)
if observed_bucket_cap_map != 15:
error_msg += F"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n"
if model.find_unused_parameters is not True:
error_msg += F"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n"
# Check the values of the defaults
if model.dim != 0:
error_msg += F"Default value not respected, should have `0` but found {model.dim}.\n"
if model.broadcast_buffers is not True:
error_msg += F"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n"
if model.gradient_as_bucket_view is not False:
error_msg += F"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n"
# Raise error at the end to make sure we don't stop at the first failure.
if len(error_msg) > 0:
raise ValueError(error_msg)
| 721 | import argparse
import hashlib
import os
import urllib
import warnings
import torch
from torch import nn
from tqdm import tqdm
from transformers import WhisperConfig, WhisperForConditionalGeneration
a_ = {
"""tiny.en""": """https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt""",
"""tiny""": """https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt""",
"""base.en""": """https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt""",
"""base""": """https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt""",
"""small.en""": """https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt""",
"""small""": """https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt""",
"""medium.en""": """https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt""",
"""medium""": """https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt""",
"""large""": """https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt""",
"""large-v2""": """https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt""",
}
def __lowerCAmelCase ( A_ : Optional[int] ) -> str:
__UpperCAmelCase = ["layers", "blocks"]
for k in ignore_keys:
state_dict.pop(A_ , A_ )
a_ = {
"""blocks""": """layers""",
"""mlp.0""": """fc1""",
"""mlp.2""": """fc2""",
"""mlp_ln""": """final_layer_norm""",
""".attn.query""": """.self_attn.q_proj""",
""".attn.key""": """.self_attn.k_proj""",
""".attn.value""": """.self_attn.v_proj""",
""".attn_ln""": """.self_attn_layer_norm""",
""".attn.out""": """.self_attn.out_proj""",
""".cross_attn.query""": """.encoder_attn.q_proj""",
""".cross_attn.key""": """.encoder_attn.k_proj""",
""".cross_attn.value""": """.encoder_attn.v_proj""",
""".cross_attn_ln""": """.encoder_attn_layer_norm""",
""".cross_attn.out""": """.encoder_attn.out_proj""",
"""decoder.ln.""": """decoder.layer_norm.""",
"""encoder.ln.""": """encoder.layer_norm.""",
"""token_embedding""": """embed_tokens""",
"""encoder.positional_embedding""": """encoder.embed_positions.weight""",
"""decoder.positional_embedding""": """decoder.embed_positions.weight""",
"""ln_post""": """layer_norm""",
}
def __lowerCAmelCase ( A_ : str ) -> List[str]:
__UpperCAmelCase = list(s_dict.keys() )
for key in keys:
__UpperCAmelCase = key
for k, v in WHISPER_MAPPING.items():
if k in key:
__UpperCAmelCase = new_key.replace(A_ , A_ )
print(F'''{key} -> {new_key}''' )
__UpperCAmelCase = s_dict.pop(A_ )
return s_dict
def __lowerCAmelCase ( A_ : List[Any] ) -> List[Any]:
__UpperCAmelCase , __UpperCAmelCase = emb.weight.shape
__UpperCAmelCase = nn.Linear(A_ , A_ , bias=A_ )
__UpperCAmelCase = emb.weight.data
return lin_layer
def __lowerCAmelCase ( A_ : str , A_ : str ) -> bytes:
os.makedirs(A_ , exist_ok=A_ )
__UpperCAmelCase = os.path.basename(A_ )
__UpperCAmelCase = url.split("/" )[-2]
__UpperCAmelCase = os.path.join(A_ , A_ )
if os.path.exists(A_ ) and not os.path.isfile(A_ ):
raise RuntimeError(F'''{download_target} exists and is not a regular file''' )
if os.path.isfile(A_ ):
__UpperCAmelCase = open(A_ , "rb" ).read()
if hashlib.shaaaa(A_ ).hexdigest() == expected_shaaaa:
return model_bytes
else:
warnings.warn(F'''{download_target} exists, but the SHA256 checksum does not match; re-downloading the file''' )
with urllib.request.urlopen(A_ ) as source, open(A_ , "wb" ) as output:
with tqdm(
total=int(source.info().get("Content-Length" ) ) , ncols=80 , unit="iB" , unit_scale=A_ , unit_divisor=10_24 ) as loop:
while True:
__UpperCAmelCase = source.read(81_92 )
if not buffer:
break
output.write(A_ )
loop.update(len(A_ ) )
__UpperCAmelCase = open(A_ , "rb" ).read()
if hashlib.shaaaa(A_ ).hexdigest() != expected_shaaaa:
raise RuntimeError(
"Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model." )
return model_bytes
def __lowerCAmelCase ( A_ : Dict , A_ : Optional[Any] ) -> Optional[Any]:
if ".pt" not in checkpoint_path:
__UpperCAmelCase = _download(_MODELS[checkpoint_path] )
else:
__UpperCAmelCase = torch.load(A_ , map_location="cpu" )
__UpperCAmelCase = original_checkpoint["dims"]
__UpperCAmelCase = original_checkpoint["model_state_dict"]
__UpperCAmelCase = state_dict["decoder.token_embedding.weight"]
remove_ignore_keys_(A_ )
rename_keys(A_ )
__UpperCAmelCase = True
__UpperCAmelCase = state_dict["decoder.layers.0.fc1.weight"].shape[0]
__UpperCAmelCase = WhisperConfig(
vocab_size=dimensions["n_vocab"] , encoder_ffn_dim=A_ , decoder_ffn_dim=A_ , num_mel_bins=dimensions["n_mels"] , d_model=dimensions["n_audio_state"] , max_target_positions=dimensions["n_text_ctx"] , encoder_layers=dimensions["n_audio_layer"] , encoder_attention_heads=dimensions["n_audio_head"] , decoder_layers=dimensions["n_text_layer"] , decoder_attention_heads=dimensions["n_text_state"] , max_source_positions=dimensions["n_audio_ctx"] , )
__UpperCAmelCase = WhisperForConditionalGeneration(A_ )
__UpperCAmelCase , __UpperCAmelCase = model.model.load_state_dict(A_ , strict=A_ )
if len(A_ ) > 0 and not set(A_ ) <= {
"encoder.embed_positions.weights",
"decoder.embed_positions.weights",
}:
raise ValueError(
"Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,"
F''' but all the following weights are missing {missing}''' )
if tie_embeds:
__UpperCAmelCase = make_linear_from_emb(model.model.decoder.embed_tokens )
else:
__UpperCAmelCase = proj_out_weights
model.save_pretrained(A_ )
if __name__ == "__main__":
a_ = argparse.ArgumentParser()
# # Required parameters
parser.add_argument("""--checkpoint_path""", type=str, help="""Patht to the downloaded checkpoints""")
parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
a_ = parser.parse_args()
convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
| 286 | 0 |
'''simple docstring'''
import numpy as np
from transformers import Pipeline
def lowercase__( __UpperCamelCase: Any ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Dict = np.max(__lowerCAmelCase ,axis=-1 ,keepdims=__lowerCAmelCase )
SCREAMING_SNAKE_CASE : Union[str, Any] = np.exp(outputs - maxes )
return shifted_exp / shifted_exp.sum(axis=-1 ,keepdims=__lowerCAmelCase )
class _a ( __lowerCamelCase ):
'''simple docstring'''
def UpperCamelCase_ ( self, **A ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : List[Any] = {}
if "second_text" in kwargs:
SCREAMING_SNAKE_CASE : Optional[Any] = kwargs['''second_text''']
return preprocess_kwargs, {}, {}
def UpperCamelCase_ ( self, A, A=None ):
'''simple docstring'''
return self.tokenizer(__lowercase, text_pair=__lowercase, return_tensors=self.framework )
def UpperCamelCase_ ( self, A ):
'''simple docstring'''
return self.model(**__lowercase )
def UpperCamelCase_ ( self, A ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : int = model_outputs.logits[0].numpy()
SCREAMING_SNAKE_CASE : Optional[Any] = softmax(__lowercase )
SCREAMING_SNAKE_CASE : Optional[int] = np.argmax(__lowercase )
SCREAMING_SNAKE_CASE : Tuple = self.model.config.idalabel[best_class]
SCREAMING_SNAKE_CASE : Any = probabilities[best_class].item()
SCREAMING_SNAKE_CASE : Optional[int] = logits.tolist()
return {"label": label, "score": score, "logits": logits}
| 28 |
def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase = " " ) -> list:
"""simple docstring"""
snake_case__ : str = []
snake_case__ : int = 0
for index, char in enumerate(__lowerCAmelCase ):
if char == separator:
split_words.append(string[last_index:index] )
snake_case__ : Dict = index + 1
elif index + 1 == len(__lowerCAmelCase ):
split_words.append(string[last_index : index + 1] )
return split_words
if __name__ == "__main__":
from doctest import testmod
testmod()
| 252 | 0 |
"""simple docstring"""
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 (
ConditionalDetrConfig,
ConditionalDetrForObjectDetection,
ConditionalDetrForSegmentation,
ConditionalDetrImageProcessor,
)
from transformers.utils import logging
logging.set_verbosity_info()
_lowerCAmelCase = logging.get_logger(__name__)
# here we list all keys to be renamed (original name on the left, our name on the right)
_lowerCAmelCase = []
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}.cross_attn.out_proj.weight''',
F'''decoder.layers.{i}.encoder_attn.out_proj.weight''',
)
)
rename_keys.append(
(
F'''transformer.decoder.layers.{i}.cross_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'''))
# q, k, v projections in self/cross-attention in decoder for conditional DETR
rename_keys.append(
(F'''transformer.decoder.layers.{i}.sa_qcontent_proj.weight''', F'''decoder.layers.{i}.sa_qcontent_proj.weight''')
)
rename_keys.append(
(F'''transformer.decoder.layers.{i}.sa_kcontent_proj.weight''', F'''decoder.layers.{i}.sa_kcontent_proj.weight''')
)
rename_keys.append(
(F'''transformer.decoder.layers.{i}.sa_qpos_proj.weight''', F'''decoder.layers.{i}.sa_qpos_proj.weight''')
)
rename_keys.append(
(F'''transformer.decoder.layers.{i}.sa_kpos_proj.weight''', F'''decoder.layers.{i}.sa_kpos_proj.weight''')
)
rename_keys.append((F'''transformer.decoder.layers.{i}.sa_v_proj.weight''', F'''decoder.layers.{i}.sa_v_proj.weight'''))
rename_keys.append(
(F'''transformer.decoder.layers.{i}.ca_qcontent_proj.weight''', F'''decoder.layers.{i}.ca_qcontent_proj.weight''')
)
# rename_keys.append((f"transformer.decoder.layers.{i}.ca_qpos_proj.weight", f"decoder.layers.{i}.ca_qpos_proj.weight"))
rename_keys.append(
(F'''transformer.decoder.layers.{i}.ca_kcontent_proj.weight''', F'''decoder.layers.{i}.ca_kcontent_proj.weight''')
)
rename_keys.append(
(F'''transformer.decoder.layers.{i}.ca_kpos_proj.weight''', F'''decoder.layers.{i}.ca_kpos_proj.weight''')
)
rename_keys.append((F'''transformer.decoder.layers.{i}.ca_v_proj.weight''', F'''decoder.layers.{i}.ca_v_proj.weight'''))
rename_keys.append(
(F'''transformer.decoder.layers.{i}.ca_qpos_sine_proj.weight''', F'''decoder.layers.{i}.ca_qpos_sine_proj.weight''')
)
rename_keys.append(
(F'''transformer.decoder.layers.{i}.sa_qcontent_proj.bias''', F'''decoder.layers.{i}.sa_qcontent_proj.bias''')
)
rename_keys.append(
(F'''transformer.decoder.layers.{i}.sa_kcontent_proj.bias''', F'''decoder.layers.{i}.sa_kcontent_proj.bias''')
)
rename_keys.append((F'''transformer.decoder.layers.{i}.sa_qpos_proj.bias''', F'''decoder.layers.{i}.sa_qpos_proj.bias'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.sa_kpos_proj.bias''', F'''decoder.layers.{i}.sa_kpos_proj.bias'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.sa_v_proj.bias''', F'''decoder.layers.{i}.sa_v_proj.bias'''))
rename_keys.append(
(F'''transformer.decoder.layers.{i}.ca_qcontent_proj.bias''', F'''decoder.layers.{i}.ca_qcontent_proj.bias''')
)
# rename_keys.append((f"transformer.decoder.layers.{i}.ca_qpos_proj.bias", f"decoder.layers.{i}.ca_qpos_proj.bias"))
rename_keys.append(
(F'''transformer.decoder.layers.{i}.ca_kcontent_proj.bias''', F'''decoder.layers.{i}.ca_kcontent_proj.bias''')
)
rename_keys.append((F'''transformer.decoder.layers.{i}.ca_kpos_proj.bias''', F'''decoder.layers.{i}.ca_kpos_proj.bias'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.ca_v_proj.bias''', F'''decoder.layers.{i}.ca_v_proj.bias'''))
rename_keys.append(
(F'''transformer.decoder.layers.{i}.ca_qpos_sine_proj.bias''', F'''decoder.layers.{i}.ca_qpos_sine_proj.bias''')
)
# convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads
# for conditional DETR, also convert reference point head and query scale MLP
rename_keys.extend(
[
("""input_proj.weight""", """input_projection.weight"""),
("""input_proj.bias""", """input_projection.bias"""),
("""query_embed.weight""", """query_position_embeddings.weight"""),
("""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"""),
("""transformer.decoder.ref_point_head.layers.0.weight""", """decoder.ref_point_head.layers.0.weight"""),
("""transformer.decoder.ref_point_head.layers.0.bias""", """decoder.ref_point_head.layers.0.bias"""),
("""transformer.decoder.ref_point_head.layers.1.weight""", """decoder.ref_point_head.layers.1.weight"""),
("""transformer.decoder.ref_point_head.layers.1.bias""", """decoder.ref_point_head.layers.1.bias"""),
("""transformer.decoder.query_scale.layers.0.weight""", """decoder.query_scale.layers.0.weight"""),
("""transformer.decoder.query_scale.layers.0.bias""", """decoder.query_scale.layers.0.bias"""),
("""transformer.decoder.query_scale.layers.1.weight""", """decoder.query_scale.layers.1.weight"""),
("""transformer.decoder.query_scale.layers.1.bias""", """decoder.query_scale.layers.1.bias"""),
("""transformer.decoder.layers.0.ca_qpos_proj.weight""", """decoder.layers.0.ca_qpos_proj.weight"""),
("""transformer.decoder.layers.0.ca_qpos_proj.bias""", """decoder.layers.0.ca_qpos_proj.bias"""),
]
)
def lowerCamelCase__ ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ):
'''simple docstring'''
_lowerCAmelCase : List[str] = state_dict.pop(_lowerCamelCase )
_lowerCAmelCase : Tuple = val
def lowerCamelCase__ ( _lowerCamelCase ):
'''simple docstring'''
_lowerCAmelCase : Tuple = OrderedDict()
for key, value in state_dict.items():
if "backbone.0.body" in key:
_lowerCAmelCase : Dict = key.replace('backbone.0.body' , 'backbone.conv_encoder.model' )
_lowerCAmelCase : Dict = value
else:
_lowerCAmelCase : Any = value
return new_state_dict
def lowerCamelCase__ ( _lowerCamelCase , _lowerCamelCase=False ):
'''simple docstring'''
_lowerCAmelCase : Optional[Any] = ''
if is_panoptic:
_lowerCAmelCase : Optional[Any] = 'conditional_detr.'
# 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)
_lowerCAmelCase : Optional[int] = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight""" )
_lowerCAmelCase : Tuple = 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
_lowerCAmelCase : Dict = in_proj_weight[:256, :]
_lowerCAmelCase : List[Any] = in_proj_bias[:256]
_lowerCAmelCase : Dict = in_proj_weight[256:512, :]
_lowerCAmelCase : Union[str, Any] = in_proj_bias[256:512]
_lowerCAmelCase : Any = in_proj_weight[-256:, :]
_lowerCAmelCase : Any = in_proj_bias[-256:]
def lowerCamelCase__ ( ):
'''simple docstring'''
_lowerCAmelCase : Any = 'http://images.cocodataset.org/val2017/000000039769.jpg'
_lowerCAmelCase : Union[str, Any] = Image.open(requests.get(_lowerCamelCase , stream=_lowerCamelCase ).raw )
return im
@torch.no_grad()
def lowerCamelCase__ ( _lowerCamelCase , _lowerCamelCase ):
'''simple docstring'''
_lowerCAmelCase : List[Any] = ConditionalDetrConfig()
# set backbone and dilation attributes
if "resnet101" in model_name:
_lowerCAmelCase : Dict = 'resnet101'
if "dc5" in model_name:
_lowerCAmelCase : List[Any] = True
_lowerCAmelCase : Dict = 'panoptic' in model_name
if is_panoptic:
_lowerCAmelCase : List[str] = 250
else:
_lowerCAmelCase : str = 91
_lowerCAmelCase : Any = 'huggingface/label-files'
_lowerCAmelCase : List[str] = 'coco-detection-id2label.json'
_lowerCAmelCase : int = json.load(open(hf_hub_download(_lowerCamelCase , _lowerCamelCase , repo_type='dataset' ) , 'r' ) )
_lowerCAmelCase : str = {int(_lowerCamelCase ): v for k, v in idalabel.items()}
_lowerCAmelCase : Union[str, Any] = idalabel
_lowerCAmelCase : Any = {v: k for k, v in idalabel.items()}
# load image processor
_lowerCAmelCase : Optional[int] = 'coco_panoptic' if is_panoptic else 'coco_detection'
_lowerCAmelCase : str = ConditionalDetrImageProcessor(format=_lowerCamelCase )
# prepare image
_lowerCAmelCase : List[str] = prepare_img()
_lowerCAmelCase : int = image_processor(images=_lowerCamelCase , return_tensors='pt' )
_lowerCAmelCase : Dict = encoding['pixel_values']
logger.info(f"""Converting model {model_name}...""" )
# load original model from torch hub
_lowerCAmelCase : Any = torch.hub.load('DeppMeng/ConditionalDETR' , _lowerCamelCase , pretrained=_lowerCamelCase ).eval()
_lowerCAmelCase : Union[str, Any] = conditional_detr.state_dict()
# rename keys
for src, dest in rename_keys:
if is_panoptic:
_lowerCAmelCase : Optional[Any] = 'conditional_detr.' + src
rename_key(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
_lowerCAmelCase : Union[str, Any] = rename_backbone_keys(_lowerCamelCase )
# query, key and value matrices need special treatment
read_in_q_k_v(_lowerCamelCase , is_panoptic=_lowerCamelCase )
# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
_lowerCAmelCase : Dict = 'conditional_detr.model.' if is_panoptic else 'model.'
for key in state_dict.copy().keys():
if is_panoptic:
if (
key.startswith('conditional_detr' )
and not key.startswith('class_labels_classifier' )
and not key.startswith('bbox_predictor' )
):
_lowerCAmelCase : List[Any] = state_dict.pop(_lowerCamelCase )
_lowerCAmelCase : Tuple = val
elif "class_labels_classifier" in key or "bbox_predictor" in key:
_lowerCAmelCase : Any = state_dict.pop(_lowerCamelCase )
_lowerCAmelCase : Dict = val
elif key.startswith('bbox_attention' ) or key.startswith('mask_head' ):
continue
else:
_lowerCAmelCase : str = state_dict.pop(_lowerCamelCase )
_lowerCAmelCase : List[str] = val
else:
if not key.startswith('class_labels_classifier' ) and not key.startswith('bbox_predictor' ):
_lowerCAmelCase : Dict = state_dict.pop(_lowerCamelCase )
_lowerCAmelCase : List[Any] = val
# finally, create HuggingFace model and load state dict
_lowerCAmelCase : str = ConditionalDetrForSegmentation(_lowerCamelCase ) if is_panoptic else ConditionalDetrForObjectDetection(_lowerCamelCase )
model.load_state_dict(_lowerCamelCase )
model.eval()
model.push_to_hub(repo_id=_lowerCamelCase , organization='DepuMeng' , commit_message='Add model' )
# verify our conversion
_lowerCAmelCase : List[Any] = conditional_detr(_lowerCamelCase )
_lowerCAmelCase : Dict = model(_lowerCamelCase )
assert torch.allclose(outputs.logits , original_outputs['pred_logits'] , atol=1e-4 )
assert torch.allclose(outputs.pred_boxes , original_outputs['pred_boxes'] , atol=1e-4 )
if is_panoptic:
assert torch.allclose(outputs.pred_masks , original_outputs['pred_masks'] , atol=1e-4 )
# Save model and image processor
logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" )
Path(_lowerCamelCase ).mkdir(exist_ok=_lowerCamelCase )
model.save_pretrained(_lowerCamelCase )
image_processor.save_pretrained(_lowerCamelCase )
if __name__ == "__main__":
_lowerCAmelCase = argparse.ArgumentParser()
parser.add_argument(
"""--model_name""",
default="""conditional_detr_resnet50""",
type=str,
help="""Name of the CONDITIONAL_DETR model 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."""
)
_lowerCAmelCase = parser.parse_args()
convert_conditional_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path)
| 16 |
"""simple docstring"""
import logging
import os
from .state import PartialState
class __UpperCamelCase ( logging.LoggerAdapter ):
@staticmethod
def __lowerCamelCase ( _A ):
'''simple docstring'''
_lowerCAmelCase : Optional[Any] = PartialState()
return not main_process_only or (main_process_only and state.is_main_process)
def __lowerCamelCase ( self ,_A ,_A ,*_A ,**_A ):
'''simple docstring'''
if PartialState._shared_state == {}:
raise RuntimeError(
'You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.' )
_lowerCAmelCase : Tuple = kwargs.pop('main_process_only' ,_A )
_lowerCAmelCase : Any = kwargs.pop('in_order' ,_A )
if self.isEnabledFor(_A ):
if self._should_log(_A ):
_lowerCAmelCase, _lowerCAmelCase : Optional[int] = self.process(_A ,_A )
self.logger.log(_A ,_A ,*_A ,**_A )
elif in_order:
_lowerCAmelCase : str = PartialState()
for i in range(state.num_processes ):
if i == state.process_index:
_lowerCAmelCase, _lowerCAmelCase : Optional[int] = self.process(_A ,_A )
self.logger.log(_A ,_A ,*_A ,**_A )
state.wait_for_everyone()
def lowerCamelCase__ ( _lowerCamelCase , _lowerCamelCase = None ):
'''simple docstring'''
if log_level is None:
_lowerCAmelCase : Union[str, Any] = os.environ.get('ACCELERATE_LOG_LEVEL' , _lowerCamelCase )
_lowerCAmelCase : int = logging.getLogger(_lowerCamelCase )
if log_level is not None:
logger.setLevel(log_level.upper() )
logger.root.setLevel(log_level.upper() )
return MultiProcessAdapter(_lowerCamelCase , {} )
| 16 | 1 |
'''simple docstring'''
# Lint as: python3
import dataclasses
import re
from dataclasses import dataclass
from functools import total_ordering
from typing import Optional, Union
UpperCAmelCase_ : Dict = re.compile(r'^(?P<major>\d+)' r'\.(?P<minor>\d+)' r'\.(?P<patch>\d+)$')
@total_ordering
@dataclass
class lowercase__ :
'''simple docstring'''
A_ : str
A_ : Optional[str] = None
A_ : Optional[Union[str, int]] = None
A_ : Optional[Union[str, int]] = None
A_ : Optional[Union[str, int]] = None
def UpperCAmelCase_ ( self ):
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = _str_to_version_tuple(self.version_str )
def __repr__( self ):
return f"""{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}"""
@property
def UpperCAmelCase_ ( self ):
return self.major, self.minor, self.patch
def UpperCAmelCase_ ( self , __snake_case ):
if isinstance(__snake_case , __snake_case ):
return Version(__snake_case )
elif isinstance(__snake_case , __snake_case ):
return other
raise TypeError(f"""{other} (type {type(__snake_case )}) cannot be compared to version.""" )
def __eq__( self , __snake_case ):
try:
_SCREAMING_SNAKE_CASE : Any = self._validate_operand(__snake_case )
except (TypeError, ValueError):
return False
else:
return self.tuple == other.tuple
def __lt__( self , __snake_case ):
_SCREAMING_SNAKE_CASE : Tuple = self._validate_operand(__snake_case )
return self.tuple < other.tuple
def __hash__( self ):
return hash(_version_tuple_to_str(self.tuple ) )
@classmethod
def UpperCAmelCase_ ( cls , __snake_case ):
_SCREAMING_SNAKE_CASE : Any = {f.name for f in dataclasses.fields(cls )}
return cls(**{k: v for k, v in dic.items() if k in field_names} )
def UpperCAmelCase_ ( self ):
return self.version_str
def snake_case_ ( SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE : Optional[int] = _VERSION_REG.match(SCREAMING_SNAKE_CASE__ )
if not res:
raise ValueError(f"""Invalid version '{version_str}'. Format should be x.y.z with {{x,y,z}} being digits.""" )
return tuple(int(SCREAMING_SNAKE_CASE__ ) for v in [res.group("""major""" ), res.group("""minor""" ), res.group("""patch""" )] )
def snake_case_ ( SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
return ".".join(str(SCREAMING_SNAKE_CASE__ ) for v in version_tuple )
| 533 |
'''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
UpperCAmelCase_ : List[Any] = '.'
if __name__ == "__main__":
UpperCAmelCase_ : Any = os.path.join(REPO_PATH, 'utils/documentation_tests.txt')
UpperCAmelCase_ : Dict = []
UpperCAmelCase_ : Union[str, Any] = []
with open(doctest_file_path) as fp:
for line in fp:
UpperCAmelCase_ : int = line.strip()
UpperCAmelCase_ : str = 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:
UpperCAmelCase_ : int = '\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.')
| 533 | 1 |
import unittest
from knapsack import knapsack as k
class UpperCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
def _UpperCAmelCase ( self : Union[str, Any] ) -> Optional[int]:
SCREAMING_SNAKE_CASE = 0
SCREAMING_SNAKE_CASE = [0]
SCREAMING_SNAKE_CASE = [0]
SCREAMING_SNAKE_CASE = len(a )
self.assertEqual(k.knapsack(a , a , a , a ) , 0 )
SCREAMING_SNAKE_CASE = [60]
SCREAMING_SNAKE_CASE = [10]
SCREAMING_SNAKE_CASE = len(a )
self.assertEqual(k.knapsack(a , a , a , a ) , 0 )
def _UpperCAmelCase ( self : List[str] ) -> List[Any]:
SCREAMING_SNAKE_CASE = 3
SCREAMING_SNAKE_CASE = [1, 2, 3]
SCREAMING_SNAKE_CASE = [3, 2, 1]
SCREAMING_SNAKE_CASE = len(a )
self.assertEqual(k.knapsack(a , a , a , a ) , 5 )
def _UpperCAmelCase ( self : str ) -> str:
SCREAMING_SNAKE_CASE = 50
SCREAMING_SNAKE_CASE = [60, 100, 120]
SCREAMING_SNAKE_CASE = [10, 20, 30]
SCREAMING_SNAKE_CASE = len(a )
self.assertEqual(k.knapsack(a , a , a , a ) , 220 )
if __name__ == "__main__":
unittest.main()
| 450 |
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
if is_torch_available():
from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
@require_torch
@require_sentencepiece
@require_tokenizers
class UpperCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
@slow
def _UpperCAmelCase ( self : Optional[int] ) -> Tuple:
SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained("""google/mt5-small""" , return_dict=a ).to(a )
SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""google/mt5-small""" )
SCREAMING_SNAKE_CASE = tokenizer("""Hello there""" , return_tensors="""pt""" ).input_ids
SCREAMING_SNAKE_CASE = tokenizer("""Hi I am""" , return_tensors="""pt""" ).input_ids
SCREAMING_SNAKE_CASE = model(input_ids.to(a ) , labels=labels.to(a ) ).loss
SCREAMING_SNAKE_CASE = -(labels.shape[-1] * loss.item())
SCREAMING_SNAKE_CASE = -84.9127
self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
| 450 | 1 |
'''simple docstring'''
from __future__ import annotations
def __UpperCamelCase ( lowercase_ : str , lowercase_ : list[str] | None = None , lowercase_ : dict[str, float] | None = None , lowercase_ : bool = False , ):
"""simple docstring"""
a_ = cipher_alphabet or [chr(lowercase_ ) for i in range(97 , 123 )]
# If the argument is None or the user provided an empty dictionary
if not frequencies_dict:
# Frequencies of letters in the english language (how much they show up)
a_ = {
'a': 0.0_8497,
'b': 0.0_1492,
'c': 0.0_2202,
'd': 0.0_4253,
'e': 0.1_1162,
'f': 0.0_2228,
'g': 0.0_2015,
'h': 0.0_6094,
'i': 0.0_7546,
'j': 0.0_0153,
'k': 0.0_1292,
'l': 0.0_4025,
'm': 0.0_2406,
'n': 0.0_6749,
'o': 0.0_7507,
'p': 0.0_1929,
'q': 0.0_0095,
'r': 0.0_7587,
's': 0.0_6327,
't': 0.0_9356,
'u': 0.0_2758,
'v': 0.0_0978,
'w': 0.0_2560,
'x': 0.0_0150,
'y': 0.0_1994,
'z': 0.0_0077,
}
else:
# Custom frequencies dictionary
a_ = frequencies_dict
if not case_sensitive:
a_ = ciphertext.lower()
# Chi squared statistic values
a_ = {}
# cycle through all of the shifts
for shift in range(len(lowercase_ ) ):
a_ = ''
# decrypt the message with the shift
for letter in ciphertext:
try:
# Try to index the letter in the alphabet
a_ = (alphabet_letters.index(letter.lower() ) - shift) % len(
lowercase_ )
decrypted_with_shift += (
alphabet_letters[new_key].upper()
if case_sensitive and letter.isupper()
else alphabet_letters[new_key]
)
except ValueError:
# Append the character if it isn't in the alphabet
decrypted_with_shift += letter
a_ = 0.0
# Loop through each letter in the decoded message with the shift
for letter in decrypted_with_shift:
if case_sensitive:
a_ = letter.lower()
if letter in frequencies:
# Get the amount of times the letter occurs in the message
a_ = decrypted_with_shift.lower().count(lowercase_ )
# Get the excepcted amount of times the letter should appear based
# on letter frequencies
a_ = frequencies[letter] * occurrences
# Complete the chi squared statistic formula
a_ = ((occurrences - expected) ** 2) / expected
# Add the margin of error to the total chi squared statistic
chi_squared_statistic += chi_letter_value
else:
if letter.lower() in frequencies:
# Get the amount of times the letter occurs in the message
a_ = decrypted_with_shift.count(lowercase_ )
# Get the excepcted amount of times the letter should appear based
# on letter frequencies
a_ = frequencies[letter] * occurrences
# Complete the chi squared statistic formula
a_ = ((occurrences - expected) ** 2) / expected
# Add the margin of error to the total chi squared statistic
chi_squared_statistic += chi_letter_value
# Add the data to the chi_squared_statistic_values dictionary
a_ = (
chi_squared_statistic,
decrypted_with_shift,
)
# Get the most likely cipher by finding the cipher with the smallest chi squared
# statistic
def chi_squared_statistic_values_sorting_key(lowercase_ : int ) -> tuple[float, str]:
return chi_squared_statistic_values[key]
a_ = min(
lowercase_ , key=lowercase_ , )
# Get all the data from the most likely cipher (key, decoded message)
(
(
a_
) , (
a_
) ,
) = chi_squared_statistic_values[most_likely_cipher]
# Return the data on the most likely shift
return (
most_likely_cipher,
most_likely_cipher_chi_squared_value,
decoded_most_likely_cipher,
)
| 536 |
'''simple docstring'''
import os
import sys
import unittest
__lowerCAmelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))
import get_test_info # noqa: E402
from get_test_info import ( # noqa: E402
get_model_to_test_mapping,
get_model_to_tester_mapping,
get_test_to_tester_mapping,
)
__lowerCAmelCase = os.path.join("tests", "models", "bert", "test_modeling_bert.py")
__lowerCAmelCase = os.path.join("tests", "models", "blip", "test_modeling_blip.py")
class __SCREAMING_SNAKE_CASE (unittest.TestCase ):
"""simple docstring"""
def _a ( self ):
"""simple docstring"""
a_ = get_test_to_tester_mapping(UpperCamelCase__ )
a_ = get_test_to_tester_mapping(UpperCamelCase__ )
a_ = {'BertModelTest': 'BertModelTester'}
a_ = {
'BlipModelTest': 'BlipModelTester',
'BlipTextImageModelTest': 'BlipTextImageModelsModelTester',
'BlipTextModelTest': 'BlipTextModelTester',
'BlipTextRetrievalModelTest': 'BlipTextRetrievalModelTester',
'BlipVQAModelTest': 'BlipVQAModelTester',
'BlipVisionModelTest': 'BlipVisionModelTester',
}
self.assertEqual(get_test_info.to_json(UpperCamelCase__ ) , UpperCamelCase__ )
self.assertEqual(get_test_info.to_json(UpperCamelCase__ ) , UpperCamelCase__ )
def _a ( self ):
"""simple docstring"""
a_ = get_model_to_test_mapping(UpperCamelCase__ )
a_ = get_model_to_test_mapping(UpperCamelCase__ )
a_ = {
'BertForMaskedLM': ['BertModelTest'],
'BertForMultipleChoice': ['BertModelTest'],
'BertForNextSentencePrediction': ['BertModelTest'],
'BertForPreTraining': ['BertModelTest'],
'BertForQuestionAnswering': ['BertModelTest'],
'BertForSequenceClassification': ['BertModelTest'],
'BertForTokenClassification': ['BertModelTest'],
'BertLMHeadModel': ['BertModelTest'],
'BertModel': ['BertModelTest'],
}
a_ = {
'BlipForConditionalGeneration': ['BlipTextImageModelTest'],
'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTest'],
'BlipForQuestionAnswering': ['BlipVQAModelTest'],
'BlipModel': ['BlipModelTest'],
'BlipTextModel': ['BlipTextModelTest'],
'BlipVisionModel': ['BlipVisionModelTest'],
}
self.assertEqual(get_test_info.to_json(UpperCamelCase__ ) , UpperCamelCase__ )
self.assertEqual(get_test_info.to_json(UpperCamelCase__ ) , UpperCamelCase__ )
def _a ( self ):
"""simple docstring"""
a_ = get_model_to_tester_mapping(UpperCamelCase__ )
a_ = get_model_to_tester_mapping(UpperCamelCase__ )
a_ = {
'BertForMaskedLM': ['BertModelTester'],
'BertForMultipleChoice': ['BertModelTester'],
'BertForNextSentencePrediction': ['BertModelTester'],
'BertForPreTraining': ['BertModelTester'],
'BertForQuestionAnswering': ['BertModelTester'],
'BertForSequenceClassification': ['BertModelTester'],
'BertForTokenClassification': ['BertModelTester'],
'BertLMHeadModel': ['BertModelTester'],
'BertModel': ['BertModelTester'],
}
a_ = {
'BlipForConditionalGeneration': ['BlipTextImageModelsModelTester'],
'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTester'],
'BlipForQuestionAnswering': ['BlipVQAModelTester'],
'BlipModel': ['BlipModelTester'],
'BlipTextModel': ['BlipTextModelTester'],
'BlipVisionModel': ['BlipVisionModelTester'],
}
self.assertEqual(get_test_info.to_json(UpperCamelCase__ ) , UpperCamelCase__ )
self.assertEqual(get_test_info.to_json(UpperCamelCase__ ) , UpperCamelCase__ )
| 536 | 1 |
"""simple docstring"""
from manim import *
class _UpperCamelCase ( UpperCamelCase__ ):
"""simple docstring"""
def _UpperCAmelCase ( self : List[Any] ) -> Tuple:
'''simple docstring'''
__magic_name__ : Any = Rectangle(height=0.5 , width=0.5 )
__magic_name__ : str = Rectangle(height=0.25 , width=0.25 )
__magic_name__ : Tuple = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 )
__magic_name__ : Union[str, Any] = [mem.copy() for i in range(6 )]
__magic_name__ : Tuple = [mem.copy() for i in range(6 )]
__magic_name__ : Dict = VGroup(*_a ).arrange(_a , buff=0 )
__magic_name__ : List[Any] = VGroup(*_a ).arrange(_a , buff=0 )
__magic_name__ : Optional[int] = VGroup(_a , _a ).arrange(_a , buff=0 )
__magic_name__ : Dict = Text('''CPU''' , font_size=24 )
__magic_name__ : int = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a )
cpu.move_to([-2.5, -0.5, 0] )
self.add(_a )
__magic_name__ : List[Any] = [mem.copy() for i in range(4 )]
__magic_name__ : List[Any] = VGroup(*_a ).arrange(_a , buff=0 )
__magic_name__ : Optional[Any] = Text('''GPU''' , font_size=24 )
__magic_name__ : int = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a )
gpu.move_to([-1, -1, 0] )
self.add(_a )
__magic_name__ : List[Any] = [mem.copy() for i in range(6 )]
__magic_name__ : Optional[int] = VGroup(*_a ).arrange(_a , buff=0 )
__magic_name__ : Tuple = Text('''Model''' , font_size=24 )
__magic_name__ : int = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a )
model.move_to([3, -1.0, 0] )
self.add(_a )
__magic_name__ : Optional[int] = []
__magic_name__ : Tuple = []
__magic_name__ : List[Any] = []
for i, rect in enumerate(_a ):
rect.set_stroke(_a )
__magic_name__ : Dict = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(_a , opacity=0.7 )
if i == 0:
cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_a )
cpu_target.set_x(cpu_target.get_x() + 0.1 )
elif i == 3:
cpu_target.next_to(model_cpu_arr[0] , direction=_a , buff=0.0 )
else:
cpu_target.next_to(model_cpu_arr[i - 1] , direction=_a , buff=0.0 )
self.add(_a )
model_cpu_arr.append(_a )
self.add(*_a , *_a , *_a )
__magic_name__ : List[Any] = [mem.copy() for i in range(6 )]
__magic_name__ : Any = VGroup(*_a ).arrange(_a , buff=0 )
__magic_name__ : Any = Text('''Loaded Checkpoint''' , font_size=24 )
__magic_name__ : str = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a )
checkpoint.move_to([3, 0.5, 0] )
self.add(_a )
__magic_name__ : int = []
__magic_name__ : List[str] = []
for i, rect in enumerate(_a ):
__magic_name__ : Optional[Any] = fill.copy().set_fill(_a , opacity=0.7 )
target.move_to(_a )
ckpt_arr.append(_a )
__magic_name__ : Union[str, Any] = target.copy()
if i < 5:
cpu_target.move_to(cpu_left_col_base[i + 1] )
else:
cpu_target.move_to(cpu_right_col_base[i - 5] )
ckpt_cpu_arr.append(_a )
self.add(*_a , *_a )
__magic_name__ : List[Any] = Square(side_length=2.2 )
key.move_to([-5, 2, 0] )
__magic_name__ : Optional[Any] = MarkupText(
f"""<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model""" , font_size=18 , )
key_text.move_to([-5, 2.4, 0] )
self.add(_a , _a )
__magic_name__ : Optional[Any] = MarkupText(
f"""<span fgcolor=\'{BLUE}\'>●</span> Checkpoint""" , font_size=18 , )
blue_text.next_to(_a , DOWN * 2.4 , aligned_edge=key_text.get_left() )
self.add(_a )
__magic_name__ : Optional[int] = MarkupText(
f"""Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.""" , font_size=24 , )
step_a.move_to([2, 2, 0] )
__magic_name__ : List[Any] = [meta_mem.copy() for i in range(6 )]
__magic_name__ : List[str] = [meta_mem.copy() for i in range(6 )]
__magic_name__ : Union[str, Any] = VGroup(*_a ).arrange(_a , buff=0 )
__magic_name__ : Tuple = VGroup(*_a ).arrange(_a , buff=0 )
__magic_name__ : Any = VGroup(_a , _a ).arrange(_a , buff=0 )
__magic_name__ : Tuple = Text('''Disk''' , font_size=24 )
__magic_name__ : int = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a )
disk.move_to([-4.0, -1.25, 0] )
self.play(Write(_a , run_time=3 ) , Write(_a , run_time=1 ) , Create(_a , run_time=1 ) )
__magic_name__ : Optional[int] = []
for i, rect in enumerate(_a ):
__magic_name__ : Optional[int] = rect.copy()
target.generate_target()
target.target.move_to(disk_left_col_base[i] ).scale(0.5 )
animations.append(MoveToTarget(_a , run_time=1.5 ) )
self.play(*_a )
self.play(FadeOut(_a ) )
__magic_name__ : List[Any] = MarkupText(f"""Then, the checkpoint is removed from memory\nthrough garbage collection.""" , font_size=24 )
step_a.move_to([2, 2, 0] )
self.play(Write(_a , run_time=3 ) )
self.play(
FadeOut(_a , _a , *_a , *_a ) , )
self.wait()
| 710 |
"""simple docstring"""
def UpperCamelCase_ ( lowerCamelCase : float ) -> float:
"""simple docstring"""
return 10 - x * x
def UpperCamelCase_ ( lowerCamelCase : float , lowerCamelCase : float ) -> float:
"""simple docstring"""
if equation(lowerCamelCase ) * equation(lowerCamelCase ) >= 0:
raise ValueError('''Wrong space!''' )
__magic_name__ : int = a
while (b - a) >= 0.0_1:
# Find middle point
__magic_name__ : str = (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:
__magic_name__ : Union[str, Any] = c
else:
__magic_name__ : List[str] = c
return c
if __name__ == "__main__":
import doctest
doctest.testmod()
print(bisection(-2, 5))
print(bisection(0, 6))
| 147 | 0 |
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block
@dataclass
class UpperCamelCase__ (lowerCAmelCase__ ):
'''simple docstring'''
lowerCamelCase_ : torch.FloatTensor
class UpperCamelCase__ (lowerCAmelCase__ , lowerCAmelCase__ ):
'''simple docstring'''
@register_to_config
def __init__( self , UpperCamelCase__ = 6_5536 , UpperCamelCase__ = None , UpperCamelCase__ = 2 , UpperCamelCase__ = 2 , UpperCamelCase__ = 0 , UpperCamelCase__ = "fourier" , UpperCamelCase__ = True , UpperCamelCase__ = False , UpperCamelCase__ = 0.0 , UpperCamelCase__ = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , UpperCamelCase__ = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , UpperCamelCase__ = "UNetMidBlock1D" , UpperCamelCase__ = None , UpperCamelCase__ = (32, 32, 64) , UpperCamelCase__ = None , UpperCamelCase__ = 8 , UpperCamelCase__ = 1 , UpperCamelCase__ = False , ) -> str:
super().__init__()
lowerCamelCase : Dict = sample_size
# time
if time_embedding_type == "fourier":
lowerCamelCase : Optional[int] = GaussianFourierProjection(
embedding_size=8 , set_W_to_weight=UpperCamelCase__ , log=UpperCamelCase__ , flip_sin_to_cos=UpperCamelCase__ )
lowerCamelCase : Union[str, Any] = 2 * block_out_channels[0]
elif time_embedding_type == "positional":
lowerCamelCase : List[Any] = Timesteps(
block_out_channels[0] , flip_sin_to_cos=UpperCamelCase__ , downscale_freq_shift=UpperCamelCase__ )
lowerCamelCase : str = block_out_channels[0]
if use_timestep_embedding:
lowerCamelCase : Optional[int] = block_out_channels[0] * 4
lowerCamelCase : Optional[int] = TimestepEmbedding(
in_channels=UpperCamelCase__ , time_embed_dim=UpperCamelCase__ , act_fn=UpperCamelCase__ , out_dim=block_out_channels[0] , )
lowerCamelCase : Optional[int] = nn.ModuleList([] )
lowerCamelCase : Union[str, Any] = None
lowerCamelCase : Optional[Any] = nn.ModuleList([] )
lowerCamelCase : str = None
# down
lowerCamelCase : List[Any] = in_channels
for i, down_block_type in enumerate(UpperCamelCase__ ):
lowerCamelCase : List[Any] = output_channel
lowerCamelCase : Any = block_out_channels[i]
if i == 0:
input_channel += extra_in_channels
lowerCamelCase : Optional[Any] = i == len(UpperCamelCase__ ) - 1
lowerCamelCase : Dict = get_down_block(
UpperCamelCase__ , num_layers=UpperCamelCase__ , in_channels=UpperCamelCase__ , out_channels=UpperCamelCase__ , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , )
self.down_blocks.append(UpperCamelCase__ )
# mid
lowerCamelCase : Union[str, Any] = get_mid_block(
UpperCamelCase__ , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=UpperCamelCase__ , add_downsample=UpperCamelCase__ , )
# up
lowerCamelCase : Union[str, Any] = list(reversed(UpperCamelCase__ ) )
lowerCamelCase : Tuple = reversed_block_out_channels[0]
if out_block_type is None:
lowerCamelCase : Optional[int] = out_channels
else:
lowerCamelCase : int = block_out_channels[0]
for i, up_block_type in enumerate(UpperCamelCase__ ):
lowerCamelCase : str = output_channel
lowerCamelCase : List[Any] = (
reversed_block_out_channels[i + 1] if i < len(UpperCamelCase__ ) - 1 else final_upsample_channels
)
lowerCamelCase : Optional[int] = i == len(UpperCamelCase__ ) - 1
lowerCamelCase : List[str] = get_up_block(
UpperCamelCase__ , num_layers=UpperCamelCase__ , in_channels=UpperCamelCase__ , out_channels=UpperCamelCase__ , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , )
self.up_blocks.append(UpperCamelCase__ )
lowerCamelCase : Dict = output_channel
# out
lowerCamelCase : List[Any] = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 )
lowerCamelCase : Any = get_out_block(
out_block_type=UpperCamelCase__ , num_groups_out=UpperCamelCase__ , embed_dim=block_out_channels[0] , out_channels=UpperCamelCase__ , act_fn=UpperCamelCase__ , fc_dim=block_out_channels[-1] // 4 , )
def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = True , ) -> Union[UNetaDOutput, Tuple]:
lowerCamelCase : str = timestep
if not torch.is_tensor(UpperCamelCase__ ):
lowerCamelCase : Optional[int] = torch.tensor([timesteps] , dtype=torch.long , device=sample.device )
elif torch.is_tensor(UpperCamelCase__ ) and len(timesteps.shape ) == 0:
lowerCamelCase : Dict = timesteps[None].to(sample.device )
lowerCamelCase : str = self.time_proj(UpperCamelCase__ )
if self.config.use_timestep_embedding:
lowerCamelCase : Union[str, Any] = self.time_mlp(UpperCamelCase__ )
else:
lowerCamelCase : Optional[int] = timestep_embed[..., None]
lowerCamelCase : str = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype )
lowerCamelCase : Dict = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) )
# 2. down
lowerCamelCase : str = ()
for downsample_block in self.down_blocks:
lowerCamelCase , lowerCamelCase : Union[str, Any] = downsample_block(hidden_states=UpperCamelCase__ , temb=UpperCamelCase__ )
down_block_res_samples += res_samples
# 3. mid
if self.mid_block:
lowerCamelCase : Any = self.mid_block(UpperCamelCase__ , UpperCamelCase__ )
# 4. up
for i, upsample_block in enumerate(self.up_blocks ):
lowerCamelCase : Dict = down_block_res_samples[-1:]
lowerCamelCase : str = down_block_res_samples[:-1]
lowerCamelCase : Union[str, Any] = upsample_block(UpperCamelCase__ , res_hidden_states_tuple=UpperCamelCase__ , temb=UpperCamelCase__ )
# 5. post-process
if self.out_block:
lowerCamelCase : Any = self.out_block(UpperCamelCase__ , UpperCamelCase__ )
if not return_dict:
return (sample,)
return UNetaDOutput(sample=UpperCamelCase__ )
| 311 |
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__ :
'''simple docstring'''
lowerCamelCase_ : List[Any] = BlenderbotSmallConfig
lowerCamelCase_ : int = {}
lowerCamelCase_ : Optional[int] = """gelu"""
def __init__( self , UpperCamelCase__ , UpperCamelCase__=13 , UpperCamelCase__=7 , UpperCamelCase__=True , UpperCamelCase__=False , UpperCamelCase__=99 , UpperCamelCase__=32 , UpperCamelCase__=2 , UpperCamelCase__=4 , UpperCamelCase__=37 , UpperCamelCase__=0.1 , UpperCamelCase__=0.1 , UpperCamelCase__=20 , UpperCamelCase__=2 , UpperCamelCase__=1 , UpperCamelCase__=0 , ) -> List[Any]:
lowerCamelCase : Any = parent
lowerCamelCase : Any = batch_size
lowerCamelCase : Any = seq_length
lowerCamelCase : int = is_training
lowerCamelCase : Tuple = use_labels
lowerCamelCase : List[Any] = vocab_size
lowerCamelCase : Optional[int] = hidden_size
lowerCamelCase : Tuple = num_hidden_layers
lowerCamelCase : Dict = num_attention_heads
lowerCamelCase : Union[str, Any] = intermediate_size
lowerCamelCase : Optional[Any] = hidden_dropout_prob
lowerCamelCase : int = attention_probs_dropout_prob
lowerCamelCase : Optional[Any] = max_position_embeddings
lowerCamelCase : Optional[Any] = eos_token_id
lowerCamelCase : List[Any] = pad_token_id
lowerCamelCase : int = bos_token_id
def _lowercase ( self ) -> int:
lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size )
lowerCamelCase : Tuple = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 )
lowerCamelCase : Tuple = tf.concat([input_ids, eos_tensor] , axis=1 )
lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
lowerCamelCase : Dict = 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 , )
lowerCamelCase : Optional[int] = prepare_blenderbot_small_inputs_dict(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
return config, inputs_dict
def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ ) -> str:
lowerCamelCase : Dict = TFBlenderbotSmallModel(config=UpperCamelCase__ ).get_decoder()
lowerCamelCase : str = inputs_dict["input_ids"]
lowerCamelCase : List[str] = input_ids[:1, :]
lowerCamelCase : str = inputs_dict["attention_mask"][:1, :]
lowerCamelCase : str = inputs_dict["head_mask"]
lowerCamelCase : Tuple = 1
# first forward pass
lowerCamelCase : List[str] = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , head_mask=UpperCamelCase__ , use_cache=UpperCamelCase__ )
lowerCamelCase , lowerCamelCase : str = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
lowerCamelCase : Union[str, Any] = ids_tensor((self.batch_size, 3) , config.vocab_size )
lowerCamelCase : str = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta )
# append to next input_ids and
lowerCamelCase : Dict = tf.concat([input_ids, next_tokens] , axis=-1 )
lowerCamelCase : Dict = tf.concat([attention_mask, next_attn_mask] , axis=-1 )
lowerCamelCase : Optional[int] = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ )[0]
lowerCamelCase : Dict = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , past_key_values=UpperCamelCase__ )[0]
self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] )
# select random slice
lowerCamelCase : str = int(ids_tensor((1,) , output_from_past.shape[-1] ) )
lowerCamelCase : int = output_from_no_past[:, -3:, random_slice_idx]
lowerCamelCase : Any = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(UpperCamelCase__ , UpperCamelCase__ , rtol=1e-3 )
def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=None ,_SCREAMING_SNAKE_CASE=None ,_SCREAMING_SNAKE_CASE=None ,_SCREAMING_SNAKE_CASE=None ,_SCREAMING_SNAKE_CASE=None ,) -> Optional[int]:
if attention_mask is None:
lowerCamelCase : Dict = tf.cast(tf.math.not_equal(_SCREAMING_SNAKE_CASE ,config.pad_token_id ) ,tf.inta )
if decoder_attention_mask is None:
lowerCamelCase : Tuple = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ),
] ,axis=-1 ,)
if head_mask is None:
lowerCamelCase : Dict = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
lowerCamelCase : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
lowerCamelCase : Any = 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__ (lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ):
'''simple docstring'''
lowerCamelCase_ : str = (
(TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else ()
)
lowerCamelCase_ : List[Any] = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else ()
lowerCamelCase_ : int = (
{
"""conversational""": TFBlenderbotSmallForConditionalGeneration,
"""feature-extraction""": TFBlenderbotSmallModel,
"""summarization""": TFBlenderbotSmallForConditionalGeneration,
"""text2text-generation""": TFBlenderbotSmallForConditionalGeneration,
"""translation""": TFBlenderbotSmallForConditionalGeneration,
}
if is_tf_available()
else {}
)
lowerCamelCase_ : Union[str, Any] = True
lowerCamelCase_ : List[Any] = False
lowerCamelCase_ : str = False
def _lowercase ( self ) -> Dict:
lowerCamelCase : str = TFBlenderbotSmallModelTester(self )
lowerCamelCase : Any = ConfigTester(self , config_class=UpperCamelCase__ )
def _lowercase ( self ) -> Dict:
self.config_tester.run_common_tests()
def _lowercase ( self ) -> Tuple:
lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*UpperCamelCase__ )
@require_tokenizers
@require_tf
class UpperCamelCase__ (unittest.TestCase ):
'''simple docstring'''
lowerCamelCase_ : int = [
"""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?"""
]
lowerCamelCase_ : Dict = """facebook/blenderbot_small-90M"""
@cached_property
def _lowercase ( self ) -> Optional[int]:
# use "old" tokenizer here because of bug when downloading new tokenizer
return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" )
@cached_property
def _lowercase ( self ) -> Optional[Any]:
lowerCamelCase : str = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name )
return model
@slow
def _lowercase ( self ) -> Tuple:
lowerCamelCase : int = self.tokenizer(self.src_text , return_tensors="tf" )
lowerCamelCase : Tuple = self.model.generate(
model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=UpperCamelCase__ , )
lowerCamelCase : str = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=UpperCamelCase__ )[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.",
)
| 311 | 1 |
'''simple docstring'''
from binascii import hexlify
from hashlib import shaaaa
from os import urandom
# RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for
# Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526
A_ : Tuple = {
# 1536-bit
5: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
+ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
+ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
+ "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 2048-bit
14: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
+ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
+ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
+ "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
+ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
+ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
+ "15728E5A8AACAA68FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 3072-bit
15: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
+ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
+ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
+ "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
+ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
+ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
+ "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
+ "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
+ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
+ "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
+ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
+ "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 4096-bit
16: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
+ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
+ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
+ "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
+ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
+ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
+ "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
+ "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
+ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
+ "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
+ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
+ "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7"
+ "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"
+ "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6"
+ "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"
+ "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9"
+ "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199"
+ "FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 6144-bit
17: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
+ "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
+ "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
+ "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
+ "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8"
+ "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C"
+ "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
+ "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D"
+ "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D"
+ "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226"
+ "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
+ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC"
+ "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26"
+ "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB"
+ "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2"
+ "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127"
+ "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
+ "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406"
+ "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918"
+ "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151"
+ "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03"
+ "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F"
+ "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
+ "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B"
+ "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632"
+ "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E"
+ "6DCC4024FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 8192-bit
18: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
+ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
+ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
+ "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
+ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
+ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
+ "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
+ "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
+ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
+ "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
+ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
+ "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7"
+ "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"
+ "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6"
+ "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"
+ "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9"
+ "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
+ "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD"
+ "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831"
+ "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
+ "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF"
+ "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6"
+ "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3"
+ "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
+ "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328"
+ "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C"
+ "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE"
+ "12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4"
+ "38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300"
+ "741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568"
+ "3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9"
+ "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B"
+ "4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A"
+ "062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36"
+ "4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1"
+ "B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92"
+ "4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47"
+ "9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71"
+ "60C980DD98EDD3DFFFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
}
class __snake_case :
'''simple docstring'''
def __init__( self , __SCREAMING_SNAKE_CASE = 1_4 ):
if group not in primes:
raise ValueError("""Unsupported Group""" )
snake_case__ : Any = primes[group]["prime"]
snake_case__ : str = primes[group]["generator"]
snake_case__ : List[str] = int(hexlify(urandom(3_2 ) ) , base=1_6 )
def __UpperCamelCase ( self ):
return hex(self.__private_key )[2:]
def __UpperCamelCase ( self ):
snake_case__ : Dict = pow(self.generator , self.__private_key , self.prime )
return hex(__lowerCamelCase )[2:]
def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ):
# check if the other public key is valid based on NIST SP800-56
return (
2 <= key <= self.prime - 2
and pow(__lowerCamelCase , (self.prime - 1) // 2 , self.prime ) == 1
)
def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ):
snake_case__ : List[str] = int(__lowerCamelCase , base=1_6 )
if not self.is_valid_public_key(__lowerCamelCase ):
raise ValueError("""Invalid public key""" )
snake_case__ : str = pow(__lowerCamelCase , self.__private_key , self.prime )
return shaaaa(str(__lowerCamelCase ).encode() ).hexdigest()
@staticmethod
def __UpperCamelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
# check if the other public key is valid based on NIST SP800-56
return (
2 <= remote_public_key_str <= prime - 2
and pow(__lowerCamelCase , (prime - 1) // 2 , __lowerCamelCase ) == 1
)
@staticmethod
def __UpperCamelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 1_4 ):
snake_case__ : Any = int(__lowerCamelCase , base=1_6 )
snake_case__ : Tuple = int(__lowerCamelCase , base=1_6 )
snake_case__ : Optional[Any] = primes[group]["prime"]
if not DiffieHellman.is_valid_public_key_static(__lowerCamelCase , __lowerCamelCase ):
raise ValueError("""Invalid public key""" )
snake_case__ : Dict = pow(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
return shaaaa(str(__lowerCamelCase ).encode() ).hexdigest()
if __name__ == "__main__":
import doctest
doctest.testmod()
| 717 |
'''simple docstring'''
import inspect
import unittest
from transformers import ViTConfig
from transformers.testing_utils import (
require_accelerate,
require_torch,
require_torch_gpu,
require_vision,
slow,
torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class __snake_case :
'''simple docstring'''
def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1_3 , __SCREAMING_SNAKE_CASE=3_0 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=5 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3_7 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1_0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=2 , ):
snake_case__ : List[Any] = parent
snake_case__ : List[Any] = batch_size
snake_case__ : str = image_size
snake_case__ : List[str] = patch_size
snake_case__ : str = num_channels
snake_case__ : Any = is_training
snake_case__ : Optional[int] = use_labels
snake_case__ : List[Any] = hidden_size
snake_case__ : List[Any] = num_hidden_layers
snake_case__ : int = num_attention_heads
snake_case__ : Dict = intermediate_size
snake_case__ : Dict = hidden_act
snake_case__ : Tuple = hidden_dropout_prob
snake_case__ : Tuple = attention_probs_dropout_prob
snake_case__ : Tuple = type_sequence_label_size
snake_case__ : int = initializer_range
snake_case__ : Tuple = scope
snake_case__ : str = encoder_stride
# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
snake_case__ : Dict = (image_size // patch_size) ** 2
snake_case__ : Union[str, Any] = num_patches + 1
def __UpperCamelCase ( self ):
snake_case__ : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
snake_case__ : Tuple = None
if self.use_labels:
snake_case__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size )
snake_case__ : List[Any] = self.get_config()
return config, pixel_values, labels
def __UpperCamelCase ( self ):
return ViTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , )
def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
snake_case__ : int = ViTModel(config=__SCREAMING_SNAKE_CASE )
model.to(__SCREAMING_SNAKE_CASE )
model.eval()
snake_case__ : Tuple = model(__SCREAMING_SNAKE_CASE )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
snake_case__ : Any = ViTForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE )
model.to(__SCREAMING_SNAKE_CASE )
model.eval()
snake_case__ : Union[str, Any] = model(__SCREAMING_SNAKE_CASE )
self.parent.assertEqual(
result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) )
# test greyscale images
snake_case__ : str = 1
snake_case__ : Any = ViTForMaskedImageModeling(__SCREAMING_SNAKE_CASE )
model.to(__SCREAMING_SNAKE_CASE )
model.eval()
snake_case__ : Optional[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
snake_case__ : Optional[Any] = model(__SCREAMING_SNAKE_CASE )
self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) )
def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
snake_case__ : List[str] = self.type_sequence_label_size
snake_case__ : Optional[int] = ViTForImageClassification(__SCREAMING_SNAKE_CASE )
model.to(__SCREAMING_SNAKE_CASE )
model.eval()
snake_case__ : str = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
snake_case__ : str = 1
snake_case__ : Tuple = ViTForImageClassification(__SCREAMING_SNAKE_CASE )
model.to(__SCREAMING_SNAKE_CASE )
model.eval()
snake_case__ : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
snake_case__ : Dict = model(__SCREAMING_SNAKE_CASE )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def __UpperCamelCase ( self ):
snake_case__ : str = self.prepare_config_and_inputs()
(
(
snake_case__
) , (
snake_case__
) , (
snake_case__
) ,
) : str = config_and_inputs
snake_case__ : Optional[Any] = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_torch
class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowerCamelCase__ = (
(
ViTModel,
ViTForImageClassification,
ViTForMaskedImageModeling,
)
if is_torch_available()
else ()
)
lowerCamelCase__ = (
{'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification}
if is_torch_available()
else {}
)
lowerCamelCase__ = True
lowerCamelCase__ = False
lowerCamelCase__ = False
lowerCamelCase__ = False
def __UpperCamelCase ( self ):
snake_case__ : Optional[Any] = ViTModelTester(self )
snake_case__ : Optional[Any] = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE , hidden_size=3_7 )
def __UpperCamelCase ( self ):
self.config_tester.run_common_tests()
@unittest.skip(reason="""ViT does not use inputs_embeds""" )
def __UpperCamelCase ( self ):
pass
def __UpperCamelCase ( self ):
snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
snake_case__ : Optional[int] = model_class(__SCREAMING_SNAKE_CASE )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
snake_case__ : str = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) )
def __UpperCamelCase ( self ):
snake_case__ , snake_case__ : int = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
snake_case__ : List[Any] = model_class(__SCREAMING_SNAKE_CASE )
snake_case__ : Dict = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
snake_case__ : Optional[int] = [*signature.parameters.keys()]
snake_case__ : Optional[Any] = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE )
def __UpperCamelCase ( self ):
snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE )
def __UpperCamelCase ( self ):
snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*__SCREAMING_SNAKE_CASE )
def __UpperCamelCase ( self ):
snake_case__ : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE )
@slow
def __UpperCamelCase ( self ):
for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
snake_case__ : Union[str, Any] = ViTModel.from_pretrained(__SCREAMING_SNAKE_CASE )
self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
def UpperCamelCase__ ( ) -> Optional[int]:
'''simple docstring'''
snake_case__ : Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
return image
@require_torch
@require_vision
class __snake_case ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def __UpperCamelCase ( self ):
return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None
@slow
def __UpperCamelCase ( self ):
snake_case__ : Optional[Any] = ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ).to(__SCREAMING_SNAKE_CASE )
snake_case__ : Optional[Any] = self.default_image_processor
snake_case__ : Optional[int] = prepare_img()
snake_case__ : Dict = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(__SCREAMING_SNAKE_CASE )
# forward pass
with torch.no_grad():
snake_case__ : Optional[int] = model(**__SCREAMING_SNAKE_CASE )
# verify the logits
snake_case__ : str = torch.Size((1, 1_0_0_0) )
self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE )
snake_case__ : List[str] = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(__SCREAMING_SNAKE_CASE )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
@slow
def __UpperCamelCase ( self ):
# ViT models have an `interpolate_pos_encoding` argument in their forward method,
# allowing to interpolate the pre-trained position embeddings in order to use
# the model on higher resolutions. The DINO model by Facebook AI leverages this
# to visualize self-attention on higher resolution images.
snake_case__ : str = ViTModel.from_pretrained("""facebook/dino-vits8""" ).to(__SCREAMING_SNAKE_CASE )
snake_case__ : Optional[Any] = ViTImageProcessor.from_pretrained("""facebook/dino-vits8""" , size=4_8_0 )
snake_case__ : Optional[Any] = prepare_img()
snake_case__ : Optional[int] = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" )
snake_case__ : Any = inputs.pixel_values.to(__SCREAMING_SNAKE_CASE )
# forward pass
with torch.no_grad():
snake_case__ : Dict = model(__SCREAMING_SNAKE_CASE , interpolate_pos_encoding=__SCREAMING_SNAKE_CASE )
# verify the logits
snake_case__ : Any = torch.Size((1, 3_6_0_1, 3_8_4) )
self.assertEqual(outputs.last_hidden_state.shape , __SCREAMING_SNAKE_CASE )
snake_case__ : Tuple = torch.tensor(
[[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(__SCREAMING_SNAKE_CASE )
self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
@slow
@require_accelerate
@require_torch_gpu
def __UpperCamelCase ( self ):
snake_case__ : Union[str, Any] = ViTModel.from_pretrained("""facebook/dino-vits8""" , torch_dtype=torch.floataa , device_map="""auto""" )
snake_case__ : Tuple = self.default_image_processor
snake_case__ : Tuple = prepare_img()
snake_case__ : Dict = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" )
snake_case__ : Tuple = inputs.pixel_values.to(__SCREAMING_SNAKE_CASE )
# forward pass to make sure inference works in fp16
with torch.no_grad():
snake_case__ : List[Any] = model(__SCREAMING_SNAKE_CASE )
| 419 | 0 |
"""simple docstring"""
from dataclasses import dataclass
from typing import Tuple
import numpy as np
import torch
@dataclass
class a :
_snake_case : List[Any] = 42 # [batch_size x 3]
_snake_case : int = 42 # [batch_size x 3]
_snake_case : List[str] = 42 # [batch_size x 3]
_snake_case : Optional[int] = 42 # [batch_size x 3]
_snake_case : Optional[Any] = 42
_snake_case : Any = 42
_snake_case : Dict = 42
_snake_case : str = 42
_snake_case : Tuple = 42
def lowerCAmelCase_ ( self : Optional[int] ):
assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0]
assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3
assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2
def lowerCAmelCase_ ( self : int ):
return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) )
def lowerCAmelCase_ ( self : Dict ):
return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) )
def lowerCAmelCase_ ( self : List[str] ):
_UpperCAmelCase = torch.arange(self.height * self.width )
_UpperCAmelCase = torch.stack(
[
pixel_indices % self.width,
torch.div(__snake_case , self.width , rounding_mode="""trunc""" ),
] , axis=1 , )
return coords
@property
def lowerCAmelCase_ ( self : str ):
_UpperCAmelCase = self.shape
_UpperCAmelCase = int(np.prod(__snake_case ) )
_UpperCAmelCase = self.get_image_coords()
_UpperCAmelCase = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] )
_UpperCAmelCase = self.get_camera_rays(__snake_case )
_UpperCAmelCase = rays.view(__snake_case , inner_batch_size * self.height * self.width , 2 , 3 )
return rays
def lowerCAmelCase_ ( self : Union[str, Any] , __lowerCAmelCase : torch.Tensor ):
_UpperCAmelCase = coords.shape
assert n_coords == 2
assert batch_size == self.origin.shape[0]
_UpperCAmelCase = coords.view(__snake_case , -1 , 2 )
_UpperCAmelCase = self.resolution()
_UpperCAmelCase = self.fov()
_UpperCAmelCase = (flat.float() / (res - 1)) * 2 - 1
_UpperCAmelCase = fracs * torch.tan(fov / 2 )
_UpperCAmelCase = fracs.view(__snake_case , -1 , 2 )
_UpperCAmelCase = (
self.z.view(__snake_case , 1 , 3 )
+ self.x.view(__snake_case , 1 , 3 ) * fracs[:, :, :1]
+ self.y.view(__snake_case , 1 , 3 ) * fracs[:, :, 1:]
)
_UpperCAmelCase = directions / directions.norm(dim=-1 , keepdim=__snake_case )
_UpperCAmelCase = torch.stack(
[
torch.broadcast_to(self.origin.view(__snake_case , 1 , 3 ) , [batch_size, directions.shape[1], 3] ),
directions,
] , dim=2 , )
return rays.view(__snake_case , *__snake_case , 2 , 3 )
def lowerCAmelCase_ ( self : Any , __lowerCAmelCase : int , __lowerCAmelCase : int ):
assert width * self.height == height * self.width, "The aspect ratio should not change."
return DifferentiableProjectiveCamera(
origin=self.origin , x=self.x , y=self.y , z=self.z , width=__snake_case , height=__snake_case , x_fov=self.x_fov , y_fov=self.y_fov , )
def __UpperCAmelCase ( lowercase ):
"""simple docstring"""
_UpperCAmelCase = []
_UpperCAmelCase = []
_UpperCAmelCase = []
_UpperCAmelCase = []
for theta in np.linspace(0 ,2 * np.pi ,num=20 ):
_UpperCAmelCase = np.array([np.sin(_A ), np.cos(_A ), -0.5] )
z /= np.sqrt(np.sum(z**2 ) )
_UpperCAmelCase = -z * 4
_UpperCAmelCase = np.array([np.cos(_A ), -np.sin(_A ), 0.0] )
_UpperCAmelCase = np.cross(_A ,_A )
origins.append(_A )
xs.append(_A )
ys.append(_A )
zs.append(_A )
return DifferentiableProjectiveCamera(
origin=torch.from_numpy(np.stack(_A ,axis=0 ) ).float() ,x=torch.from_numpy(np.stack(_A ,axis=0 ) ).float() ,y=torch.from_numpy(np.stack(_A ,axis=0 ) ).float() ,z=torch.from_numpy(np.stack(_A ,axis=0 ) ).float() ,width=_A ,height=_A ,x_fov=0.7 ,y_fov=0.7 ,shape=(1, len(_A )) ,)
| 277 |
'''simple docstring'''
from __future__ import annotations
def lowerCamelCase__ ( _A , _A , _A ):
a : List[str] = list(range(len(_A ) ) )
a : Union[str, Any] = [v / w for v, w in zip(_A , _A )]
index.sort(key=lambda _A : ratio[i] , reverse=_A )
a : float = 0
a : list[float] = [0] * len(_A )
for i in index:
if weight[i] <= capacity:
a : int = 1
max_value += value[i]
capacity -= weight[i]
else:
a : Optional[int] = capacity / weight[i]
max_value += value[i] * capacity / weight[i]
break
return max_value, fractions
if __name__ == "__main__":
import doctest
doctest.testmod() | 526 | 0 |
import unittest
import numpy as np
from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
if is_flax_available():
import jax.numpy as jnp
from transformers.models.distilbert.modeling_flax_distilbert import (
FlaxDistilBertForMaskedLM,
FlaxDistilBertForMultipleChoice,
FlaxDistilBertForQuestionAnswering,
FlaxDistilBertForSequenceClassification,
FlaxDistilBertForTokenClassification,
FlaxDistilBertModel,
)
class __a ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : List[str] ,_UpperCamelCase : Tuple ,_UpperCamelCase : Union[str, Any]=1_3 ,_UpperCamelCase : Optional[Any]=7 ,_UpperCamelCase : str=True ,_UpperCamelCase : Union[str, Any]=True ,_UpperCamelCase : Any=True ,_UpperCamelCase : Union[str, Any]=True ,_UpperCamelCase : List[str]=9_9 ,_UpperCamelCase : Optional[Any]=3_2 ,_UpperCamelCase : Union[str, Any]=5 ,_UpperCamelCase : Any=4 ,_UpperCamelCase : Any=3_7 ,_UpperCamelCase : str="gelu" ,_UpperCamelCase : List[Any]=0.1 ,_UpperCamelCase : List[str]=0.1 ,_UpperCamelCase : Any=5_1_2 ,_UpperCamelCase : Dict=1_6 ,_UpperCamelCase : Union[str, Any]=2 ,_UpperCamelCase : Dict=0.02 ,_UpperCamelCase : Optional[int]=4 ,) -> int:
'''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_attention_mask
SCREAMING_SNAKE_CASE__ =use_token_type_ids
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_act
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__ =type_sequence_label_size
SCREAMING_SNAKE_CASE__ =initializer_range
SCREAMING_SNAKE_CASE__ =num_choices
def __A ( self : List[Any] ) -> Optional[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ =ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size )
SCREAMING_SNAKE_CASE__ =None
if self.use_attention_mask:
SCREAMING_SNAKE_CASE__ =random_attention_mask([self.batch_size, self.seq_length] )
SCREAMING_SNAKE_CASE__ =DistilBertConfig(
vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=_UpperCamelCase ,)
return config, input_ids, attention_mask
def __A ( self : Tuple ) -> Union[str, Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ =self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ =config_and_inputs
SCREAMING_SNAKE_CASE__ ={"""input_ids""": input_ids, """attention_mask""": attention_mask}
return config, inputs_dict
@require_flax
class __a ( __lowerCamelCase , unittest.TestCase ):
"""simple docstring"""
_A : Tuple = (
(
FlaxDistilBertModel,
FlaxDistilBertForMaskedLM,
FlaxDistilBertForMultipleChoice,
FlaxDistilBertForQuestionAnswering,
FlaxDistilBertForSequenceClassification,
FlaxDistilBertForTokenClassification,
FlaxDistilBertForQuestionAnswering,
)
if is_flax_available()
else ()
)
def __A ( self : Union[str, Any] ) -> Any:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ =FlaxDistilBertModelTester(self )
@slow
def __A ( self : Optional[Any] ) -> Optional[int]:
'''simple docstring'''
for model_class_name in self.all_model_classes:
SCREAMING_SNAKE_CASE__ =model_class_name.from_pretrained("""distilbert-base-uncased""" )
SCREAMING_SNAKE_CASE__ =model(np.ones((1, 1) ) )
self.assertIsNotNone(_UpperCamelCase )
@require_flax
class __a ( unittest.TestCase ):
"""simple docstring"""
@slow
def __A ( self : Any ) -> List[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ =FlaxDistilBertModel.from_pretrained("""distilbert-base-uncased""" )
SCREAMING_SNAKE_CASE__ =np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] )
SCREAMING_SNAKE_CASE__ =np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
SCREAMING_SNAKE_CASE__ =model(_UpperCamelCase ,attention_mask=_UpperCamelCase )[0]
SCREAMING_SNAKE_CASE__ =(1, 1_1, 7_6_8)
self.assertEqual(output.shape ,_UpperCamelCase )
SCREAMING_SNAKE_CASE__ =np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] )
self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,_UpperCamelCase ,atol=1e-4 ) )
| 588 |
import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import SPIECE_UNDERLINE, logging
lowerCamelCase_ = logging.get_logger(__name__)
lowerCamelCase_ = {"vocab_file": "spiece.model"}
lowerCamelCase_ = {
"vocab_file": {
"TsinghuaAI/CPM-Generate": "https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model",
}
}
class __a ( __lowerCamelCase ):
"""simple docstring"""
def __init__( self : str ,_UpperCamelCase : Tuple ,_UpperCamelCase : int=False ,_UpperCamelCase : int=True ,_UpperCamelCase : str=False ,_UpperCamelCase : Dict="<s>" ,_UpperCamelCase : Tuple="</s>" ,_UpperCamelCase : Tuple="<unk>" ,_UpperCamelCase : int="<sep>" ,_UpperCamelCase : List[str]="<pad>" ,_UpperCamelCase : str="<cls>" ,_UpperCamelCase : Any="<mask>" ,_UpperCamelCase : Any=["<eop>", "<eod>"] ,_UpperCamelCase : Optional[Dict[str, Any]] = None ,**_UpperCamelCase : str ,) -> None:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ =AddedToken(_UpperCamelCase ,lstrip=_UpperCamelCase ,rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase ,_UpperCamelCase ) else mask_token
SCREAMING_SNAKE_CASE__ ={} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
do_lower_case=_UpperCamelCase ,remove_space=_UpperCamelCase ,keep_accents=_UpperCamelCase ,bos_token=_UpperCamelCase ,eos_token=_UpperCamelCase ,unk_token=_UpperCamelCase ,sep_token=_UpperCamelCase ,pad_token=_UpperCamelCase ,cls_token=_UpperCamelCase ,mask_token=_UpperCamelCase ,additional_special_tokens=_UpperCamelCase ,sp_model_kwargs=self.sp_model_kwargs ,**_UpperCamelCase ,)
SCREAMING_SNAKE_CASE__ =3
SCREAMING_SNAKE_CASE__ =do_lower_case
SCREAMING_SNAKE_CASE__ =remove_space
SCREAMING_SNAKE_CASE__ =keep_accents
SCREAMING_SNAKE_CASE__ =vocab_file
SCREAMING_SNAKE_CASE__ =spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(_UpperCamelCase )
try:
import jieba
except ModuleNotFoundError as error:
raise error.__class__(
"""You need to install jieba to use CpmTokenizer or CpmTokenizerFast. """
"""See https://pypi.org/project/jieba/ for installation.""" )
SCREAMING_SNAKE_CASE__ =jieba
SCREAMING_SNAKE_CASE__ =str.maketrans(""" \n""" ,"""\u2582\u2583""" )
@property
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
def __A ( self : Any ) -> List[str]:
'''simple docstring'''
return len(self.sp_model )
def __A ( self : Optional[Any] ) -> Optional[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ ={self.convert_ids_to_tokens(_UpperCamelCase ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : List[Any] ) -> Tuple:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ =self.__dict__.copy()
SCREAMING_SNAKE_CASE__ =None
return state
def __setstate__( self : Any ,_UpperCamelCase : List[str] ) -> Dict:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ =d
# for backward compatibility
if not hasattr(self ,"""sp_model_kwargs""" ):
SCREAMING_SNAKE_CASE__ ={}
SCREAMING_SNAKE_CASE__ =spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def __A ( self : str ,_UpperCamelCase : List[str] ) -> Optional[Any]:
'''simple docstring'''
if self.remove_space:
SCREAMING_SNAKE_CASE__ =""" """.join(inputs.strip().split() )
else:
SCREAMING_SNAKE_CASE__ =inputs
SCREAMING_SNAKE_CASE__ =outputs.replace("""``""" ,"""\"""" ).replace("""''""" ,"""\"""" )
if not self.keep_accents:
SCREAMING_SNAKE_CASE__ =unicodedata.normalize("""NFKD""" ,_UpperCamelCase )
SCREAMING_SNAKE_CASE__ ="""""".join([c for c in outputs if not unicodedata.combining(_UpperCamelCase )] )
if self.do_lower_case:
SCREAMING_SNAKE_CASE__ =outputs.lower()
return outputs
def __A ( self : Optional[int] ,_UpperCamelCase : str ) -> List[str]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ =self.preprocess_text(_UpperCamelCase )
SCREAMING_SNAKE_CASE__ =self.sp_model.encode(_UpperCamelCase ,out_type=_UpperCamelCase )
SCREAMING_SNAKE_CASE__ =[]
for piece in pieces:
if len(_UpperCamelCase ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit():
SCREAMING_SNAKE_CASE__ =self.sp_model.EncodeAsPieces(piece[:-1].replace(_UpperCamelCase ,"""""" ) )
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
if len(cur_pieces[0] ) == 1:
SCREAMING_SNAKE_CASE__ =cur_pieces[1:]
else:
SCREAMING_SNAKE_CASE__ =cur_pieces[0][1:]
cur_pieces.append(piece[-1] )
new_pieces.extend(_UpperCamelCase )
else:
new_pieces.append(_UpperCamelCase )
return new_pieces
def __A ( self : Tuple ,_UpperCamelCase : Any ) -> Any:
'''simple docstring'''
return self.sp_model.PieceToId(_UpperCamelCase )
def __A ( self : str ,_UpperCamelCase : List[str] ) -> Dict:
'''simple docstring'''
return self.sp_model.IdToPiece(_UpperCamelCase )
def __A ( self : int ,_UpperCamelCase : Any ) -> str:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ ="""""".join(_UpperCamelCase ).replace(_UpperCamelCase ,""" """ ).strip()
return out_string
def __A ( self : Union[str, Any] ,_UpperCamelCase : List[int] ,_UpperCamelCase : Optional[List[int]] = None ) -> List[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ =[self.sep_token_id]
SCREAMING_SNAKE_CASE__ =[self.cls_token_id]
if token_ids_a is None:
return token_ids_a + sep + cls
return token_ids_a + sep + token_ids_a + sep + cls
def __A ( self : int ,_UpperCamelCase : List[int] ,_UpperCamelCase : Optional[List[int]] = None ,_UpperCamelCase : bool = False ) -> List[int]:
'''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 )
if token_ids_a is not None:
return ([0] * len(_UpperCamelCase )) + [1] + ([0] * len(_UpperCamelCase )) + [1, 1]
return ([0] * len(_UpperCamelCase )) + [1, 1]
def __A ( self : int ,_UpperCamelCase : List[int] ,_UpperCamelCase : Optional[List[int]] = None ) -> List[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ =[self.sep_token_id]
SCREAMING_SNAKE_CASE__ =[2]
if token_ids_a is None:
return len(token_ids_a + sep ) * [0] + cls_segment_id
return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id
def __A ( self : Optional[int] ,_UpperCamelCase : str ,_UpperCamelCase : Optional[str] = None ) -> Tuple[str]:
'''simple docstring'''
if not os.path.isdir(_UpperCamelCase ):
logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" )
return
SCREAMING_SNAKE_CASE__ =os.path.join(
_UpperCamelCase ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCamelCase ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file ,_UpperCamelCase )
elif not os.path.isfile(self.vocab_file ):
with open(_UpperCamelCase ,"""wb""" ) as fi:
SCREAMING_SNAKE_CASE__ =self.sp_model.serialized_model_proto()
fi.write(_UpperCamelCase )
return (out_vocab_file,)
def __A ( self : int ,*_UpperCamelCase : Dict ,**_UpperCamelCase : Optional[Any] ) -> Union[str, Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ =super()._decode(*_UpperCamelCase ,**_UpperCamelCase )
SCREAMING_SNAKE_CASE__ =text.replace(""" """ ,"""""" ).replace("""\u2582""" ,""" """ ).replace("""\u2583""" ,"""\n""" )
return text
| 588 | 1 |
import argparse
import json
import os
import fairseq
import torch
from fairseq.data import Dictionary
from transformers import (
UniSpeechConfig,
UniSpeechForCTC,
UniSpeechForPreTraining,
WavaVecaFeatureExtractor,
WavaVecaPhonemeCTCTokenizer,
WavaVecaProcessor,
logging,
)
logging.set_verbosity_info()
__A = logging.get_logger(__name__)
__A = {
"post_extract_proj": "feature_projection.projection",
"encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
"self_attn.k_proj": "encoder.layers.*.attention.k_proj",
"self_attn.v_proj": "encoder.layers.*.attention.v_proj",
"self_attn.q_proj": "encoder.layers.*.attention.q_proj",
"self_attn.out_proj": "encoder.layers.*.attention.out_proj",
"self_attn_layer_norm": "encoder.layers.*.layer_norm",
"fc1": "encoder.layers.*.feed_forward.intermediate_dense",
"fc2": "encoder.layers.*.feed_forward.output_dense",
"final_layer_norm": "encoder.layers.*.final_layer_norm",
"encoder.layer_norm": "encoder.layer_norm",
"w2v_model.layer_norm": "feature_projection.layer_norm",
"quantizer.weight_proj": "quantizer.weight_proj",
"quantizer.vars": "quantizer.codevectors",
"project_q": "project_q",
"final_proj": "project_hid",
"w2v_encoder.proj": "ctc_proj",
"mask_emb": "masked_spec_embed",
}
__A = [
"ctc_proj",
"quantizer.weight_proj",
"quantizer.codevectors",
"project_q",
"project_hid",
]
def lowercase__ ( A_: int , A_: Optional[int] , A_: Optional[int] , A_: int , A_: List[str] , A_: Union[str, Any] ) -> Any:
"""simple docstring"""
for attribute in key.split(""".""" ):
if is_finetuned:
if attribute in ["quantizer", "project_q", "project_hid"]:
# those layers are only relevant for pretraining and should be dropped
return
if attribute == "ctc_proj":
# we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models
__UpperCAmelCase ="""lm_head"""
__UpperCAmelCase =getattr(A_ , A_ )
if weight_type is not None:
__UpperCAmelCase =getattr(A_ , A_ ).shape
else:
__UpperCAmelCase =hf_pointer.shape
assert hf_shape == value.shape, (
F'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'''
F''' {value.shape} for {full_name}'''
)
if weight_type == "weight":
__UpperCAmelCase =value
elif weight_type == "weight_g":
__UpperCAmelCase =value
elif weight_type == "weight_v":
__UpperCAmelCase =value
elif weight_type == "bias":
__UpperCAmelCase =value
else:
__UpperCAmelCase =value
logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' )
def lowercase__ ( A_: str , A_: int , A_: int ) -> List[str]:
"""simple docstring"""
__UpperCAmelCase =[]
__UpperCAmelCase =fairseq_model.state_dict()
__UpperCAmelCase =hf_model.unispeech.feature_extractor
for name, value in fairseq_dict.items():
__UpperCAmelCase =False
if "conv_layers" in name:
load_conv_layer(
A_ , A_ , A_ , A_ , hf_model.config.feat_extract_norm == """group""" , )
__UpperCAmelCase =True
else:
for key, mapped_key in MAPPING.items():
__UpperCAmelCase ="""unispeech.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]:
__UpperCAmelCase =True
if "*" in mapped_key:
__UpperCAmelCase =name.split(A_ )[0].split(""".""" )[-2]
__UpperCAmelCase =mapped_key.replace("""*""" , A_ )
if "weight_g" in name:
__UpperCAmelCase ="""weight_g"""
elif "weight_v" in name:
__UpperCAmelCase ="""weight_v"""
elif "bias" in name:
__UpperCAmelCase ="""bias"""
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
__UpperCAmelCase ="""weight"""
else:
__UpperCAmelCase =None
set_recursively(A_ , A_ , A_ , A_ , A_ , A_ )
continue
if not is_used:
unused_weights.append(A_ )
logger.warning(F'''Unused weights: {unused_weights}''' )
def lowercase__ ( A_: List[str] , A_: Union[str, Any] , A_: Any , A_: Optional[int] , A_: Union[str, Any] ) -> Tuple:
"""simple docstring"""
__UpperCAmelCase =full_name.split("""conv_layers.""" )[-1]
__UpperCAmelCase =name.split(""".""" )
__UpperCAmelCase =int(items[0] )
__UpperCAmelCase =int(items[1] )
if type_id == 0:
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
)
__UpperCAmelCase =value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
)
__UpperCAmelCase =value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
" found."
)
__UpperCAmelCase =value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
)
__UpperCAmelCase =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 lowercase__ ( A_: Optional[int] , A_: str , A_: List[Any]=None , A_: List[str]=None , A_: Optional[int]=True ) -> Dict:
"""simple docstring"""
if config_path is not None:
__UpperCAmelCase =UniSpeechConfig.from_pretrained(A_ )
else:
__UpperCAmelCase =UniSpeechConfig()
if is_finetuned:
if dict_path:
__UpperCAmelCase =Dictionary.load_from_json(A_ )
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
__UpperCAmelCase =target_dict.pad_index
__UpperCAmelCase =target_dict.bos_index
__UpperCAmelCase =target_dict.eos_index
__UpperCAmelCase =len(target_dict.symbols )
__UpperCAmelCase =os.path.join(A_ , """vocab.json""" )
if not os.path.isdir(A_ ):
logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(A_ ) )
return
os.makedirs(A_ , exist_ok=A_ )
__UpperCAmelCase =target_dict.indices
# fairseq has the <pad> and <s> switched
__UpperCAmelCase =42
__UpperCAmelCase =43
with open(A_ , """w""" , encoding="""utf-8""" ) as vocab_handle:
json.dump(A_ , A_ )
__UpperCAmelCase =WavaVecaPhonemeCTCTokenizer(
A_ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=A_ , )
__UpperCAmelCase =True if config.feat_extract_norm == """layer""" else False
__UpperCAmelCase =WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=A_ , return_attention_mask=A_ , )
__UpperCAmelCase =WavaVecaProcessor(feature_extractor=A_ , tokenizer=A_ )
processor.save_pretrained(A_ )
__UpperCAmelCase =UniSpeechForCTC(A_ )
else:
__UpperCAmelCase =UniSpeechForPreTraining(A_ )
if is_finetuned:
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] ), """w2v_path""": checkpoint_path} )
else:
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] )
__UpperCAmelCase =model[0].eval()
recursively_load_weights(A_ , A_ , A_ )
hf_unispeech.save_pretrained(A_ )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
parser.add_argument(
"--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not"
)
__A = parser.parse_args()
convert_unispeech_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
)
| 68 |
from collections import defaultdict
from typing import Optional
from ..image_utils import load_image
from ..utils import (
add_end_docstrings,
is_torch_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ChunkPipeline
if is_torch_available():
import torch
from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING
SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__)
@add_end_docstrings(__lowercase )
class lowerCAmelCase__ ( __lowercase ):
def __init__( self : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]:
super().__init__(**SCREAMING_SNAKE_CASE__ )
requires_backends(self , '''vision''' )
requires_backends(self , '''torch''' )
if self.framework != "pt":
raise ValueError(f'''The {self.__class__} is only available in PyTorch.''' )
self.check_model_type(SCREAMING_SNAKE_CASE__ )
def __A ( self : str , **SCREAMING_SNAKE_CASE__ : str ) -> Any:
__lowerCamelCase = {}
__lowerCamelCase = {}
__lowerCamelCase = {}
# preprocess args
if "points_per_batch" in kwargs:
__lowerCamelCase = kwargs['''points_per_batch''']
if "points_per_crop" in kwargs:
__lowerCamelCase = kwargs['''points_per_crop''']
if "crops_n_layers" in kwargs:
__lowerCamelCase = kwargs['''crops_n_layers''']
if "crop_overlap_ratio" in kwargs:
__lowerCamelCase = kwargs['''crop_overlap_ratio''']
if "crop_n_points_downscale_factor" in kwargs:
__lowerCamelCase = kwargs['''crop_n_points_downscale_factor''']
# postprocess args
if "pred_iou_thresh" in kwargs:
__lowerCamelCase = kwargs['''pred_iou_thresh''']
if "stability_score_offset" in kwargs:
__lowerCamelCase = kwargs['''stability_score_offset''']
if "mask_threshold" in kwargs:
__lowerCamelCase = kwargs['''mask_threshold''']
if "stability_score_thresh" in kwargs:
__lowerCamelCase = kwargs['''stability_score_thresh''']
if "crops_nms_thresh" in kwargs:
__lowerCamelCase = kwargs['''crops_nms_thresh''']
if "output_rle_mask" in kwargs:
__lowerCamelCase = kwargs['''output_rle_mask''']
if "output_bboxes_mask" in kwargs:
__lowerCamelCase = kwargs['''output_bboxes_mask''']
return preprocess_kwargs, forward_params, postprocess_kwargs
def __call__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , *SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , **SCREAMING_SNAKE_CASE__ : int ) -> Union[str, Any]:
return super().__call__(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , num_workers=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
def __A ( self : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any]=64 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : float = 5_12 / 15_00 , SCREAMING_SNAKE_CASE__ : Optional[int] = 32 , SCREAMING_SNAKE_CASE__ : Optional[int] = 1 , ) -> List[str]:
__lowerCamelCase = load_image(SCREAMING_SNAKE_CASE__ )
__lowerCamelCase = self.image_processor.size['''longest_edge''']
__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = self.image_processor.generate_crop_boxes(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
__lowerCamelCase = self.image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' )
with self.device_placement():
if self.framework == "pt":
__lowerCamelCase = self.get_inference_context()
with inference_context():
__lowerCamelCase = self._ensure_tensor_on_device(SCREAMING_SNAKE_CASE__ , device=self.device )
__lowerCamelCase = self.model.get_image_embeddings(model_inputs.pop('''pixel_values''' ) )
__lowerCamelCase = image_embeddings
__lowerCamelCase = grid_points.shape[1]
__lowerCamelCase = points_per_batch if points_per_batch is not None else n_points
if points_per_batch <= 0:
raise ValueError(
'''Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. '''
'''To return all points at once, set points_per_batch to None''' )
for i in range(0 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
__lowerCamelCase = grid_points[:, i : i + points_per_batch, :, :]
__lowerCamelCase = input_labels[:, i : i + points_per_batch]
__lowerCamelCase = i == n_points - points_per_batch
yield {
"input_points": batched_points,
"input_labels": labels,
"input_boxes": crop_boxes,
"is_last": is_last,
**model_inputs,
}
def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int]=0.88 , SCREAMING_SNAKE_CASE__ : Tuple=0.95 , SCREAMING_SNAKE_CASE__ : Dict=0 , SCREAMING_SNAKE_CASE__ : Tuple=1 , ) -> Dict:
__lowerCamelCase = model_inputs.pop('''input_boxes''' )
__lowerCamelCase = model_inputs.pop('''is_last''' )
__lowerCamelCase = model_inputs.pop('''original_sizes''' ).tolist()
__lowerCamelCase = model_inputs.pop('''reshaped_input_sizes''' ).tolist()
__lowerCamelCase = self.model(**SCREAMING_SNAKE_CASE__ )
# post processing happens here in order to avoid CPU GPU copies of ALL the masks
__lowerCamelCase = model_outputs['''pred_masks''']
__lowerCamelCase = self.image_processor.post_process_masks(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , binarize=SCREAMING_SNAKE_CASE__ )
__lowerCamelCase = model_outputs['''iou_scores''']
__lowerCamelCase , __lowerCamelCase , __lowerCamelCase = self.image_processor.filter_masks(
masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , )
return {
"masks": masks,
"is_last": is_last,
"boxes": boxes,
"iou_scores": iou_scores,
}
def __A ( self : str , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Optional[int]=0.7 , ) -> Union[str, Any]:
__lowerCamelCase = []
__lowerCamelCase = []
__lowerCamelCase = []
for model_output in model_outputs:
all_scores.append(model_output.pop('''iou_scores''' ) )
all_masks.extend(model_output.pop('''masks''' ) )
all_boxes.append(model_output.pop('''boxes''' ) )
__lowerCamelCase = torch.cat(SCREAMING_SNAKE_CASE__ )
__lowerCamelCase = torch.cat(SCREAMING_SNAKE_CASE__ )
__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = self.image_processor.post_process_for_mask_generation(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
__lowerCamelCase = defaultdict(SCREAMING_SNAKE_CASE__ )
for output in model_outputs:
for k, v in output.items():
extra[k].append(SCREAMING_SNAKE_CASE__ )
__lowerCamelCase = {}
if output_rle_mask:
__lowerCamelCase = rle_mask
if output_bboxes_mask:
__lowerCamelCase = bounding_boxes
return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
| 298 | 0 |
"""simple docstring"""
class UpperCAmelCase :
def __init__( self : Optional[int] ):
"""simple docstring"""
_snake_case = ''''''
_snake_case = ''''''
_snake_case = []
def __UpperCAmelCase ( self : Tuple , __lowerCamelCase : int , __lowerCamelCase : int ):
"""simple docstring"""
if m == -1:
return n + 1
elif n == -1:
return m + 1
elif self.dp[m][n] > -1:
return self.dp[m][n]
else:
if self.worda[m] == self.worda[n]:
_snake_case = self.__min_dist_top_down_dp(m - 1 , n - 1 )
else:
_snake_case = self.__min_dist_top_down_dp(__lowerCamelCase , n - 1 )
_snake_case = self.__min_dist_top_down_dp(m - 1 , __lowerCamelCase )
_snake_case = self.__min_dist_top_down_dp(m - 1 , n - 1 )
_snake_case = 1 + min(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
return self.dp[m][n]
def __UpperCAmelCase ( self : Optional[Any] , __lowerCamelCase : str , __lowerCamelCase : str ):
"""simple docstring"""
_snake_case = worda
_snake_case = worda
_snake_case = [[-1 for _ in range(len(__lowerCamelCase ) )] for _ in range(len(__lowerCamelCase ) )]
return self.__min_dist_top_down_dp(len(__lowerCamelCase ) - 1 , len(__lowerCamelCase ) - 1 )
def __UpperCAmelCase ( self : Any , __lowerCamelCase : str , __lowerCamelCase : str ):
"""simple docstring"""
_snake_case = worda
_snake_case = worda
_snake_case = len(__lowerCamelCase )
_snake_case = len(__lowerCamelCase )
_snake_case = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )]
for i in range(m + 1 ):
for j in range(n + 1 ):
if i == 0: # first string is empty
_snake_case = j
elif j == 0: # second string is empty
_snake_case = i
elif worda[i - 1] == worda[j - 1]: # last characters are equal
_snake_case = self.dp[i - 1][j - 1]
else:
_snake_case = self.dp[i][j - 1]
_snake_case = self.dp[i - 1][j]
_snake_case = self.dp[i - 1][j - 1]
_snake_case = 1 + min(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
return self.dp[m][n]
if __name__ == "__main__":
snake_case = EditDistance()
print('''****************** Testing Edit Distance DP Algorithm ******************''')
print()
snake_case = input('''Enter the first string: ''').strip()
snake_case = input('''Enter the second string: ''').strip()
print()
print(F"The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}")
print(F"The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}")
print()
print('''*************** End of Testing Edit Distance DP Algorithm ***************''')
| 404 |
"""simple docstring"""
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel
from transformers.utils import logging
logging.set_verbosity_info()
snake_case = logging.get_logger(__name__)
def snake_case ( lowerCAmelCase_ , lowerCAmelCase_=False ) -> str:
_snake_case = []
for i in range(config.num_hidden_layers ):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""") )
rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""") )
rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""") )
rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""") )
rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""") )
rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""") )
rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""") )
rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""") )
rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""") )
rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""") )
# projection layer + position embeddings
rename_keys.extend(
[
('''cls_token''', '''vit.embeddings.cls_token'''),
('''patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight'''),
('''patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias'''),
('''pos_embed''', '''vit.embeddings.position_embeddings'''),
] )
if base_model:
# layernorm + pooler
rename_keys.extend(
[
('''norm.weight''', '''layernorm.weight'''),
('''norm.bias''', '''layernorm.bias'''),
] )
# if just the base model, we should remove "vit" from all keys that start with "vit"
_snake_case = [(pair[0], pair[1][4:]) if pair[1].startswith('''vit''' ) else pair for pair in rename_keys]
else:
# layernorm + classification head
rename_keys.extend(
[
('''norm.weight''', '''vit.layernorm.weight'''),
('''norm.bias''', '''vit.layernorm.bias'''),
('''head.weight''', '''classifier.weight'''),
('''head.bias''', '''classifier.bias'''),
] )
return rename_keys
def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False ) -> int:
for i in range(config.num_hidden_layers ):
if base_model:
_snake_case = ''''''
else:
_snake_case = '''vit.'''
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
_snake_case = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" )
_snake_case = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" )
# next, add query, keys and values (in that order) to the state dict
_snake_case = in_proj_weight[
: config.hidden_size, :
]
_snake_case = in_proj_bias[: config.hidden_size]
_snake_case = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
_snake_case = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
_snake_case = in_proj_weight[
-config.hidden_size :, :
]
_snake_case = in_proj_bias[-config.hidden_size :]
def snake_case ( lowerCAmelCase_ ) -> Any:
_snake_case = ['''head.weight''', '''head.bias''']
for k in ignore_keys:
state_dict.pop(lowerCAmelCase_ , lowerCAmelCase_ )
def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Dict:
_snake_case = dct.pop(lowerCAmelCase_ )
_snake_case = val
def snake_case ( ) -> List[Any]:
_snake_case = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
_snake_case = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw )
return im
@torch.no_grad()
def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=True ) -> Any:
_snake_case = ViTConfig()
# patch_size
if model_name[-1] == "8":
_snake_case = 8
# set labels if required
if not base_model:
_snake_case = 1000
_snake_case = '''huggingface/label-files'''
_snake_case = '''imagenet-1k-id2label.json'''
_snake_case = json.load(open(hf_hub_download(lowerCAmelCase_ , lowerCAmelCase_ , repo_type='''dataset''' ) , '''r''' ) )
_snake_case = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()}
_snake_case = idalabel
_snake_case = {v: k for k, v in idalabel.items()}
# size of the architecture
if model_name in ["dino_vits8", "dino_vits16"]:
_snake_case = 384
_snake_case = 1536
_snake_case = 12
_snake_case = 6
# load original model from torch hub
_snake_case = torch.hub.load('''facebookresearch/dino:main''' , lowerCAmelCase_ )
original_model.eval()
# load state_dict of original model, remove and rename some keys
_snake_case = original_model.state_dict()
if base_model:
remove_classification_head_(lowerCAmelCase_ )
_snake_case = create_rename_keys(lowerCAmelCase_ , base_model=lowerCAmelCase_ )
for src, dest in rename_keys:
rename_key(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
read_in_q_k_v(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
# load HuggingFace model
if base_model:
_snake_case = ViTModel(lowerCAmelCase_ , add_pooling_layer=lowerCAmelCase_ ).eval()
else:
_snake_case = ViTForImageClassification(lowerCAmelCase_ ).eval()
model.load_state_dict(lowerCAmelCase_ )
# Check outputs on an image, prepared by ViTImageProcessor
_snake_case = ViTImageProcessor()
_snake_case = image_processor(images=prepare_img() , return_tensors='''pt''' )
_snake_case = encoding['''pixel_values''']
_snake_case = model(lowerCAmelCase_ )
if base_model:
_snake_case = original_model(lowerCAmelCase_ )
assert torch.allclose(lowerCAmelCase_ , outputs.last_hidden_state[:, 0, :] , atol=1E-1 )
else:
_snake_case = original_model(lowerCAmelCase_ )
assert logits.shape == outputs.logits.shape
assert torch.allclose(lowerCAmelCase_ , outputs.logits , atol=1E-3 )
Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ )
print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" )
model.save_pretrained(lowerCAmelCase_ )
print(f"""Saving image processor to {pytorch_dump_folder_path}""" )
image_processor.save_pretrained(lowerCAmelCase_ )
if __name__ == "__main__":
snake_case = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--model_name''',
default='''dino_vitb16''',
type=str,
help='''Name of the model trained with DINO you\'d like to convert.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
)
parser.add_argument(
'''--base_model''',
action='''store_true''',
help='''Whether to only convert the base model (no projection head weights).''',
)
parser.set_defaults(base_model=True)
snake_case = parser.parse_args()
convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
| 404 | 1 |
UpperCamelCase : Optional[int] = """Input must be a string of 8 numbers plus letter"""
UpperCamelCase : Tuple = """TRWAGMYFPDXBNJZSQVHLCKE"""
def UpperCamelCase_ ( __a ) -> bool:
if not isinstance(__a , __a ):
a__ : Dict = f'''Expected string as input, found {type(__a ).__name__}'''
raise TypeError(__a )
a__ : str = spanish_id.replace("-" , "" ).upper()
if len(__a ) != 9:
raise ValueError(__a )
try:
a__ : List[str] = int(spanish_id_clean[0:8] )
a__ : Any = spanish_id_clean[8]
except ValueError as ex:
raise ValueError(__a ) from ex
if letter.isdigit():
raise ValueError(__a )
return letter == LOOKUP_LETTERS[number % 23]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 37 |
from transformers import DistilBertTokenizer, DistilBertTokenizerFast
from transformers.testing_utils import require_tokenizers, slow
from ..bert.test_tokenization_bert import BertTokenizationTest
@require_tokenizers
class __lowercase ( UpperCAmelCase_ ):
"""simple docstring"""
_UpperCAmelCase : Optional[Any] = DistilBertTokenizer
_UpperCAmelCase : Union[str, Any] = DistilBertTokenizerFast
_UpperCAmelCase : int = True
@slow
def _SCREAMING_SNAKE_CASE ( self : Any):
SCREAMING_SNAKE_CASE_: Optional[Any] = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
SCREAMING_SNAKE_CASE_: Any = tokenizer.encode("sequence builders" , add_special_tokens=lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: List[Any] = tokenizer.encode("multi-sequence build" , add_special_tokens=lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Tuple = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: int = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__ , lowerCAmelCase__)
assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [
tokenizer.sep_token_id
]
| 671 | 0 |
'''simple docstring'''
def UpperCamelCase_ ( __SCREAMING_SNAKE_CASE ):
"""simple docstring"""
snake_case_ : str = int(__SCREAMING_SNAKE_CASE )
if decimal in (0, 1): # Exit cases for the recursion
return str(__SCREAMING_SNAKE_CASE )
snake_case_ , snake_case_ : Any = divmod(__SCREAMING_SNAKE_CASE, 2 )
return binary_recursive(__SCREAMING_SNAKE_CASE ) + str(__SCREAMING_SNAKE_CASE )
def UpperCamelCase_ ( __SCREAMING_SNAKE_CASE ):
"""simple docstring"""
snake_case_ : List[Any] = str(__SCREAMING_SNAKE_CASE ).strip()
if not number:
raise ValueError("No input value was provided" )
snake_case_ : Dict = "-" if number.startswith("-" ) else ""
snake_case_ : Optional[int] = number.lstrip("-" )
if not number.isnumeric():
raise ValueError("Input value is not an integer" )
return f'{negative}0b{binary_recursive(int(__SCREAMING_SNAKE_CASE ) )}'
if __name__ == "__main__":
from doctest import testmod
testmod()
| 92 |
'''simple docstring'''
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import TensorType, logging
if TYPE_CHECKING:
from ...onnx.config import PatchingSpec
from ...tokenization_utils_base import PreTrainedTokenizerBase
a_ = logging.get_logger(__name__)
a_ = {
"allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json",
"allenai/longformer-large-4096": "https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json",
"allenai/longformer-large-4096-finetuned-triviaqa": (
"https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json"
),
"allenai/longformer-base-4096-extra.pos.embd.only": (
"https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json"
),
"allenai/longformer-large-4096-extra.pos.embd.only": (
"https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json"
),
}
class UpperCAmelCase_ ( snake_case__ ):
UpperCAmelCase_ = """longformer"""
def __init__( self , lowercase_ = 5_12 , lowercase_ = 2 , lowercase_ = 1 , lowercase_ = 0 , lowercase_ = 2 , lowercase_ = 3_05_22 , lowercase_ = 7_68 , lowercase_ = 12 , lowercase_ = 12 , lowercase_ = 30_72 , lowercase_ = "gelu" , lowercase_ = 0.1 , lowercase_ = 0.1 , lowercase_ = 5_12 , lowercase_ = 2 , lowercase_ = 0.02 , lowercase_ = 1E-12 , lowercase_ = False , **lowercase_ , ):
super().__init__(pad_token_id=lowercase_ , **lowercase_)
snake_case_ : Dict = attention_window
snake_case_ : Tuple = sep_token_id
snake_case_ : Optional[Any] = bos_token_id
snake_case_ : str = eos_token_id
snake_case_ : Optional[int] = vocab_size
snake_case_ : Dict = hidden_size
snake_case_ : Optional[Any] = num_hidden_layers
snake_case_ : int = num_attention_heads
snake_case_ : Union[str, Any] = hidden_act
snake_case_ : Union[str, Any] = intermediate_size
snake_case_ : Union[str, Any] = hidden_dropout_prob
snake_case_ : Optional[Any] = attention_probs_dropout_prob
snake_case_ : List[str] = max_position_embeddings
snake_case_ : str = type_vocab_size
snake_case_ : Tuple = initializer_range
snake_case_ : List[str] = layer_norm_eps
snake_case_ : Tuple = onnx_export
class UpperCAmelCase_ ( snake_case__ ):
def __init__( self , lowercase_ , lowercase_ = "default" , lowercase_ = None):
super().__init__(lowercase_ , lowercase_ , lowercase_)
snake_case_ : Dict = True
@property
def snake_case__ ( self):
if self.task == "multiple-choice":
snake_case_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"}
else:
snake_case_ : int = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
("global_attention_mask", dynamic_axis),
])
@property
def snake_case__ ( self):
snake_case_ : Union[str, Any] = super().outputs
if self.task == "default":
snake_case_ : str = {0: "batch"}
return outputs
@property
def snake_case__ ( self):
return 1E-4
@property
def snake_case__ ( self):
# needs to be >= 14 to support tril operator
return max(super().default_onnx_opset , 14)
def snake_case__ ( self , lowercase_ , lowercase_ = -1 , lowercase_ = -1 , lowercase_ = False , lowercase_ = None , ):
snake_case_ : Optional[Any] = super().generate_dummy_inputs(
preprocessor=lowercase_ , batch_size=lowercase_ , seq_length=lowercase_ , is_pair=lowercase_ , framework=lowercase_)
import torch
# for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64)
# makes the export fail randomly
snake_case_ : Any = torch.zeros_like(inputs["input_ids"])
# make every second token global
snake_case_ : Tuple = 1
return inputs
| 92 | 1 |
'''simple docstring'''
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxSeqaSeqConfigWithPast
from ...utils import logging
_SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
_SCREAMING_SNAKE_CASE = {
"t5-small": "https://huggingface.co/t5-small/resolve/main/config.json",
"t5-base": "https://huggingface.co/t5-base/resolve/main/config.json",
"t5-large": "https://huggingface.co/t5-large/resolve/main/config.json",
"t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json",
"t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json",
}
class lowerCAmelCase_ ( __magic_name__ ):
__lowerCamelCase : Union[str, Any] = "t5"
__lowerCamelCase : Optional[Any] = ["past_key_values"]
__lowerCamelCase : Dict = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"}
def __init__( self , _lowerCAmelCase=32128 , _lowerCAmelCase=512 , _lowerCAmelCase=64 , _lowerCAmelCase=2048 , _lowerCAmelCase=6 , _lowerCAmelCase=None , _lowerCAmelCase=8 , _lowerCAmelCase=32 , _lowerCAmelCase=128 , _lowerCAmelCase=0.1 , _lowerCAmelCase=1E-6 , _lowerCAmelCase=1.0 , _lowerCAmelCase="relu" , _lowerCAmelCase=True , _lowerCAmelCase=True , _lowerCAmelCase=0 , _lowerCAmelCase=1 , **_lowerCAmelCase , ) -> Optional[int]:
_lowerCAmelCase = vocab_size
_lowerCAmelCase = d_model
_lowerCAmelCase = d_kv
_lowerCAmelCase = d_ff
_lowerCAmelCase = num_layers
_lowerCAmelCase = (
num_decoder_layers if num_decoder_layers is not None else self.num_layers
) # default = symmetry
_lowerCAmelCase = num_heads
_lowerCAmelCase = relative_attention_num_buckets
_lowerCAmelCase = relative_attention_max_distance
_lowerCAmelCase = dropout_rate
_lowerCAmelCase = layer_norm_epsilon
_lowerCAmelCase = initializer_factor
_lowerCAmelCase = feed_forward_proj
_lowerCAmelCase = use_cache
_lowerCAmelCase = self.feed_forward_proj.split("-" )
_lowerCAmelCase = act_info[-1]
_lowerCAmelCase = act_info[0] == "gated"
if len(_lowerCAmelCase ) > 1 and act_info[0] != "gated" or len(_lowerCAmelCase ) > 2:
raise ValueError(
f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'''
"Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
"'gated-gelu' or 'relu'" )
# for backwards compatibility
if feed_forward_proj == "gated-gelu":
_lowerCAmelCase = "gelu_new"
super().__init__(
pad_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , is_encoder_decoder=_lowerCAmelCase , **_lowerCAmelCase , )
class lowerCAmelCase_ ( __magic_name__ ):
@property
def _snake_case ( self ) -> Mapping[str, Mapping[int, str]]:
_lowerCAmelCase = {
"input_ids": {0: "batch", 1: "encoder_sequence"},
"attention_mask": {0: "batch", 1: "encoder_sequence"},
}
if self.use_past:
_lowerCAmelCase = "past_encoder_sequence + sequence"
_lowerCAmelCase = {0: "batch"}
_lowerCAmelCase = {0: "batch", 1: "past_decoder_sequence + sequence"}
else:
_lowerCAmelCase = {0: "batch", 1: "decoder_sequence"}
_lowerCAmelCase = {0: "batch", 1: "decoder_sequence"}
if self.use_past:
self.fill_with_past_key_values_(_lowerCAmelCase , direction="inputs" )
return common_inputs
@property
def _snake_case ( self ) -> int:
return 13
| 18 |
'''simple docstring'''
from typing import Dict, Iterable, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_DEFAULT_MEAN,
IMAGENET_DEFAULT_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, logging
_SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
class lowerCAmelCase_ ( __magic_name__ ):
__lowerCamelCase : int = ["pixel_values"]
def __init__( self , _lowerCAmelCase = True , _lowerCAmelCase = None , _lowerCAmelCase = PILImageResampling.BICUBIC , _lowerCAmelCase = True , _lowerCAmelCase = None , _lowerCAmelCase = True , _lowerCAmelCase = 1 / 255 , _lowerCAmelCase = True , _lowerCAmelCase = IMAGENET_DEFAULT_MEAN , _lowerCAmelCase = IMAGENET_DEFAULT_STD , **_lowerCAmelCase , ) -> None:
super().__init__(**_lowerCAmelCase )
_lowerCAmelCase = size if size is not None else {"shortest_edge": 224}
_lowerCAmelCase = get_size_dict(_lowerCAmelCase , default_to_square=_lowerCAmelCase )
_lowerCAmelCase = crop_size if crop_size is not None else {"height": 224, "width": 224}
_lowerCAmelCase = get_size_dict(_lowerCAmelCase , param_name="crop_size" )
_lowerCAmelCase = do_resize
_lowerCAmelCase = size
_lowerCAmelCase = resample
_lowerCAmelCase = do_center_crop
_lowerCAmelCase = crop_size
_lowerCAmelCase = do_rescale
_lowerCAmelCase = rescale_factor
_lowerCAmelCase = do_normalize
_lowerCAmelCase = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
_lowerCAmelCase = image_std if image_std is not None else IMAGENET_DEFAULT_STD
def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = PILImageResampling.BICUBIC , _lowerCAmelCase = None , **_lowerCAmelCase , ) -> np.ndarray:
_lowerCAmelCase = get_size_dict(_lowerCAmelCase , default_to_square=_lowerCAmelCase )
# size_dict is a dict with either keys "height" and "width" or "shortest_edge"
if "shortest_edge" in size:
_lowerCAmelCase = int((256 / 224) * size["shortest_edge"] )
_lowerCAmelCase = get_resize_output_image_size(_lowerCAmelCase , size=_lowerCAmelCase , default_to_square=_lowerCAmelCase )
_lowerCAmelCase = {"height": output_size[0], "width": output_size[1]}
if "height" not in size_dict or "width" not in size_dict:
raise ValueError(
f'''Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}''' )
return resize(
_lowerCAmelCase , size=(size_dict["height"], size_dict["width"]) , resample=_lowerCAmelCase , data_format=_lowerCAmelCase , **_lowerCAmelCase )
def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = None , **_lowerCAmelCase , ) -> np.ndarray:
_lowerCAmelCase = get_size_dict(_lowerCAmelCase )
if "height" not in size or "width" not in size:
raise ValueError(f'''Size dict must have keys \'height\' and \'width\'. Got {size.keys()}''' )
return center_crop(_lowerCAmelCase , size=(size["height"], size["width"]) , data_format=_lowerCAmelCase , **_lowerCAmelCase )
def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = None , **_lowerCAmelCase , ) -> np.ndarray:
return rescale(_lowerCAmelCase , scale=_lowerCAmelCase , data_format=_lowerCAmelCase , **_lowerCAmelCase )
def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = None , **_lowerCAmelCase , ) -> np.ndarray:
return normalize(_lowerCAmelCase , mean=_lowerCAmelCase , std=_lowerCAmelCase , data_format=_lowerCAmelCase , **_lowerCAmelCase )
def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = ChannelDimension.FIRST , **_lowerCAmelCase , ) -> BatchFeature:
_lowerCAmelCase = do_resize if do_resize is not None else self.do_resize
_lowerCAmelCase = resample if resample is not None else self.resample
_lowerCAmelCase = do_center_crop if do_center_crop is not None else self.do_center_crop
_lowerCAmelCase = do_rescale if do_rescale is not None else self.do_rescale
_lowerCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor
_lowerCAmelCase = do_normalize if do_normalize is not None else self.do_normalize
_lowerCAmelCase = image_mean if image_mean is not None else self.image_mean
_lowerCAmelCase = image_std if image_std is not None else self.image_std
_lowerCAmelCase = size if size is not None else self.size
_lowerCAmelCase = get_size_dict(_lowerCAmelCase , default_to_square=_lowerCAmelCase )
_lowerCAmelCase = crop_size if crop_size is not None else self.crop_size
_lowerCAmelCase = get_size_dict(_lowerCAmelCase , param_name="crop_size" )
_lowerCAmelCase = make_list_of_images(_lowerCAmelCase )
if not valid_images(_lowerCAmelCase ):
raise ValueError(
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
"torch.Tensor, tf.Tensor or jax.ndarray." )
if do_resize and size is None:
raise ValueError("Size must be specified if do_resize is True." )
if do_center_crop and crop_size is None:
raise ValueError("Crop size must be specified if do_center_crop is True." )
if do_rescale and rescale_factor is None:
raise ValueError("Rescale factor must be specified if do_rescale is True." )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("Image mean and std must be specified if do_normalize is True." )
# All transformations expect numpy arrays.
_lowerCAmelCase = [to_numpy_array(_lowerCAmelCase ) for image in images]
if do_resize:
_lowerCAmelCase = [self.resize(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) for image in images]
if do_center_crop:
_lowerCAmelCase = [self.center_crop(_lowerCAmelCase , _lowerCAmelCase ) for image in images]
if do_rescale:
_lowerCAmelCase = [self.rescale(_lowerCAmelCase , _lowerCAmelCase ) for image in images]
if do_normalize:
_lowerCAmelCase = [self.normalize(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) for image in images]
_lowerCAmelCase = [to_channel_dimension_format(_lowerCAmelCase , _lowerCAmelCase ) for image in images]
_lowerCAmelCase = {"pixel_values": images}
return BatchFeature(data=_lowerCAmelCase , tensor_type=_lowerCAmelCase )
| 18 | 1 |
'''simple docstring'''
def __UpperCamelCase ( _A : int , _A : int ) -> int:
"""simple docstring"""
lowerCAmelCase : Dict = 1 # To kept the Calculated Value
# Since C(n, k) = C(n, n-k)
if k > (n - k):
lowerCAmelCase : Any = n - k
# Calculate C(n,k)
for i in range(_A ):
result *= n - i
result //= i + 1
return result
def __UpperCamelCase ( _A : int ) -> int:
"""simple docstring"""
return binomial_coefficient(2 * node_count , _A ) // (node_count + 1)
def __UpperCamelCase ( _A : int ) -> int:
"""simple docstring"""
if n < 0:
raise ValueError('factorial() not defined for negative values' )
lowerCAmelCase : int = 1
for i in range(1 , n + 1 ):
result *= i
return result
def __UpperCamelCase ( _A : int ) -> int:
"""simple docstring"""
return catalan_number(_A ) * factorial(_A )
if __name__ == "__main__":
_lowerCAmelCase : int = int(input('Enter the number of nodes: ').strip() or 0)
if node_count <= 0:
raise ValueError('We need some nodes to work with.')
print(
f"""Given {node_count} nodes, there are {binary_tree_count(node_count)} """
f"""binary trees and {catalan_number(node_count)} binary search trees."""
)
| 646 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
_lowerCAmelCase : Tuple = logging.get_logger(__name__)
_lowerCAmelCase : List[str] = {
'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 lowerCAmelCase ( a ):
_lowerCamelCase : int = """xmod"""
def __init__( self , snake_case__=3_0522 , snake_case__=768 , snake_case__=12 , snake_case__=12 , snake_case__=3072 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=512 , snake_case__=2 , snake_case__=0.0_2 , snake_case__=1e-1_2 , snake_case__=1 , snake_case__=0 , snake_case__=2 , snake_case__="absolute" , snake_case__=True , snake_case__=None , snake_case__=False , snake_case__=2 , snake_case__=False , snake_case__=True , snake_case__=True , snake_case__=("en_XX",) , snake_case__=None , **snake_case__ , ):
super().__init__(pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , **snake_case__ )
lowerCAmelCase : Dict = vocab_size
lowerCAmelCase : Optional[Any] = hidden_size
lowerCAmelCase : int = num_hidden_layers
lowerCAmelCase : List[Any] = num_attention_heads
lowerCAmelCase : List[Any] = hidden_act
lowerCAmelCase : Optional[int] = intermediate_size
lowerCAmelCase : Optional[int] = hidden_dropout_prob
lowerCAmelCase : Optional[Any] = attention_probs_dropout_prob
lowerCAmelCase : str = max_position_embeddings
lowerCAmelCase : int = type_vocab_size
lowerCAmelCase : List[Any] = initializer_range
lowerCAmelCase : Any = layer_norm_eps
lowerCAmelCase : Dict = position_embedding_type
lowerCAmelCase : Optional[Any] = use_cache
lowerCAmelCase : Union[str, Any] = classifier_dropout
lowerCAmelCase : int = pre_norm
lowerCAmelCase : Optional[Any] = adapter_reduction_factor
lowerCAmelCase : Any = adapter_layer_norm
lowerCAmelCase : Dict = adapter_reuse_layer_norm
lowerCAmelCase : Any = ln_before_adapter
lowerCAmelCase : Optional[Any] = list(snake_case__ )
lowerCAmelCase : List[Any] = default_language
class lowerCAmelCase ( a ):
@property
def lowercase ( self ):
if self.task == "multiple-choice":
lowerCAmelCase : List[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
lowerCAmelCase : Optional[int] = {0: 'batch', 1: 'sequence'}
return OrderedDict(
[
('input_ids', dynamic_axis),
('attention_mask', dynamic_axis),
] )
| 646 | 1 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
A : Tuple = logging.get_logger(__name__)
A : Optional[Any] = {
'weiweishi/roc-bert-base-zh': 'https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json',
}
class A ( UpperCAmelCase__ ):
'''simple docstring'''
A__ = '''roc_bert'''
def __init__(self : Union[str, Any] , _UpperCAmelCase : str=3_0522 , _UpperCAmelCase : List[str]=768 , _UpperCAmelCase : int=12 , _UpperCAmelCase : List[str]=12 , _UpperCAmelCase : Dict=3072 , _UpperCAmelCase : Optional[int]="gelu" , _UpperCAmelCase : Optional[Any]=0.1 , _UpperCAmelCase : Tuple=0.1 , _UpperCAmelCase : List[Any]=512 , _UpperCAmelCase : Tuple=2 , _UpperCAmelCase : str=0.02 , _UpperCAmelCase : Tuple=1E-1_2 , _UpperCAmelCase : Tuple=True , _UpperCAmelCase : List[Any]=0 , _UpperCAmelCase : List[Any]="absolute" , _UpperCAmelCase : str=None , _UpperCAmelCase : str=True , _UpperCAmelCase : Dict=True , _UpperCAmelCase : Optional[int]=768 , _UpperCAmelCase : List[str]=910 , _UpperCAmelCase : List[Any]=512 , _UpperCAmelCase : Optional[int]=2_4858 , _UpperCAmelCase : List[Any]=True , **_UpperCAmelCase : Any , ) -> List[str]:
"""simple docstring"""
lowercase__ = vocab_size
lowercase__ = max_position_embeddings
lowercase__ = hidden_size
lowercase__ = num_hidden_layers
lowercase__ = num_attention_heads
lowercase__ = intermediate_size
lowercase__ = hidden_act
lowercase__ = hidden_dropout_prob
lowercase__ = attention_probs_dropout_prob
lowercase__ = initializer_range
lowercase__ = type_vocab_size
lowercase__ = layer_norm_eps
lowercase__ = use_cache
lowercase__ = enable_pronunciation
lowercase__ = enable_shape
lowercase__ = pronunciation_embed_dim
lowercase__ = pronunciation_vocab_size
lowercase__ = shape_embed_dim
lowercase__ = shape_vocab_size
lowercase__ = concat_input
lowercase__ = position_embedding_type
lowercase__ = classifier_dropout
super().__init__(pad_token_id=_UpperCAmelCase , **_UpperCAmelCase )
| 15 |
import random
import unittest
import torch
from diffusers import IFInpaintingPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device
from ..pipeline_params import (
TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin
@skip_mps
class __SCREAMING_SNAKE_CASE ( A__ , A__ , unittest.TestCase ):
A : List[str] = IFInpaintingPipeline
A : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'width', 'height'}
A : Tuple = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
A : Optional[Any] = PipelineTesterMixin.required_optional_params - {'latents'}
def __lowerCamelCase ( self ):
return self._get_dummy_components()
def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0 ):
if str(SCREAMING_SNAKE_CASE__ ).startswith('''mps''' ):
lowercase : Tuple = torch.manual_seed(SCREAMING_SNAKE_CASE__ )
else:
lowercase : Dict = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ )
lowercase : Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ )
lowercase : int = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ )
lowercase : Tuple = {
'''prompt''': '''A painting of a squirrel eating a burger''',
'''image''': image,
'''mask_image''': mask_image,
'''generator''': generator,
'''num_inference_steps''': 2,
'''output_type''': '''numpy''',
}
return inputs
@unittest.skipIf(
torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , )
def __lowerCamelCase ( self ):
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 )
def __lowerCamelCase ( self ):
self._test_save_load_optional_components()
@unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' )
def __lowerCamelCase ( self ):
# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
super().test_save_load_floataa(expected_max_diff=1E-1 )
def __lowerCamelCase ( self ):
self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 )
def __lowerCamelCase ( self ):
self._test_save_load_local()
def __lowerCamelCase ( self ):
self._test_inference_batch_single_identical(
expected_max_diff=1E-2 , )
| 319 | 0 |
"""simple docstring"""
from __future__ import annotations
from math import gcd
def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int = 2 , SCREAMING_SNAKE_CASE : int = 1 , SCREAMING_SNAKE_CASE : int = 3 , ):
'''simple docstring'''
if num < 2:
raise ValueError("""The input value cannot be less than 2""" )
# Because of the relationship between ``f(f(x))`` and ``f(x)``, this
# algorithm struggles to find factors that are divisible by two.
# As a workaround, we specifically check for two and even inputs.
# See: https://math.stackexchange.com/a/2856214/165820
if num > 2 and num % 2 == 0:
return 2
# Pollard's Rho algorithm requires a function that returns pseudorandom
# values between 0 <= X < ``num``. It doesn't need to be random in the
# sense that the output value is cryptographically secure or difficult
# to calculate, it only needs to be random in the sense that all output
# values should be equally likely to appear.
# For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num``
# However, the success of Pollard's algorithm isn't guaranteed and is
# determined in part by the initial seed and the chosen random function.
# To make retries easier, we will instead use ``f(x) = (x**2 + C) % num``
# where ``C`` is a value that we can modify between each attempt.
def rand_fn(SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ) -> int:
return (pow(SCREAMING_SNAKE_CASE , 2 ) + step) % modulus
for _ in range(SCREAMING_SNAKE_CASE ):
# These track the position within the cycle detection logic.
lowerCAmelCase = seed
lowerCAmelCase = seed
while True:
# At each iteration, the tortoise moves one step and the hare moves two.
lowerCAmelCase = rand_fn(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
lowerCAmelCase = rand_fn(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
lowerCAmelCase = rand_fn(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
# At some point both the tortoise and the hare will enter a cycle whose
# length ``p`` is a divisor of ``num``. Once in that cycle, at some point
# the tortoise and hare will end up on the same value modulo ``p``.
# We can detect when this happens because the position difference between
# the tortoise and the hare will share a common divisor with ``num``.
lowerCAmelCase = gcd(hare - tortoise , SCREAMING_SNAKE_CASE )
if divisor == 1:
# No common divisor yet, just keep searching.
continue
else:
# We found a common divisor!
if divisor == num:
# Unfortunately, the divisor is ``num`` itself and is useless.
break
else:
# The divisor is a nontrivial factor of ``num``!
return divisor
# If we made it here, then this attempt failed.
# We need to pick a new starting seed for the tortoise and hare
# in addition to a new step value for the random function.
# To keep this example implementation deterministic, the
# new values will be generated based on currently available
# values instead of using something like ``random.randint``.
# We can use the hare's position as the new seed.
# This is actually what Richard Brent's the "optimized" variant does.
lowerCAmelCase = hare
# The new step value for the random function can just be incremented.
# At first the results will be similar to what the old function would
# have produced, but the value will quickly diverge after a bit.
step += 1
# We haven't found a divisor within the requested number of attempts.
# We were unlucky or ``num`` itself is actually prime.
return None
if __name__ == "__main__":
import argparse
SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser()
parser.add_argument(
"num",
type=int,
help="The value to find a divisor of",
)
parser.add_argument(
"--attempts",
type=int,
default=3,
help="The number of attempts before giving up",
)
SCREAMING_SNAKE_CASE__ = parser.parse_args()
SCREAMING_SNAKE_CASE__ = pollard_rho(args.num, attempts=args.attempts)
if divisor is None:
print(f'{args.num} is probably prime')
else:
SCREAMING_SNAKE_CASE__ = args.num // divisor
print(f'{args.num} = {divisor} * {quotient}')
| 708 |
"""simple docstring"""
import argparse
import intel_extension_for_pytorch as ipex
import torch
from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline
SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser("Stable Diffusion script with intel optimization", add_help=False)
parser.add_argument("--dpm", action="store_true", help="Enable DPMSolver or not")
parser.add_argument("--steps", default=None, type=int, help="Num inference steps")
SCREAMING_SNAKE_CASE__ = parser.parse_args()
SCREAMING_SNAKE_CASE__ = "cpu"
SCREAMING_SNAKE_CASE__ = "a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings"
SCREAMING_SNAKE_CASE__ = "path-to-your-trained-model"
SCREAMING_SNAKE_CASE__ = StableDiffusionPipeline.from_pretrained(model_id)
if args.dpm:
SCREAMING_SNAKE_CASE__ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
SCREAMING_SNAKE_CASE__ = pipe.to(device)
# to channels last
SCREAMING_SNAKE_CASE__ = pipe.unet.to(memory_format=torch.channels_last)
SCREAMING_SNAKE_CASE__ = pipe.vae.to(memory_format=torch.channels_last)
SCREAMING_SNAKE_CASE__ = pipe.text_encoder.to(memory_format=torch.channels_last)
if pipe.requires_safety_checker:
SCREAMING_SNAKE_CASE__ = pipe.safety_checker.to(memory_format=torch.channels_last)
# optimize with ipex
SCREAMING_SNAKE_CASE__ = torch.randn(2, 4, 64, 64)
SCREAMING_SNAKE_CASE__ = torch.rand(1) * 999
SCREAMING_SNAKE_CASE__ = torch.randn(2, 77, 768)
SCREAMING_SNAKE_CASE__ = (sample, timestep, encoder_hidden_status)
try:
SCREAMING_SNAKE_CASE__ = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example)
except Exception:
SCREAMING_SNAKE_CASE__ = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True)
SCREAMING_SNAKE_CASE__ = ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True)
SCREAMING_SNAKE_CASE__ = ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True)
if pipe.requires_safety_checker:
SCREAMING_SNAKE_CASE__ = ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True)
# compute
SCREAMING_SNAKE_CASE__ = 666
SCREAMING_SNAKE_CASE__ = torch.Generator(device).manual_seed(seed)
SCREAMING_SNAKE_CASE__ = {"generator": generator}
if args.steps is not None:
SCREAMING_SNAKE_CASE__ = args.steps
with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa):
SCREAMING_SNAKE_CASE__ = pipe(prompt, **generate_kwargs).images[0]
# save image
image.save("generated.png")
| 393 | 0 |
'''simple docstring'''
from datetime import datetime
import matplotlib.pyplot as plt
import torch
def __UpperCamelCase ( UpperCAmelCase ):
for param in module.parameters():
lowercase__ : str = False
def __UpperCamelCase ( ):
lowercase__ : str = '''cuda''' if torch.cuda.is_available() else '''cpu'''
if torch.backends.mps.is_available() and torch.backends.mps.is_built():
lowercase__ : Dict = '''mps'''
if device == "mps":
print(
'''WARNING: MPS currently doesn\'t seem to work, and messes up backpropagation without any visible torch'''
''' errors. I recommend using CUDA on a colab notebook or CPU instead if you\'re facing inexplicable issues'''
''' with generations.''' )
return device
def __UpperCamelCase ( UpperCAmelCase ):
lowercase__ : Tuple = plt.imshow(A__ )
fig.axes.get_xaxis().set_visible(A__ )
fig.axes.get_yaxis().set_visible(A__ )
plt.show()
def __UpperCamelCase ( ):
lowercase__ : Union[str, Any] = datetime.now()
lowercase__ : List[Any] = current_time.strftime('''%H:%M:%S''' )
return timestamp
| 152 |
'''simple docstring'''
from collections import OrderedDict
from typing import Any, Mapping, Optional
from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...file_utils import TensorType, is_torch_available
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging
lowerCAmelCase__ = logging.get_logger(__name__)
lowerCAmelCase__ = {
'''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json''',
# See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small
}
class lowercase_ (lowerCamelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Dict = 'blenderbot-small'
SCREAMING_SNAKE_CASE : int = ['past_key_values']
SCREAMING_SNAKE_CASE : List[str] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}
def __init__( self : Optional[int] ,lowercase__ : List[str]=5_0_2_6_5 ,lowercase__ : Optional[Any]=5_1_2 ,lowercase__ : Optional[int]=8 ,lowercase__ : List[Any]=2_0_4_8 ,lowercase__ : List[str]=1_6 ,lowercase__ : str=8 ,lowercase__ : Any=2_0_4_8 ,lowercase__ : Tuple=1_6 ,lowercase__ : Tuple=0.0 ,lowercase__ : List[str]=0.0 ,lowercase__ : Any=True ,lowercase__ : str=True ,lowercase__ : int="gelu" ,lowercase__ : Tuple=5_1_2 ,lowercase__ : List[Any]=0.1 ,lowercase__ : Tuple=0.0 ,lowercase__ : str=0.0 ,lowercase__ : Any=0.0_2 ,lowercase__ : Union[str, Any]=1 ,lowercase__ : List[Any]=False ,lowercase__ : Optional[int]=0 ,lowercase__ : Optional[int]=1 ,lowercase__ : str=2 ,lowercase__ : int=2 ,**lowercase__ : List[str] ,):
__lowercase = vocab_size
__lowercase = max_position_embeddings
__lowercase = d_model
__lowercase = encoder_ffn_dim
__lowercase = encoder_layers
__lowercase = encoder_attention_heads
__lowercase = decoder_ffn_dim
__lowercase = decoder_layers
__lowercase = decoder_attention_heads
__lowercase = dropout
__lowercase = attention_dropout
__lowercase = activation_dropout
__lowercase = activation_function
__lowercase = init_std
__lowercase = encoder_layerdrop
__lowercase = decoder_layerdrop
__lowercase = use_cache
__lowercase = encoder_layers
__lowercase = scale_embedding # scale factor will be sqrt(d_model) if True
super().__init__(
pad_token_id=lowercase__ ,bos_token_id=lowercase__ ,eos_token_id=lowercase__ ,is_encoder_decoder=lowercase__ ,decoder_start_token_id=lowercase__ ,forced_eos_token_id=lowercase__ ,**lowercase__ ,)
class lowercase_ (lowerCamelCase__ ):
"""simple docstring"""
@property
def SCREAMING_SNAKE_CASE ( self : Dict ):
if self.task in ["default", "seq2seq-lm"]:
__lowercase = OrderedDict(
[
('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
] )
if self.use_past:
__lowercase = {0: '''batch'''}
__lowercase = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''}
else:
__lowercase = {0: '''batch''', 1: '''decoder_sequence'''}
__lowercase = {0: '''batch''', 1: '''decoder_sequence'''}
if self.use_past:
self.fill_with_past_key_values_(lowercase__ ,direction='''inputs''' )
elif self.task == "causal-lm":
# TODO: figure this case out.
__lowercase = OrderedDict(
[
('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
] )
if self.use_past:
__lowercase , __lowercase = self.num_layers
for i in range(lowercase__ ):
__lowercase = {0: '''batch''', 2: '''past_sequence + sequence'''}
__lowercase = {0: '''batch''', 2: '''past_sequence + sequence'''}
else:
__lowercase = OrderedDict(
[
('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
('''decoder_input_ids''', {0: '''batch''', 1: '''decoder_sequence'''}),
('''decoder_attention_mask''', {0: '''batch''', 1: '''decoder_sequence'''}),
] )
return common_inputs
@property
def SCREAMING_SNAKE_CASE ( self : List[Any] ):
if self.task in ["default", "seq2seq-lm"]:
__lowercase = super().outputs
else:
__lowercase = super(lowercase__ ,self ).outputs
if self.use_past:
__lowercase , __lowercase = self.num_layers
for i in range(lowercase__ ):
__lowercase = {0: '''batch''', 2: '''past_sequence + sequence'''}
__lowercase = {0: '''batch''', 2: '''past_sequence + sequence'''}
return common_outputs
def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : PreTrainedTokenizer ,lowercase__ : int = -1 ,lowercase__ : int = -1 ,lowercase__ : bool = False ,lowercase__ : Optional[TensorType] = None ,):
__lowercase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ )
# Generate decoder inputs
__lowercase = seq_length if not self.use_past else 1
__lowercase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ )
__lowercase = {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
__lowercase = dict(**lowercase__ ,**lowercase__ )
if self.use_past:
if not is_torch_available():
raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' )
else:
import torch
__lowercase , __lowercase = common_inputs['''input_ids'''].shape
__lowercase = common_inputs['''decoder_input_ids'''].shape[1]
__lowercase , __lowercase = self.num_attention_heads
__lowercase = (
batch,
num_encoder_attention_heads,
encoder_seq_length,
self._config.hidden_size // num_encoder_attention_heads,
)
__lowercase = decoder_seq_length + 3
__lowercase = (
batch,
num_decoder_attention_heads,
decoder_past_length,
self._config.hidden_size // num_decoder_attention_heads,
)
__lowercase = torch.cat(
[common_inputs['''decoder_attention_mask'''], torch.ones(lowercase__ ,lowercase__ )] ,dim=1 )
__lowercase = []
# If the number of encoder and decoder layers are present in the model configuration, both are considered
__lowercase , __lowercase = self.num_layers
__lowercase = min(lowercase__ ,lowercase__ )
__lowercase = max(lowercase__ ,lowercase__ ) - min_num_layers
__lowercase = '''encoder''' if num_encoder_layers > num_decoder_layers else '''decoder'''
for _ in range(lowercase__ ):
common_inputs["past_key_values"].append(
(
torch.zeros(lowercase__ ),
torch.zeros(lowercase__ ),
torch.zeros(lowercase__ ),
torch.zeros(lowercase__ ),
) )
# TODO: test this.
__lowercase = encoder_shape if remaining_side_name == '''encoder''' else decoder_shape
for _ in range(lowercase__ ,lowercase__ ):
common_inputs["past_key_values"].append((torch.zeros(lowercase__ ), torch.zeros(lowercase__ )) )
return common_inputs
def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : PreTrainedTokenizer ,lowercase__ : int = -1 ,lowercase__ : int = -1 ,lowercase__ : bool = False ,lowercase__ : Optional[TensorType] = None ,):
__lowercase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ )
if self.use_past:
if not is_torch_available():
raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' )
else:
import torch
__lowercase , __lowercase = common_inputs['''input_ids'''].shape
# Not using the same length for past_key_values
__lowercase = seqlen + 2
__lowercase , __lowercase = self.num_layers
__lowercase , __lowercase = self.num_attention_heads
__lowercase = (
batch,
num_encoder_attention_heads,
past_key_values_length,
self._config.hidden_size // num_encoder_attention_heads,
)
__lowercase = common_inputs['''attention_mask'''].dtype
__lowercase = torch.cat(
[common_inputs['''attention_mask'''], torch.ones(lowercase__ ,lowercase__ ,dtype=lowercase__ )] ,dim=1 )
__lowercase = [
(torch.zeros(lowercase__ ), torch.zeros(lowercase__ )) for _ in range(lowercase__ )
]
return common_inputs
def SCREAMING_SNAKE_CASE ( self : List[str] ,lowercase__ : PreTrainedTokenizer ,lowercase__ : int = -1 ,lowercase__ : int = -1 ,lowercase__ : bool = False ,lowercase__ : Optional[TensorType] = None ,):
# Copied from OnnxConfig.generate_dummy_inputs
# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
__lowercase = compute_effective_axis_dimension(
lowercase__ ,fixed_dimension=OnnxConfig.default_fixed_batch ,num_token_to_add=0 )
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
__lowercase = tokenizer.num_special_tokens_to_add(lowercase__ )
__lowercase = compute_effective_axis_dimension(
lowercase__ ,fixed_dimension=OnnxConfig.default_fixed_sequence ,num_token_to_add=lowercase__ )
# Generate dummy inputs according to compute batch and sequence
__lowercase = [''' '''.join([tokenizer.unk_token] ) * seq_length] * batch_size
__lowercase = dict(tokenizer(lowercase__ ,return_tensors=lowercase__ ) )
return common_inputs
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,lowercase__ : PreTrainedTokenizer ,lowercase__ : int = -1 ,lowercase__ : int = -1 ,lowercase__ : bool = False ,lowercase__ : Optional[TensorType] = None ,):
if self.task in ["default", "seq2seq-lm"]:
__lowercase = self._generate_dummy_inputs_for_default_and_seqaseq_lm(
lowercase__ ,batch_size=lowercase__ ,seq_length=lowercase__ ,is_pair=lowercase__ ,framework=lowercase__ )
elif self.task == "causal-lm":
__lowercase = self._generate_dummy_inputs_for_causal_lm(
lowercase__ ,batch_size=lowercase__ ,seq_length=lowercase__ ,is_pair=lowercase__ ,framework=lowercase__ )
else:
__lowercase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
lowercase__ ,batch_size=lowercase__ ,seq_length=lowercase__ ,is_pair=lowercase__ ,framework=lowercase__ )
return common_inputs
def SCREAMING_SNAKE_CASE ( self : Tuple ,lowercase__ : List[Any] ,lowercase__ : Tuple ,lowercase__ : List[Any] ,lowercase__ : Optional[Any] ):
if self.task in ["default", "seq2seq-lm"]:
__lowercase = super()._flatten_past_key_values_(lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ )
else:
__lowercase = super(lowercase__ ,self )._flatten_past_key_values_(
lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ )
| 41 | 0 |
import unittest
import torch
from torch import nn
from accelerate.test_utils import require_cuda
from accelerate.utils.memory import find_executable_batch_size, release_memory
def __lowercase ( ) -> Optional[int]:
"""simple docstring"""
raise RuntimeError("""CUDA out of memory.""" )
class lowerCAmelCase_ ( nn.Module ):
"""simple docstring"""
def __init__( self : List[Any] ):
'''simple docstring'''
super().__init__()
__a = nn.Linear(3 , 4 )
__a = nn.BatchNormad(4 )
__a = nn.Linear(4 , 5 )
def __a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str ):
'''simple docstring'''
return self.lineara(self.batchnorm(self.lineara(SCREAMING_SNAKE_CASE__ ) ) )
class lowerCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
def __a ( self : Optional[Any] ):
'''simple docstring'''
__a = []
@find_executable_batch_size(starting_batch_size=1_2_8 )
def mock_training_loop_function(SCREAMING_SNAKE_CASE__ : List[str] ):
nonlocal batch_sizes
batch_sizes.append(SCREAMING_SNAKE_CASE__ )
if batch_size != 8:
raise_fake_out_of_memory()
mock_training_loop_function()
self.assertListEqual(SCREAMING_SNAKE_CASE__ , [1_2_8, 6_4, 3_2, 1_6, 8] )
def __a ( self : Tuple ):
'''simple docstring'''
__a = []
@find_executable_batch_size(starting_batch_size=1_2_8 )
def mock_training_loop_function(SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any ):
nonlocal batch_sizes
batch_sizes.append(SCREAMING_SNAKE_CASE__ )
if batch_size != 8:
raise_fake_out_of_memory()
return batch_size, arga
__a , __a = mock_training_loop_function("""hello""" )
self.assertListEqual(SCREAMING_SNAKE_CASE__ , [1_2_8, 6_4, 3_2, 1_6, 8] )
self.assertListEqual([bs, arga] , [8, """hello"""] )
def __a ( self : Tuple ):
'''simple docstring'''
@find_executable_batch_size(starting_batch_size=0 )
def mock_training_loop_function(SCREAMING_SNAKE_CASE__ : int ):
pass
with self.assertRaises(SCREAMING_SNAKE_CASE__ ) as cm:
mock_training_loop_function()
self.assertIn("""No executable batch size found, reached zero.""" , cm.exception.args[0] )
def __a ( self : List[Any] ):
'''simple docstring'''
@find_executable_batch_size(starting_batch_size=1_6 )
def mock_training_loop_function(SCREAMING_SNAKE_CASE__ : Optional[Any] ):
if batch_size > 0:
raise_fake_out_of_memory()
pass
with self.assertRaises(SCREAMING_SNAKE_CASE__ ) as cm:
mock_training_loop_function()
self.assertIn("""No executable batch size found, reached zero.""" , cm.exception.args[0] )
def __a ( self : List[str] ):
'''simple docstring'''
@find_executable_batch_size(starting_batch_size=1_2_8 )
def mock_training_loop_function(SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ):
if batch_size != 8:
raise raise_fake_out_of_memory()
with self.assertRaises(SCREAMING_SNAKE_CASE__ ) as cm:
mock_training_loop_function(1_2_8 , """hello""" , """world""" )
self.assertIn("""Batch size was passed into `f`""" , cm.exception.args[0] )
self.assertIn("""`f(arg1='hello', arg2='world')""" , cm.exception.args[0] )
def __a ( self : Optional[Any] ):
'''simple docstring'''
@find_executable_batch_size(starting_batch_size=1_6 )
def mock_training_loop_function(SCREAMING_SNAKE_CASE__ : Tuple ):
raise ValueError("""Oops, we had an error!""" )
with self.assertRaises(SCREAMING_SNAKE_CASE__ ) as cm:
mock_training_loop_function()
self.assertIn("""Oops, we had an error!""" , cm.exception.args[0] )
@require_cuda
def __a ( self : Dict ):
'''simple docstring'''
__a = torch.cuda.memory_allocated()
__a = ModelForTest()
model.cuda()
self.assertGreater(torch.cuda.memory_allocated() , SCREAMING_SNAKE_CASE__ )
__a = release_memory(SCREAMING_SNAKE_CASE__ )
self.assertEqual(torch.cuda.memory_allocated() , SCREAMING_SNAKE_CASE__ )
| 708 |
'''simple docstring'''
import inspect
import unittest
from transformers import ViTConfig
from transformers.testing_utils import (
require_accelerate,
require_torch,
require_torch_gpu,
require_vision,
slow,
torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class lowerCAmelCase_ :
"""simple docstring"""
def __init__( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str]=1_3 , SCREAMING_SNAKE_CASE__ : int=3_0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : str=3_2 , SCREAMING_SNAKE_CASE__ : Tuple=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Dict=3_7 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE__ : str=0.0_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Any=2 , ):
'''simple docstring'''
__a = parent
__a = batch_size
__a = image_size
__a = patch_size
__a = num_channels
__a = is_training
__a = use_labels
__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 = type_sequence_label_size
__a = initializer_range
__a = scope
__a = encoder_stride
# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
__a = (image_size // patch_size) ** 2
__a = num_patches + 1
def __a ( self : Any ):
'''simple docstring'''
__a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__a = None
if self.use_labels:
__a = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__a = self.get_config()
return config, pixel_values, labels
def __a ( self : Optional[int] ):
'''simple docstring'''
return ViTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , )
def __a ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] ):
'''simple docstring'''
__a = ViTModel(config=SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
__a = model(SCREAMING_SNAKE_CASE__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __a ( self : str , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : str ):
'''simple docstring'''
__a = ViTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
__a = model(SCREAMING_SNAKE_CASE__ )
self.parent.assertEqual(
result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) )
# test greyscale images
__a = 1
__a = ViTForMaskedImageModeling(SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
__a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
__a = model(SCREAMING_SNAKE_CASE__ )
self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) )
def __a ( self : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Dict ):
'''simple docstring'''
__a = self.type_sequence_label_size
__a = ViTForImageClassification(SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
__a = model(SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
__a = 1
__a = ViTForImageClassification(SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
__a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
__a = model(SCREAMING_SNAKE_CASE__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def __a ( self : str ):
'''simple docstring'''
__a = self.prepare_config_and_inputs()
(
(
__a
) , (
__a
) , (
__a
) ,
) = config_and_inputs
__a = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_torch
class lowerCAmelCase_ ( snake_case__ , snake_case__ , unittest.TestCase ):
"""simple docstring"""
a_ :str =(
(
ViTModel,
ViTForImageClassification,
ViTForMaskedImageModeling,
)
if is_torch_available()
else ()
)
a_ :Tuple =(
{"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification}
if is_torch_available()
else {}
)
a_ :List[str] =True
a_ :str =False
a_ :Optional[int] =False
a_ :Tuple =False
def __a ( self : str ):
'''simple docstring'''
__a = ViTModelTester(self )
__a = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=3_7 )
def __a ( self : Dict ):
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason="""ViT does not use inputs_embeds""" )
def __a ( self : List[Any] ):
'''simple docstring'''
pass
def __a ( self : int ):
'''simple docstring'''
__a , __a = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__a = model_class(SCREAMING_SNAKE_CASE__ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
__a = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) )
def __a ( self : int ):
'''simple docstring'''
__a , __a = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__a = model_class(SCREAMING_SNAKE_CASE__ )
__a = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__a = [*signature.parameters.keys()]
__a = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ )
def __a ( self : List[str] ):
'''simple docstring'''
__a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ )
def __a ( self : Union[str, Any] ):
'''simple docstring'''
__a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE__ )
def __a ( self : Optional[Any] ):
'''simple docstring'''
__a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ )
@slow
def __a ( self : List[str] ):
'''simple docstring'''
for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__a = ViTModel.from_pretrained(SCREAMING_SNAKE_CASE__ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
def __lowercase ( ) -> int:
"""simple docstring"""
__a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
return image
@require_torch
@require_vision
class lowerCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def __a ( self : str ):
'''simple docstring'''
return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None
@slow
def __a ( self : Dict ):
'''simple docstring'''
__a = ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ).to(SCREAMING_SNAKE_CASE__ )
__a = self.default_image_processor
__a = prepare_img()
__a = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE__ )
# forward pass
with torch.no_grad():
__a = model(**SCREAMING_SNAKE_CASE__ )
# verify the logits
__a = torch.Size((1, 1_0_0_0) )
self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ )
__a = torch.tensor([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6] ).to(SCREAMING_SNAKE_CASE__ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) )
@slow
def __a ( self : int ):
'''simple docstring'''
__a = ViTModel.from_pretrained("""facebook/dino-vits8""" ).to(SCREAMING_SNAKE_CASE__ )
__a = ViTImageProcessor.from_pretrained("""facebook/dino-vits8""" , size=4_8_0 )
__a = prepare_img()
__a = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" )
__a = inputs.pixel_values.to(SCREAMING_SNAKE_CASE__ )
# forward pass
with torch.no_grad():
__a = model(SCREAMING_SNAKE_CASE__ , interpolate_pos_encoding=SCREAMING_SNAKE_CASE__ )
# verify the logits
__a = torch.Size((1, 3_6_0_1, 3_8_4) )
self.assertEqual(outputs.last_hidden_state.shape , SCREAMING_SNAKE_CASE__ )
__a = torch.tensor(
[[4.2_3_4_0, 4.3_9_0_6, -6.6_6_9_2], [4.5_4_6_3, 1.8_9_2_8, -6.7_2_5_7], [4.4_4_2_9, 0.8_4_9_6, -5.8_5_8_5]] ).to(SCREAMING_SNAKE_CASE__ )
self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) )
@slow
@require_accelerate
@require_torch_gpu
def __a ( self : Optional[Any] ):
'''simple docstring'''
__a = ViTModel.from_pretrained("""facebook/dino-vits8""" , torch_dtype=torch.floataa , device_map="""auto""" )
__a = self.default_image_processor
__a = prepare_img()
__a = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" )
__a = inputs.pixel_values.to(SCREAMING_SNAKE_CASE__ )
# forward pass to make sure inference works in fp16
with torch.no_grad():
__a = model(SCREAMING_SNAKE_CASE__ )
| 201 | 0 |
import warnings
from typing import List
import numpy as np
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available
class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ):
'''simple docstring'''
_lowerCamelCase = ['''image_processor''', '''tokenizer''']
_lowerCamelCase = '''OwlViTImageProcessor'''
_lowerCamelCase = ('''CLIPTokenizer''', '''CLIPTokenizerFast''')
def __init__( self : Union[str, Any] , lowerCamelCase : List[Any]=None , lowerCamelCase : Optional[int]=None , **lowerCamelCase : int ) -> Any:
"""simple docstring"""
_UpperCAmelCase = None
if "feature_extractor" in kwargs:
warnings.warn(
"""The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
""" instead.""" , lowerCamelCase , )
_UpperCAmelCase = kwargs.pop("""feature_extractor""" )
_UpperCAmelCase = 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__(lowerCamelCase , lowerCamelCase )
def __call__( self : Optional[Any] , lowerCamelCase : Optional[Any]=None , lowerCamelCase : Optional[int]=None , lowerCamelCase : str=None , lowerCamelCase : List[Any]="max_length" , lowerCamelCase : List[Any]="np" , **lowerCamelCase : Union[str, Any] ) -> Any:
"""simple docstring"""
if text is None and query_images is None and images is None:
raise ValueError(
"""You have to specify at least one text or query image or image. All three cannot be none.""" )
if text is not None:
if isinstance(lowerCamelCase , lowerCamelCase ) or (isinstance(lowerCamelCase , lowerCamelCase ) and not isinstance(text[0] , lowerCamelCase )):
_UpperCAmelCase = [self.tokenizer(lowerCamelCase , padding=lowerCamelCase , return_tensors=lowerCamelCase , **lowerCamelCase )]
elif isinstance(lowerCamelCase , lowerCamelCase ) and isinstance(text[0] , lowerCamelCase ):
_UpperCAmelCase = []
# Maximum number of queries across batch
_UpperCAmelCase = max([len(lowerCamelCase ) for t in text] )
# Pad all batch samples to max number of text queries
for t in text:
if len(lowerCamelCase ) != max_num_queries:
_UpperCAmelCase = t + [""" """] * (max_num_queries - len(lowerCamelCase ))
_UpperCAmelCase = self.tokenizer(lowerCamelCase , padding=lowerCamelCase , return_tensors=lowerCamelCase , **lowerCamelCase )
encodings.append(lowerCamelCase )
else:
raise TypeError("""Input text should be a string, a list of strings or a nested list of strings""" )
if return_tensors == "np":
_UpperCAmelCase = np.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 )
_UpperCAmelCase = np.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 )
elif return_tensors == "jax" and is_flax_available():
import jax.numpy as jnp
_UpperCAmelCase = jnp.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 )
_UpperCAmelCase = jnp.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 )
elif return_tensors == "pt" and is_torch_available():
import torch
_UpperCAmelCase = torch.cat([encoding["""input_ids"""] for encoding in encodings] , dim=0 )
_UpperCAmelCase = torch.cat([encoding["""attention_mask"""] for encoding in encodings] , dim=0 )
elif return_tensors == "tf" and is_tf_available():
import tensorflow as tf
_UpperCAmelCase = tf.stack([encoding["""input_ids"""] for encoding in encodings] , axis=0 )
_UpperCAmelCase = tf.stack([encoding["""attention_mask"""] for encoding in encodings] , axis=0 )
else:
raise ValueError("""Target return tensor type could not be returned""" )
_UpperCAmelCase = BatchEncoding()
_UpperCAmelCase = input_ids
_UpperCAmelCase = attention_mask
if query_images is not None:
_UpperCAmelCase = BatchEncoding()
_UpperCAmelCase = self.image_processor(
lowerCamelCase , return_tensors=lowerCamelCase , **lowerCamelCase ).pixel_values
_UpperCAmelCase = query_pixel_values
if images is not None:
_UpperCAmelCase = self.image_processor(lowerCamelCase , return_tensors=lowerCamelCase , **lowerCamelCase )
if text is not None and images is not None:
_UpperCAmelCase = image_features.pixel_values
return encoding
elif query_images is not None and images is not None:
_UpperCAmelCase = image_features.pixel_values
return encoding
elif text is not None or query_images is not None:
return encoding
else:
return BatchEncoding(data=dict(**lowerCamelCase ) , tensor_type=lowerCamelCase )
def lowerCamelCase ( self : List[Any] , *lowerCamelCase : Dict , **lowerCamelCase : Any ) -> Union[str, Any]:
"""simple docstring"""
return self.image_processor.post_process(*lowerCamelCase , **lowerCamelCase )
def lowerCamelCase ( self : List[str] , *lowerCamelCase : Union[str, Any] , **lowerCamelCase : Optional[Any] ) -> List[Any]:
"""simple docstring"""
return self.image_processor.post_process_object_detection(*lowerCamelCase , **lowerCamelCase )
def lowerCamelCase ( self : List[Any] , *lowerCamelCase : int , **lowerCamelCase : Tuple ) -> List[str]:
"""simple docstring"""
return self.image_processor.post_process_image_guided_detection(*lowerCamelCase , **lowerCamelCase )
def lowerCamelCase ( self : Dict , *lowerCamelCase : Union[str, Any] , **lowerCamelCase : Dict ) -> Union[str, Any]:
"""simple docstring"""
return self.tokenizer.batch_decode(*lowerCamelCase , **lowerCamelCase )
def lowerCamelCase ( self : int , *lowerCamelCase : List[Any] , **lowerCamelCase : Tuple ) -> int:
"""simple docstring"""
return self.tokenizer.decode(*lowerCamelCase , **lowerCamelCase )
@property
def lowerCamelCase ( self : List[str] ) -> List[Any]:
"""simple docstring"""
warnings.warn(
"""`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , lowerCamelCase , )
return self.image_processor_class
@property
def lowerCamelCase ( self : List[str] ) -> Union[str, Any]:
"""simple docstring"""
warnings.warn(
"""`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , lowerCamelCase , )
return self.image_processor | 108 |
import unittest
from transformers import DebertaVaConfig, 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
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
DebertaVaForMaskedLM,
DebertaVaForMultipleChoice,
DebertaVaForQuestionAnswering,
DebertaVaForSequenceClassification,
DebertaVaForTokenClassification,
DebertaVaModel,
)
from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST
class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ):
'''simple docstring'''
def __init__( self : Union[str, Any] , lowerCamelCase : str , lowerCamelCase : Optional[Any]=13 , lowerCamelCase : List[Any]=7 , lowerCamelCase : List[Any]=True , lowerCamelCase : str=True , lowerCamelCase : List[str]=True , lowerCamelCase : List[str]=True , lowerCamelCase : Optional[int]=99 , lowerCamelCase : int=32 , lowerCamelCase : str=5 , lowerCamelCase : str=4 , lowerCamelCase : List[str]=37 , lowerCamelCase : str="gelu" , lowerCamelCase : Dict=0.1 , lowerCamelCase : Any=0.1 , lowerCamelCase : Union[str, Any]=512 , lowerCamelCase : Optional[int]=16 , lowerCamelCase : Any=2 , lowerCamelCase : Any=0.02 , lowerCamelCase : List[Any]=False , lowerCamelCase : Optional[Any]=True , lowerCamelCase : Optional[int]="None" , lowerCamelCase : Tuple=3 , lowerCamelCase : int=4 , lowerCamelCase : Optional[Any]=None , ) -> Optional[int]:
"""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 = relative_attention
_UpperCAmelCase = position_biased_input
_UpperCAmelCase = pos_att_type
_UpperCAmelCase = scope
def lowerCamelCase ( self : str ) -> 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 = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 )
_UpperCAmelCase = None
if self.use_token_type_ids:
_UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
_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, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def lowerCamelCase ( self : Dict ) -> Dict:
"""simple docstring"""
return DebertaVaConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , )
def lowerCamelCase ( self : Union[str, Any] , lowerCamelCase : List[Any] ) -> Union[str, Any]:
"""simple docstring"""
self.parent.assertListEqual(list(result.loss.size() ) , [] )
def lowerCamelCase ( self : Optional[Any] , lowerCamelCase : int , lowerCamelCase : List[Any] , lowerCamelCase : int , lowerCamelCase : Union[str, Any] , lowerCamelCase : List[str] , lowerCamelCase : List[str] , lowerCamelCase : Any ) -> List[Any]:
"""simple docstring"""
_UpperCAmelCase = DebertaVaModel(config=lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
_UpperCAmelCase = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase )[0]
_UpperCAmelCase = model(lowerCamelCase , token_type_ids=lowerCamelCase )[0]
_UpperCAmelCase = model(lowerCamelCase )[0]
self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] )
def lowerCamelCase ( self : List[str] , lowerCamelCase : Any , lowerCamelCase : Optional[int] , lowerCamelCase : int , lowerCamelCase : Tuple , lowerCamelCase : Optional[Any] , lowerCamelCase : List[str] , lowerCamelCase : List[Any] ) -> List[str]:
"""simple docstring"""
_UpperCAmelCase = DebertaVaForMaskedLM(config=lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
_UpperCAmelCase = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def lowerCamelCase ( self : str , lowerCamelCase : Optional[Any] , lowerCamelCase : List[str] , lowerCamelCase : Dict , lowerCamelCase : List[Any] , lowerCamelCase : List[str] , lowerCamelCase : Optional[Any] , lowerCamelCase : Any ) -> Union[str, Any]:
"""simple docstring"""
_UpperCAmelCase = self.num_labels
_UpperCAmelCase = DebertaVaForSequenceClassification(lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
_UpperCAmelCase = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase )
self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] )
self.check_loss_output(lowerCamelCase )
def lowerCamelCase ( self : Dict , lowerCamelCase : List[str] , lowerCamelCase : int , lowerCamelCase : Optional[Any] , lowerCamelCase : Dict , lowerCamelCase : Union[str, Any] , lowerCamelCase : Optional[int] , lowerCamelCase : Union[str, Any] ) -> Tuple:
"""simple docstring"""
_UpperCAmelCase = self.num_labels
_UpperCAmelCase = DebertaVaForTokenClassification(config=lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
_UpperCAmelCase = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def lowerCamelCase ( self : Any , lowerCamelCase : Tuple , lowerCamelCase : Any , lowerCamelCase : str , lowerCamelCase : Tuple , lowerCamelCase : Optional[int] , lowerCamelCase : Optional[Any] , lowerCamelCase : str ) -> Tuple:
"""simple docstring"""
_UpperCAmelCase = DebertaVaForQuestionAnswering(config=lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
_UpperCAmelCase = model(
lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=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 lowerCamelCase ( self : Dict , lowerCamelCase : List[str] , lowerCamelCase : str , lowerCamelCase : Any , lowerCamelCase : Tuple , lowerCamelCase : Optional[Any] , lowerCamelCase : Any , lowerCamelCase : str ) -> str:
"""simple docstring"""
_UpperCAmelCase = DebertaVaForMultipleChoice(config=lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
_UpperCAmelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_UpperCAmelCase = token_type_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 , token_type_ids=lowerCamelCase , labels=lowerCamelCase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def lowerCamelCase ( self : List[str] ) -> Optional[int]:
"""simple docstring"""
_UpperCAmelCase = self.prepare_config_and_inputs()
(
(
_UpperCAmelCase
) , (
_UpperCAmelCase
) , (
_UpperCAmelCase
) , (
_UpperCAmelCase
) , (
_UpperCAmelCase
) , (
_UpperCAmelCase
) , (
_UpperCAmelCase
) ,
) = config_and_inputs
_UpperCAmelCase = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ):
'''simple docstring'''
_lowerCamelCase = (
(
DebertaVaModel,
DebertaVaForMaskedLM,
DebertaVaForSequenceClassification,
DebertaVaForTokenClassification,
DebertaVaForQuestionAnswering,
DebertaVaForMultipleChoice,
)
if is_torch_available()
else ()
)
_lowerCamelCase = (
{
'''feature-extraction''': DebertaVaModel,
'''fill-mask''': DebertaVaForMaskedLM,
'''question-answering''': DebertaVaForQuestionAnswering,
'''text-classification''': DebertaVaForSequenceClassification,
'''token-classification''': DebertaVaForTokenClassification,
'''zero-shot''': DebertaVaForSequenceClassification,
}
if is_torch_available()
else {}
)
_lowerCamelCase = True
_lowerCamelCase = False
_lowerCamelCase = False
_lowerCamelCase = False
_lowerCamelCase = False
def lowerCamelCase ( self : int ) -> List[str]:
"""simple docstring"""
_UpperCAmelCase = DebertaVaModelTester(self )
_UpperCAmelCase = ConfigTester(self , config_class=lowerCamelCase , hidden_size=37 )
def lowerCamelCase ( self : Optional[int] ) -> Tuple:
"""simple docstring"""
self.config_tester.run_common_tests()
def lowerCamelCase ( self : Tuple ) -> Tuple:
"""simple docstring"""
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_model(*lowerCamelCase )
def lowerCamelCase ( self : List[Any] ) -> Any:
"""simple docstring"""
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_sequence_classification(*lowerCamelCase )
def lowerCamelCase ( self : Union[str, Any] ) -> List[str]:
"""simple docstring"""
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_masked_lm(*lowerCamelCase )
def lowerCamelCase ( self : Tuple ) -> Tuple:
"""simple docstring"""
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_question_answering(*lowerCamelCase )
def lowerCamelCase ( self : Dict ) -> List[str]:
"""simple docstring"""
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_token_classification(*lowerCamelCase )
def lowerCamelCase ( self : int ) -> List[Any]:
"""simple docstring"""
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_multiple_choice(*lowerCamelCase )
@slow
def lowerCamelCase ( self : Dict ) -> Optional[int]:
"""simple docstring"""
for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCAmelCase = DebertaVaModel.from_pretrained(lowerCamelCase )
self.assertIsNotNone(lowerCamelCase )
@require_torch
@require_sentencepiece
@require_tokenizers
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
'''simple docstring'''
@unittest.skip(reason="""Model not available yet""" )
def lowerCamelCase ( self : Any ) -> Tuple:
"""simple docstring"""
pass
@slow
def lowerCamelCase ( self : Union[str, Any] ) -> int:
"""simple docstring"""
_UpperCAmelCase = DebertaVaModel.from_pretrained("""microsoft/deberta-v2-xlarge""" )
_UpperCAmelCase = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] )
_UpperCAmelCase = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
with torch.no_grad():
_UpperCAmelCase = model(lowerCamelCase , attention_mask=lowerCamelCase )[0]
# compare the actual values for a slice.
_UpperCAmelCase = torch.tensor(
[[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] )
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , lowerCamelCase , atol=1E-4 ) , f"""{output[:, 1:4, 1:4]}""" ) | 108 | 1 |
"""simple docstring"""
import tempfile
import unittest
import numpy as np
from diffusers import (
DDIMScheduler,
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
OnnxStableDiffusionPipeline,
PNDMScheduler,
)
from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu
from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin
if is_onnx_available():
import onnxruntime as ort
class UpperCAmelCase ( __SCREAMING_SNAKE_CASE,unittest.TestCase ):
A__ : Optional[Any] = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'''
def __UpperCAmelCase ( self : List[str] , __lowerCamelCase : List[str]=0 ):
"""simple docstring"""
_snake_case = np.random.RandomState(__lowerCamelCase )
_snake_case = {
'''prompt''': '''A painting of a squirrel eating a burger''',
'''generator''': generator,
'''num_inference_steps''': 2,
'''guidance_scale''': 7.5,
'''output_type''': '''numpy''',
}
return inputs
def __UpperCAmelCase ( self : List[Any] ):
"""simple docstring"""
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' )
pipe.set_progress_bar_config(disable=__lowerCamelCase )
_snake_case = self.get_dummy_inputs()
_snake_case = pipe(**__lowerCamelCase ).images
_snake_case = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
_snake_case = np.array([0.6_5_0_7_2, 0.5_8_4_9_2, 0.4_8_2_1_9, 0.5_5_5_2_1, 0.5_3_1_8_0, 0.5_5_9_3_9, 0.5_0_6_9_7, 0.3_9_8_0_0, 0.4_6_4_5_5] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def __UpperCAmelCase ( self : Dict ):
"""simple docstring"""
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' )
_snake_case = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__lowerCamelCase )
pipe.set_progress_bar_config(disable=__lowerCamelCase )
_snake_case = self.get_dummy_inputs()
_snake_case = pipe(**__lowerCamelCase ).images
_snake_case = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
_snake_case = np.array([0.6_5_8_6_3, 0.5_9_4_2_5, 0.4_9_3_2_6, 0.5_6_3_1_3, 0.5_3_8_7_5, 0.5_6_6_2_7, 0.5_1_0_6_5, 0.3_9_7_7_7, 0.4_6_3_3_0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def __UpperCAmelCase ( self : List[Any] ):
"""simple docstring"""
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' )
_snake_case = LMSDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=__lowerCamelCase )
_snake_case = self.get_dummy_inputs()
_snake_case = pipe(**__lowerCamelCase ).images
_snake_case = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
_snake_case = np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def __UpperCAmelCase ( self : Optional[Any] ):
"""simple docstring"""
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' )
_snake_case = EulerDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=__lowerCamelCase )
_snake_case = self.get_dummy_inputs()
_snake_case = pipe(**__lowerCamelCase ).images
_snake_case = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
_snake_case = np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def __UpperCAmelCase ( self : List[Any] ):
"""simple docstring"""
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' )
_snake_case = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=__lowerCamelCase )
_snake_case = self.get_dummy_inputs()
_snake_case = pipe(**__lowerCamelCase ).images
_snake_case = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
_snake_case = np.array([0.5_3_8_1_7, 0.6_0_8_1_2, 0.4_7_3_8_4, 0.4_9_5_3_0, 0.5_1_8_9_4, 0.4_9_8_1_4, 0.4_7_9_8_4, 0.3_8_9_5_8, 0.4_4_2_7_1] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def __UpperCAmelCase ( self : Dict ):
"""simple docstring"""
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' )
_snake_case = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=__lowerCamelCase )
_snake_case = self.get_dummy_inputs()
_snake_case = pipe(**__lowerCamelCase ).images
_snake_case = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
_snake_case = np.array([0.5_3_8_9_5, 0.6_0_8_0_8, 0.4_7_9_3_3, 0.4_9_6_0_8, 0.5_1_8_8_6, 0.4_9_9_5_0, 0.4_8_0_5_3, 0.3_8_9_5_7, 0.4_4_2_0_0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def __UpperCAmelCase ( self : List[str] ):
"""simple docstring"""
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' )
pipe.set_progress_bar_config(disable=__lowerCamelCase )
_snake_case = self.get_dummy_inputs()
_snake_case = 3 * [inputs['''prompt''']]
# forward
_snake_case = pipe(**__lowerCamelCase )
_snake_case = output.images[0, -3:, -3:, -1]
_snake_case = self.get_dummy_inputs()
_snake_case = 3 * [inputs.pop('''prompt''' )]
_snake_case = pipe.tokenizer(
__lowerCamelCase , padding='''max_length''' , max_length=pipe.tokenizer.model_max_length , truncation=__lowerCamelCase , return_tensors='''np''' , )
_snake_case = text_inputs['''input_ids''']
_snake_case = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0]
_snake_case = prompt_embeds
# forward
_snake_case = pipe(**__lowerCamelCase )
_snake_case = output.images[0, -3:, -3:, -1]
assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4
def __UpperCAmelCase ( self : List[Any] ):
"""simple docstring"""
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' )
pipe.set_progress_bar_config(disable=__lowerCamelCase )
_snake_case = self.get_dummy_inputs()
_snake_case = 3 * ['''this is a negative prompt''']
_snake_case = negative_prompt
_snake_case = 3 * [inputs['''prompt''']]
# forward
_snake_case = pipe(**__lowerCamelCase )
_snake_case = output.images[0, -3:, -3:, -1]
_snake_case = self.get_dummy_inputs()
_snake_case = 3 * [inputs.pop('''prompt''' )]
_snake_case = []
for p in [prompt, negative_prompt]:
_snake_case = pipe.tokenizer(
__lowerCamelCase , padding='''max_length''' , max_length=pipe.tokenizer.model_max_length , truncation=__lowerCamelCase , return_tensors='''np''' , )
_snake_case = text_inputs['''input_ids''']
embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] )
_snake_case , _snake_case = embeds
# forward
_snake_case = pipe(**__lowerCamelCase )
_snake_case = output.images[0, -3:, -3:, -1]
assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4
@nightly
@require_onnxruntime
@require_torch_gpu
class UpperCAmelCase ( unittest.TestCase ):
@property
def __UpperCAmelCase ( self : int ):
"""simple docstring"""
return (
"CUDAExecutionProvider",
{
"gpu_mem_limit": "15000000000", # 15GB
"arena_extend_strategy": "kSameAsRequested",
},
)
@property
def __UpperCAmelCase ( self : str ):
"""simple docstring"""
_snake_case = ort.SessionOptions()
_snake_case = False
return options
def __UpperCAmelCase ( self : Optional[Any] ):
"""simple docstring"""
# using the PNDM scheduler by default
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(
'''CompVis/stable-diffusion-v1-4''' , revision='''onnx''' , safety_checker=__lowerCamelCase , feature_extractor=__lowerCamelCase , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=__lowerCamelCase )
_snake_case = '''A painting of a squirrel eating a burger'''
np.random.seed(0 )
_snake_case = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=1_0 , output_type='''np''' )
_snake_case = output.images
_snake_case = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_1_2, 5_1_2, 3)
_snake_case = np.array([0.0_4_5_2, 0.0_3_9_0, 0.0_0_8_7, 0.0_3_5_0, 0.0_6_1_7, 0.0_3_6_4, 0.0_5_4_4, 0.0_5_2_3, 0.0_7_2_0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def __UpperCAmelCase ( self : Dict ):
"""simple docstring"""
_snake_case = DDIMScheduler.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , subfolder='''scheduler''' , revision='''onnx''' )
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , revision='''onnx''' , scheduler=__lowerCamelCase , safety_checker=__lowerCamelCase , feature_extractor=__lowerCamelCase , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=__lowerCamelCase )
_snake_case = '''open neural network exchange'''
_snake_case = np.random.RandomState(0 )
_snake_case = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=1_0 , generator=__lowerCamelCase , output_type='''np''' )
_snake_case = output.images
_snake_case = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_1_2, 5_1_2, 3)
_snake_case = np.array([0.2_8_6_7, 0.1_9_7_4, 0.1_4_8_1, 0.7_2_9_4, 0.7_2_5_1, 0.6_6_6_7, 0.4_1_9_4, 0.5_6_4_2, 0.6_4_8_6] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def __UpperCAmelCase ( self : int ):
"""simple docstring"""
_snake_case = LMSDiscreteScheduler.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , subfolder='''scheduler''' , revision='''onnx''' )
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , revision='''onnx''' , scheduler=__lowerCamelCase , safety_checker=__lowerCamelCase , feature_extractor=__lowerCamelCase , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=__lowerCamelCase )
_snake_case = '''open neural network exchange'''
_snake_case = np.random.RandomState(0 )
_snake_case = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=1_0 , generator=__lowerCamelCase , output_type='''np''' )
_snake_case = output.images
_snake_case = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_1_2, 5_1_2, 3)
_snake_case = np.array([0.2_3_0_6, 0.1_9_5_9, 0.1_5_9_3, 0.6_5_4_9, 0.6_3_9_4, 0.5_4_0_8, 0.5_0_6_5, 0.6_0_1_0, 0.6_1_6_1] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def __UpperCAmelCase ( self : List[Any] ):
"""simple docstring"""
_snake_case = 0
def test_callback_fn(__lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : np.ndarray ) -> None:
_snake_case = True
nonlocal number_of_steps
number_of_steps += 1
if step == 0:
assert latents.shape == (1, 4, 6_4, 6_4)
_snake_case = latents[0, -3:, -3:, -1]
_snake_case = np.array(
[-0.6_7_7_2, -0.3_8_3_5, -1.2_4_5_6, 0.1_9_0_5, -1.0_9_7_4, 0.6_9_6_7, -1.9_3_5_3, 0.0_1_7_8, 1.0_1_6_7] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3
elif step == 5:
assert latents.shape == (1, 4, 6_4, 6_4)
_snake_case = latents[0, -3:, -3:, -1]
_snake_case = np.array(
[-0.3_3_5_1, 0.2_2_4_1, -0.1_8_3_7, -0.2_3_2_5, -0.6_5_7_7, 0.3_3_9_3, -0.0_2_4_1, 0.5_8_9_9, 1.3_8_7_5] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3
_snake_case = False
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , revision='''onnx''' , safety_checker=__lowerCamelCase , feature_extractor=__lowerCamelCase , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=__lowerCamelCase )
_snake_case = '''Andromeda galaxy in a bottle'''
_snake_case = np.random.RandomState(0 )
pipe(
prompt=__lowerCamelCase , num_inference_steps=5 , guidance_scale=7.5 , generator=__lowerCamelCase , callback=__lowerCamelCase , callback_steps=1 , )
assert test_callback_fn.has_been_called
assert number_of_steps == 6
def __UpperCAmelCase ( self : Any ):
"""simple docstring"""
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , revision='''onnx''' , safety_checker=__lowerCamelCase , feature_extractor=__lowerCamelCase , provider=self.gpu_provider , sess_options=self.gpu_options , )
assert isinstance(__lowerCamelCase , __lowerCamelCase )
assert pipe.safety_checker is None
_snake_case = pipe('''example prompt''' , num_inference_steps=2 ).images[0]
assert image is not None
# check that there's no error when saving a pipeline with one of the models being None
with tempfile.TemporaryDirectory() as tmpdirname:
pipe.save_pretrained(__lowerCamelCase )
_snake_case = OnnxStableDiffusionPipeline.from_pretrained(__lowerCamelCase )
# sanity check that the pipeline still works
assert pipe.safety_checker is None
_snake_case = pipe('''example prompt''' , num_inference_steps=2 ).images[0]
assert image is not None
| 404 |
"""simple docstring"""
def snake_case ( ) -> Tuple:
_snake_case = 0
for i in range(1 , 1001 ):
total += i**i
return str(lowerCAmelCase_ )[-10:]
if __name__ == "__main__":
print(solution())
| 404 | 1 |
from math import acos, sin
from typing import List, Tuple, Union
import numpy as np
import torch
from PIL import Image
from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel
class UpperCAmelCase ( __snake_case ):
lowercase = ["""vqvae"""]
def __init__( self : List[str] , __magic_name__ : AutoencoderKL , __magic_name__ : UNetaDConditionModel , __magic_name__ : Mel , __magic_name__ : Union[DDIMScheduler, DDPMScheduler] , ):
"""simple docstring"""
super().__init__()
self.register_modules(unet=__magic_name__ , scheduler=__magic_name__ , mel=__magic_name__ , vqvae=__magic_name__ )
def lowerCamelCase_ ( self : Optional[Any] ):
"""simple docstring"""
return 5_0 if isinstance(self.scheduler , __magic_name__ ) else 1_0_0_0
@torch.no_grad()
def __call__( self : Optional[int] , __magic_name__ : int = 1 , __magic_name__ : str = None , __magic_name__ : np.ndarray = None , __magic_name__ : int = 0 , __magic_name__ : int = 0 , __magic_name__ : int = None , __magic_name__ : torch.Generator = None , __magic_name__ : float = 0 , __magic_name__ : float = 0 , __magic_name__ : torch.Generator = None , __magic_name__ : float = 0 , __magic_name__ : torch.Tensor = None , __magic_name__ : torch.Tensor = None , __magic_name__ : Optional[Any]=True , ):
"""simple docstring"""
UpperCamelCase = steps or self.get_default_steps()
self.scheduler.set_timesteps(__magic_name__ )
UpperCamelCase = step_generator or generator
# For backwards compatibility
if type(self.unet.config.sample_size ) == int:
UpperCamelCase = (self.unet.config.sample_size, self.unet.config.sample_size)
if noise is None:
UpperCamelCase = randn_tensor(
(
batch_size,
self.unet.config.in_channels,
self.unet.config.sample_size[0],
self.unet.config.sample_size[1],
) , generator=__magic_name__ , device=self.device , )
UpperCamelCase = noise
UpperCamelCase = None
if audio_file is not None or raw_audio is not None:
self.mel.load_audio(__magic_name__ , __magic_name__ )
UpperCamelCase = self.mel.audio_slice_to_image(__magic_name__ )
UpperCamelCase = np.frombuffer(input_image.tobytes() , dtype="""uint8""" ).reshape(
(input_image.height, input_image.width) )
UpperCamelCase = (input_image / 2_5_5) * 2 - 1
UpperCamelCase = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device )
if self.vqvae is not None:
UpperCamelCase = self.vqvae.encode(torch.unsqueeze(__magic_name__ , 0 ) ).latent_dist.sample(
generator=__magic_name__ )[0]
UpperCamelCase = self.vqvae.config.scaling_factor * input_images
if start_step > 0:
UpperCamelCase = self.scheduler.add_noise(__magic_name__ , __magic_name__ , self.scheduler.timesteps[start_step - 1] )
UpperCamelCase = (
self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
)
UpperCamelCase = int(mask_start_secs * pixels_per_second )
UpperCamelCase = int(mask_end_secs * pixels_per_second )
UpperCamelCase = self.scheduler.add_noise(__magic_name__ , __magic_name__ , torch.tensor(self.scheduler.timesteps[start_step:] ) )
for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ):
if isinstance(self.unet , __magic_name__ ):
UpperCamelCase = self.unet(__magic_name__ , __magic_name__ , __magic_name__ )["""sample"""]
else:
UpperCamelCase = self.unet(__magic_name__ , __magic_name__ )["""sample"""]
if isinstance(self.scheduler , __magic_name__ ):
UpperCamelCase = self.scheduler.step(
model_output=__magic_name__ , timestep=__magic_name__ , sample=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , )["""prev_sample"""]
else:
UpperCamelCase = self.scheduler.step(
model_output=__magic_name__ , timestep=__magic_name__ , sample=__magic_name__ , generator=__magic_name__ , )["""prev_sample"""]
if mask is not None:
if mask_start > 0:
UpperCamelCase = mask[:, step, :, :mask_start]
if mask_end > 0:
UpperCamelCase = mask[:, step, :, -mask_end:]
if self.vqvae is not None:
# 0.18215 was scaling factor used in training to ensure unit variance
UpperCamelCase = 1 / self.vqvae.config.scaling_factor * images
UpperCamelCase = self.vqvae.decode(__magic_name__ )["""sample"""]
UpperCamelCase = (images / 2 + 0.5).clamp(0 , 1 )
UpperCamelCase = images.cpu().permute(0 , 2 , 3 , 1 ).numpy()
UpperCamelCase = (images * 2_5_5).round().astype("""uint8""" )
UpperCamelCase = list(
(Image.fromarray(_[:, :, 0] ) for _ in images)
if images.shape[3] == 1
else (Image.fromarray(__magic_name__ , mode="""RGB""" ).convert("""L""" ) for _ in images) )
UpperCamelCase = [self.mel.image_to_audio(__magic_name__ ) for _ in images]
if not return_dict:
return images, (self.mel.get_sample_rate(), audios)
return BaseOutput(**AudioPipelineOutput(np.array(__magic_name__ )[:, np.newaxis, :] ) , **ImagePipelineOutput(__magic_name__ ) )
@torch.no_grad()
def lowerCamelCase_ ( self : Tuple , __magic_name__ : List[Image.Image] , __magic_name__ : int = 5_0 ):
"""simple docstring"""
assert isinstance(self.scheduler , __magic_name__ )
self.scheduler.set_timesteps(__magic_name__ )
UpperCamelCase = np.array(
[np.frombuffer(image.tobytes() , dtype="""uint8""" ).reshape((1, image.height, image.width) ) for image in images] )
UpperCamelCase = (sample / 2_5_5) * 2 - 1
UpperCamelCase = torch.Tensor(__magic_name__ ).to(self.device )
for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ):
UpperCamelCase = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
UpperCamelCase = self.scheduler.alphas_cumprod[t]
UpperCamelCase = (
self.scheduler.alphas_cumprod[prev_timestep]
if prev_timestep >= 0
else self.scheduler.final_alpha_cumprod
)
UpperCamelCase = 1 - alpha_prod_t
UpperCamelCase = self.unet(__magic_name__ , __magic_name__ )["""sample"""]
UpperCamelCase = (1 - alpha_prod_t_prev) ** 0.5 * model_output
UpperCamelCase = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
UpperCamelCase = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output
return sample
@staticmethod
def lowerCamelCase_ ( __magic_name__ : torch.Tensor , __magic_name__ : torch.Tensor , __magic_name__ : float ):
"""simple docstring"""
UpperCamelCase = acos(torch.dot(torch.flatten(__magic_name__ ) , torch.flatten(__magic_name__ ) ) / torch.norm(__magic_name__ ) / torch.norm(__magic_name__ ) )
return sin((1 - alpha) * theta ) * xa / sin(__magic_name__ ) + sin(alpha * theta ) * xa / sin(__magic_name__ )
| 386 |
def _lowercase ( SCREAMING_SNAKE_CASE_ : int = 10 , SCREAMING_SNAKE_CASE_ : int = 22 ):
"""simple docstring"""
UpperCamelCase = range(1 , SCREAMING_SNAKE_CASE_ )
UpperCamelCase = range(1 , SCREAMING_SNAKE_CASE_ )
return sum(
1 for power in powers for base in bases if len(str(base**power ) ) == power )
if __name__ == "__main__":
print(F'''{solution(10, 22) = }''')
| 386 | 1 |
'''simple docstring'''
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError
from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
sys.path.append(str(Path(__file__).parent.parent / "utils"))
from test_module.custom_image_processing import CustomImageProcessor # noqa E402
__UpperCAmelCase = get_tests_dir("fixtures")
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: List[str] = mock.Mock()
snake_case: Any = 5_00
snake_case: int = {}
snake_case: Union[str, Any] = HTTPError
snake_case: int = {}
# Download this model to make sure it's in the cache.
snake_case: List[Any] = ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit' )
# Under the mock environment we get a 500 error when trying to reach the model.
with mock.patch('requests.Session.request' , return_value=SCREAMING_SNAKE_CASE__ ) as mock_head:
snake_case: Optional[int] = ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit' )
# This check we did call the fake head request
mock_head.assert_called()
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: Optional[int] = ViTImageProcessor.from_pretrained(
'https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json' )
def _UpperCamelCase ( self ):
'''simple docstring'''
with self.assertRaises(SCREAMING_SNAKE_CASE__ ):
# config is in subfolder, the following should not work without specifying the subfolder
snake_case: Union[str, Any] = AutoImageProcessor.from_pretrained('hf-internal-testing/stable-diffusion-all-variants' )
snake_case: Dict = AutoImageProcessor.from_pretrained(
'hf-internal-testing/stable-diffusion-all-variants' , subfolder='feature_extractor' )
self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
@is_staging_test
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
@classmethod
def _UpperCamelCase ( cls ):
'''simple docstring'''
snake_case: List[str] = TOKEN
HfFolder.save_token(SCREAMING_SNAKE_CASE__ )
@classmethod
def _UpperCamelCase ( cls ):
'''simple docstring'''
try:
delete_repo(token=cls._token , repo_id='test-image-processor' )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id='valid_org/test-image-processor-org' )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id='test-dynamic-image-processor' )
except HTTPError:
pass
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: Dict = ViTImageProcessor.from_pretrained(SCREAMING_SNAKE_CASE__ )
image_processor.push_to_hub('test-image-processor' , use_auth_token=self._token )
snake_case: List[Any] = ViTImageProcessor.from_pretrained(F"""{USER}/test-image-processor""" )
for k, v in image_processor.__dict__.items():
self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
# Reset repo
delete_repo(token=self._token , repo_id='test-image-processor' )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(
SCREAMING_SNAKE_CASE__ , repo_id='test-image-processor' , push_to_hub=SCREAMING_SNAKE_CASE__ , use_auth_token=self._token )
snake_case: Dict = ViTImageProcessor.from_pretrained(F"""{USER}/test-image-processor""" )
for k, v in image_processor.__dict__.items():
self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: Optional[int] = ViTImageProcessor.from_pretrained(SCREAMING_SNAKE_CASE__ )
image_processor.push_to_hub('valid_org/test-image-processor' , use_auth_token=self._token )
snake_case: int = ViTImageProcessor.from_pretrained('valid_org/test-image-processor' )
for k, v in image_processor.__dict__.items():
self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
# Reset repo
delete_repo(token=self._token , repo_id='valid_org/test-image-processor' )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(
SCREAMING_SNAKE_CASE__ , repo_id='valid_org/test-image-processor-org' , push_to_hub=SCREAMING_SNAKE_CASE__ , use_auth_token=self._token )
snake_case: Union[str, Any] = ViTImageProcessor.from_pretrained('valid_org/test-image-processor-org' )
for k, v in image_processor.__dict__.items():
self.assertEqual(SCREAMING_SNAKE_CASE__ , getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
def _UpperCamelCase ( self ):
'''simple docstring'''
CustomImageProcessor.register_for_auto_class()
snake_case: List[Any] = CustomImageProcessor.from_pretrained(SCREAMING_SNAKE_CASE__ )
image_processor.push_to_hub('test-dynamic-image-processor' , use_auth_token=self._token )
# This has added the proper auto_map field to the config
self.assertDictEqual(
image_processor.auto_map , {'AutoImageProcessor': 'custom_image_processing.CustomImageProcessor'} , )
snake_case: List[Any] = AutoImageProcessor.from_pretrained(
F"""{USER}/test-dynamic-image-processor""" , trust_remote_code=SCREAMING_SNAKE_CASE__ )
# Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
self.assertEqual(new_image_processor.__class__.__name__ , 'CustomImageProcessor' ) | 692 |
'''simple docstring'''
import os
import warnings
from typing import List, Optional
from ...tokenization_utils_base import BatchEncoding
from ...utils import logging
from .configuration_rag import RagConfig
__UpperCAmelCase = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
snake_case: Dict = question_encoder
snake_case: Union[str, Any] = generator
snake_case: Optional[int] = self.question_encoder
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
if os.path.isfile(SCREAMING_SNAKE_CASE__ ):
raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""" )
os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ )
snake_case: Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , 'question_encoder_tokenizer' )
snake_case: Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , 'generator_tokenizer' )
self.question_encoder.save_pretrained(SCREAMING_SNAKE_CASE__ )
self.generator.save_pretrained(SCREAMING_SNAKE_CASE__ )
@classmethod
def _UpperCamelCase ( cls , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
from ..auto.tokenization_auto import AutoTokenizer
snake_case: int = kwargs.pop('config' , SCREAMING_SNAKE_CASE__ )
if config is None:
snake_case: str = RagConfig.from_pretrained(SCREAMING_SNAKE_CASE__ )
snake_case: Optional[int] = AutoTokenizer.from_pretrained(
SCREAMING_SNAKE_CASE__ , config=config.question_encoder , subfolder='question_encoder_tokenizer' )
snake_case: Dict = AutoTokenizer.from_pretrained(
SCREAMING_SNAKE_CASE__ , config=config.generator , subfolder='generator_tokenizer' )
return cls(question_encoder=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ )
def __call__( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
return self.current_tokenizer(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
def _UpperCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
return self.generator.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
def _UpperCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
return self.generator.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: Union[str, Any] = self.question_encoder
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: Dict = self.generator
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "longest" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = True , **SCREAMING_SNAKE_CASE__ , ):
'''simple docstring'''
warnings.warn(
'`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the '
'regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` '
'context manager to prepare your targets. See the documentation of your specific tokenizer for more '
'details' , SCREAMING_SNAKE_CASE__ , )
if max_length is None:
snake_case: Optional[Any] = self.current_tokenizer.model_max_length
snake_case: int = self(
SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
if tgt_texts is None:
return model_inputs
# Process tgt_texts
if max_target_length is None:
snake_case: Any = self.current_tokenizer.model_max_length
snake_case: List[str] = self(
text_target=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
snake_case: Dict = labels['input_ids']
return model_inputs | 692 | 1 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCAmelCase__ = logging.get_logger(__name__)
lowerCAmelCase__ = {
'google/switch-base-8': 'https://huggingface.co/google/switch-base-8/blob/main/config.json',
}
class snake_case ( __lowercase ):
UpperCAmelCase__ = '''switch_transformers'''
UpperCAmelCase__ = ['''past_key_values''']
UpperCAmelCase__ = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''}
def __init__(self , SCREAMING_SNAKE_CASE_=3_21_28 , SCREAMING_SNAKE_CASE_=7_68 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=20_48 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=8 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=0.01 , SCREAMING_SNAKE_CASE_="float32" , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=1_28 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=1e-6 , SCREAMING_SNAKE_CASE_=0.0_01 , SCREAMING_SNAKE_CASE_=0.0_01 , SCREAMING_SNAKE_CASE_=1.0 , SCREAMING_SNAKE_CASE_="relu" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , **SCREAMING_SNAKE_CASE_ , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = d_model
SCREAMING_SNAKE_CASE_ = d_kv
SCREAMING_SNAKE_CASE_ = d_ff
SCREAMING_SNAKE_CASE_ = num_sparse_encoder_layers
SCREAMING_SNAKE_CASE_ = num_layers
SCREAMING_SNAKE_CASE_ = (
num_decoder_layers if num_decoder_layers is not None else self.num_layers
) # default = symmetry
SCREAMING_SNAKE_CASE_ = num_sparse_decoder_layers
# This tells us, each how many encoder layer we'll have to set a sparse layer.
if self.num_sparse_encoder_layers > 0:
SCREAMING_SNAKE_CASE_ = self.num_layers // self.num_sparse_encoder_layers
else:
SCREAMING_SNAKE_CASE_ = self.num_layers # HACK: this will create 0 sparse layers
# This tells us, each how many encoder layer we'll have to set a sparse layer.
if self.num_sparse_decoder_layers > 0:
SCREAMING_SNAKE_CASE_ = self.num_decoder_layers // self.num_sparse_decoder_layers
else:
SCREAMING_SNAKE_CASE_ = self.num_decoder_layers # HACK: this will create 0 sparse layers
SCREAMING_SNAKE_CASE_ = num_heads
SCREAMING_SNAKE_CASE_ = num_experts
SCREAMING_SNAKE_CASE_ = expert_capacity
SCREAMING_SNAKE_CASE_ = router_bias
SCREAMING_SNAKE_CASE_ = router_jitter_noise
if router_dtype not in ["float32", "float16", "bfloat16"]:
raise ValueError(f'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}' )
SCREAMING_SNAKE_CASE_ = router_dtype
SCREAMING_SNAKE_CASE_ = router_ignore_padding_tokens
SCREAMING_SNAKE_CASE_ = relative_attention_num_buckets
SCREAMING_SNAKE_CASE_ = relative_attention_max_distance
SCREAMING_SNAKE_CASE_ = dropout_rate
SCREAMING_SNAKE_CASE_ = layer_norm_epsilon
SCREAMING_SNAKE_CASE_ = initializer_factor
SCREAMING_SNAKE_CASE_ = feed_forward_proj
SCREAMING_SNAKE_CASE_ = use_cache
SCREAMING_SNAKE_CASE_ = add_router_probs
SCREAMING_SNAKE_CASE_ = router_z_loss_coef
SCREAMING_SNAKE_CASE_ = router_aux_loss_coef
SCREAMING_SNAKE_CASE_ = self.feed_forward_proj.split('''-''' )
SCREAMING_SNAKE_CASE_ = act_info[-1]
SCREAMING_SNAKE_CASE_ = act_info[0] == '''gated'''
if len(SCREAMING_SNAKE_CASE_ ) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE_ ) > 2:
raise ValueError(
f'`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'
'''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '''
'''\'gated-gelu\' or \'relu\'''' )
# for backwards compatibility
if feed_forward_proj == "gated-gelu":
SCREAMING_SNAKE_CASE_ = '''gelu_new'''
super().__init__(
pad_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) | 626 |
"""simple docstring"""
import collections.abc
from typing import Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_poolformer import PoolFormerConfig
lowerCAmelCase__ = logging.get_logger(__name__)
# General docstring
lowerCAmelCase__ = 'PoolFormerConfig'
# Base docstring
lowerCAmelCase__ = 'sail/poolformer_s12'
lowerCAmelCase__ = [1, 512, 7, 7]
# Image classification docstring
lowerCAmelCase__ = 'sail/poolformer_s12'
lowerCAmelCase__ = 'tabby, tabby cat'
lowerCAmelCase__ = [
'sail/poolformer_s12',
# See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]
def _lowerCamelCase ( __a, __a = 0.0, __a = False ):
if drop_prob == 0.0 or not training:
return input
SCREAMING_SNAKE_CASE_ = 1 - drop_prob
SCREAMING_SNAKE_CASE_ = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
SCREAMING_SNAKE_CASE_ = keep_prob + torch.rand(__a, dtype=input.dtype, device=input.device )
random_tensor.floor_() # binarize
SCREAMING_SNAKE_CASE_ = input.div(__a ) * random_tensor
return output
class snake_case ( nn.Module ):
def __init__(self , SCREAMING_SNAKE_CASE_ = None ):
"""simple docstring"""
super().__init__()
SCREAMING_SNAKE_CASE_ = drop_prob
def _lowercase (self , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
return drop_path(SCREAMING_SNAKE_CASE_ , self.drop_prob , self.training )
def _lowercase (self ):
"""simple docstring"""
return "p={}".format(self.drop_prob )
class snake_case ( nn.Module ):
def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ):
"""simple docstring"""
super().__init__()
SCREAMING_SNAKE_CASE_ = patch_size if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.Iterable ) else (patch_size, patch_size)
SCREAMING_SNAKE_CASE_ = stride if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.Iterable ) else (stride, stride)
SCREAMING_SNAKE_CASE_ = padding if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.Iterable ) else (padding, padding)
SCREAMING_SNAKE_CASE_ = nn.Convad(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , kernel_size=SCREAMING_SNAKE_CASE_ , stride=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = norm_layer(SCREAMING_SNAKE_CASE_ ) if norm_layer else nn.Identity()
def _lowercase (self , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = self.projection(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = self.norm(SCREAMING_SNAKE_CASE_ )
return embeddings
class snake_case ( nn.GroupNorm ):
def __init__(self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
super().__init__(1 , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
class snake_case ( nn.Module ):
def __init__(self , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
super().__init__()
SCREAMING_SNAKE_CASE_ = nn.AvgPoolad(SCREAMING_SNAKE_CASE_ , stride=1 , padding=pool_size // 2 , count_include_pad=SCREAMING_SNAKE_CASE_ )
def _lowercase (self , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
return self.pool(SCREAMING_SNAKE_CASE_ ) - hidden_states
class snake_case ( nn.Module ):
def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
super().__init__()
SCREAMING_SNAKE_CASE_ = nn.Convad(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 )
SCREAMING_SNAKE_CASE_ = nn.Convad(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 )
SCREAMING_SNAKE_CASE_ = PoolFormerDropPath(SCREAMING_SNAKE_CASE_ )
if isinstance(config.hidden_act , SCREAMING_SNAKE_CASE_ ):
SCREAMING_SNAKE_CASE_ = ACTaFN[config.hidden_act]
else:
SCREAMING_SNAKE_CASE_ = config.hidden_act
def _lowercase (self , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = self.conva(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = self.act_fn(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = self.drop(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = self.conva(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = self.drop(SCREAMING_SNAKE_CASE_ )
return hidden_states
class snake_case ( nn.Module ):
def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
super().__init__()
SCREAMING_SNAKE_CASE_ = PoolFormerPooling(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = PoolFormerOutput(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE_ )
# Useful for training neural nets
SCREAMING_SNAKE_CASE_ = PoolFormerDropPath(SCREAMING_SNAKE_CASE_ ) if drop_path > 0.0 else nn.Identity()
SCREAMING_SNAKE_CASE_ = config.use_layer_scale
if config.use_layer_scale:
SCREAMING_SNAKE_CASE_ = nn.Parameter(
config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE_) ) , requires_grad=SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = nn.Parameter(
config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE_) ) , requires_grad=SCREAMING_SNAKE_CASE_ )
def _lowercase (self , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
if self.use_layer_scale:
SCREAMING_SNAKE_CASE_ = self.pooling(self.before_norm(SCREAMING_SNAKE_CASE_ ) )
SCREAMING_SNAKE_CASE_ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output
# First residual connection
SCREAMING_SNAKE_CASE_ = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = ()
SCREAMING_SNAKE_CASE_ = self.output(self.after_norm(SCREAMING_SNAKE_CASE_ ) )
SCREAMING_SNAKE_CASE_ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output
# Second residual connection
SCREAMING_SNAKE_CASE_ = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = (output,) + outputs
return outputs
else:
SCREAMING_SNAKE_CASE_ = self.drop_path(self.pooling(self.before_norm(SCREAMING_SNAKE_CASE_ ) ) )
# First residual connection
SCREAMING_SNAKE_CASE_ = pooling_output + hidden_states
SCREAMING_SNAKE_CASE_ = ()
# Second residual connection inside the PoolFormerOutput block
SCREAMING_SNAKE_CASE_ = self.drop_path(self.output(self.after_norm(SCREAMING_SNAKE_CASE_ ) ) )
SCREAMING_SNAKE_CASE_ = hidden_states + layer_output
SCREAMING_SNAKE_CASE_ = (output,) + outputs
return outputs
class snake_case ( nn.Module ):
def __init__(self , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
super().__init__()
SCREAMING_SNAKE_CASE_ = config
# stochastic depth decay rule
SCREAMING_SNAKE_CASE_ = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )]
# patch embeddings
SCREAMING_SNAKE_CASE_ = []
for i in range(config.num_encoder_blocks ):
embeddings.append(
PoolFormerEmbeddings(
patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) )
SCREAMING_SNAKE_CASE_ = nn.ModuleList(SCREAMING_SNAKE_CASE_ )
# Transformer blocks
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
for i in range(config.num_encoder_blocks ):
# each block consists of layers
SCREAMING_SNAKE_CASE_ = []
if i != 0:
cur += config.depths[i - 1]
for j in range(config.depths[i] ):
layers.append(
PoolFormerLayer(
SCREAMING_SNAKE_CASE_ , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) )
blocks.append(nn.ModuleList(SCREAMING_SNAKE_CASE_ ) )
SCREAMING_SNAKE_CASE_ = nn.ModuleList(SCREAMING_SNAKE_CASE_ )
def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = () if output_hidden_states else None
SCREAMING_SNAKE_CASE_ = pixel_values
for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ):
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = layers
# Get patch embeddings from hidden_states
SCREAMING_SNAKE_CASE_ = embedding_layer(SCREAMING_SNAKE_CASE_ )
# Send the embeddings through the blocks
for _, blk in enumerate(SCREAMING_SNAKE_CASE_ ):
SCREAMING_SNAKE_CASE_ = blk(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = layer_outputs[0]
if output_hidden_states:
SCREAMING_SNAKE_CASE_ = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, all_hidden_states] if v is not None )
return BaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE_ , hidden_states=SCREAMING_SNAKE_CASE_ )
class snake_case ( __lowercase ):
UpperCAmelCase__ = PoolFormerConfig
UpperCAmelCase__ = '''poolformer'''
UpperCAmelCase__ = '''pixel_values'''
UpperCAmelCase__ = True
def _lowercase (self , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
if isinstance(SCREAMING_SNAKE_CASE_ , (nn.Linear, nn.Convad) ):
module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range )
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(SCREAMING_SNAKE_CASE_ , nn.LayerNorm ):
module.bias.data.zero_()
module.weight.data.fill_(1.0 )
def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ):
"""simple docstring"""
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
SCREAMING_SNAKE_CASE_ = value
lowerCAmelCase__ = r'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'
lowerCAmelCase__ = r'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n'
@add_start_docstrings(
'''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.''' , __lowercase , )
class snake_case ( __lowercase ):
def __init__(self , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
super().__init__(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = config
SCREAMING_SNAKE_CASE_ = PoolFormerEncoder(SCREAMING_SNAKE_CASE_ )
# Initialize weights and apply final processing
self.post_init()
def _lowercase (self ):
"""simple docstring"""
return self.embeddings.patch_embeddings
@add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE_ )
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC , output_type=SCREAMING_SNAKE_CASE_ , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , )
def _lowercase (self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
SCREAMING_SNAKE_CASE_ = return_dict if return_dict is not None else self.config.use_return_dict
if pixel_values is None:
raise ValueError('''You have to specify pixel_values''' )
SCREAMING_SNAKE_CASE_ = self.encoder(
SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )
SCREAMING_SNAKE_CASE_ = encoder_outputs[0]
if not return_dict:
return (sequence_output, None) + encoder_outputs[1:]
return BaseModelOutputWithNoAttention(
last_hidden_state=SCREAMING_SNAKE_CASE_ , hidden_states=encoder_outputs.hidden_states , )
class snake_case ( nn.Module ):
def __init__(self , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
super().__init__()
SCREAMING_SNAKE_CASE_ = nn.Linear(config.hidden_size , config.hidden_size )
def _lowercase (self , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = self.dense(SCREAMING_SNAKE_CASE_ )
return output
@add_start_docstrings(
'''
PoolFormer Model transformer with an image classification head on top
''' , __lowercase , )
class snake_case ( __lowercase ):
def __init__(self , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
super().__init__(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = config.num_labels
SCREAMING_SNAKE_CASE_ = PoolFormerModel(SCREAMING_SNAKE_CASE_ )
# Final norm
SCREAMING_SNAKE_CASE_ = PoolFormerGroupNorm(config.hidden_sizes[-1] )
# Classifier head
SCREAMING_SNAKE_CASE_ = (
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(SCREAMING_SNAKE_CASE_ )
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=SCREAMING_SNAKE_CASE_ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , )
def _lowercase (self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = return_dict if return_dict is not None else self.config.use_return_dict
SCREAMING_SNAKE_CASE_ = self.poolformer(
SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )
SCREAMING_SNAKE_CASE_ = outputs[0]
SCREAMING_SNAKE_CASE_ = self.classifier(self.norm(SCREAMING_SNAKE_CASE_ ).mean([-2, -1] ) )
SCREAMING_SNAKE_CASE_ = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
SCREAMING_SNAKE_CASE_ = '''regression'''
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
SCREAMING_SNAKE_CASE_ = '''single_label_classification'''
else:
SCREAMING_SNAKE_CASE_ = '''multi_label_classification'''
if self.config.problem_type == "regression":
SCREAMING_SNAKE_CASE_ = MSELoss()
if self.num_labels == 1:
SCREAMING_SNAKE_CASE_ = loss_fct(logits.squeeze() , labels.squeeze() )
else:
SCREAMING_SNAKE_CASE_ = loss_fct(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
elif self.config.problem_type == "single_label_classification":
SCREAMING_SNAKE_CASE_ = CrossEntropyLoss()
SCREAMING_SNAKE_CASE_ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
elif self.config.problem_type == "multi_label_classification":
SCREAMING_SNAKE_CASE_ = BCEWithLogitsLoss()
SCREAMING_SNAKE_CASE_ = loss_fct(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
if not return_dict:
SCREAMING_SNAKE_CASE_ = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return ImageClassifierOutputWithNoAttention(loss=SCREAMING_SNAKE_CASE_ , logits=SCREAMING_SNAKE_CASE_ , hidden_states=outputs.hidden_states ) | 626 | 1 |
"""simple docstring"""
def __UpperCamelCase ( snake_case__ = 2_000_000 ):
A_ : List[str] = [0 for i in range(n + 1 )]
A_ : Dict = 1
A_ : Any = 1
for i in range(2 , int(n**0.5 ) + 1 ):
if primality_list[i] == 0:
for j in range(i * i , n + 1 , snake_case__ ):
A_ : Any = 1
A_ : Tuple = 0
for i in range(snake_case__ ):
if primality_list[i] == 0:
sum_of_primes += i
return sum_of_primes
if __name__ == "__main__":
print(F'{solution() = }')
| 718 |
"""simple docstring"""
def __UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ ):
return not any(
neighbour == 1 and colored_vertices[i] == color
for i, neighbour in enumerate(snake_case__ ) )
def __UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ ):
# Base Case
if index == len(snake_case__ ):
return True
# Recursive Step
for i in range(snake_case__ ):
if valid_coloring(graph[index] , snake_case__ , snake_case__ ):
# Color current vertex
A_ : Dict = i
# Validate coloring
if util_color(snake_case__ , snake_case__ , snake_case__ , index + 1 ):
return True
# Backtrack
A_ : Union[str, Any] = -1
return False
def __UpperCamelCase ( snake_case__ , snake_case__ ):
A_ : int = [-1] * len(snake_case__ )
if util_color(snake_case__ , snake_case__ , snake_case__ , 0 ):
return colored_vertices
return []
| 480 | 0 |
import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union
import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn
import transformers
from transformers import (
HfArgumentParser,
Trainer,
TrainingArguments,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaForCTC,
WavaVecaProcessor,
is_apex_available,
set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process
if is_apex_available():
from apex import amp
if version.parse(version.parse(torch.__version__).base_version) >= version.parse("1.6"):
_SCREAMING_SNAKE_CASE = True
from torch.cuda.amp import autocast
_SCREAMING_SNAKE_CASE = logging.getLogger(__name__)
def _snake_case (_snake_case : Optional[Any]=None , _snake_case : Optional[int]=None) -> Optional[int]:
return field(default_factory=lambda: default , metadata=_snake_case)
@dataclass
class SCREAMING_SNAKE_CASE_ :
"""simple docstring"""
__lowerCAmelCase : str =field(
metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} )
__lowerCAmelCase : Optional[str] =field(
default=_a , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , )
__lowerCAmelCase : Optional[bool] =field(
default=_a , metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''} )
__lowerCAmelCase : Optional[float] =field(
default=0.1 , metadata={'''help''': '''The dropout ratio for the attention probabilities.'''} )
__lowerCAmelCase : Optional[float] =field(
default=0.1 , metadata={'''help''': '''The dropout ratio for activations inside the fully connected layer.'''} )
__lowerCAmelCase : Optional[float] =field(
default=0.1 , metadata={
'''help''': '''The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'''
} , )
__lowerCAmelCase : Optional[float] =field(
default=0.1 , metadata={'''help''': '''The dropout probabilitiy for all 1D convolutional layers in feature extractor.'''} , )
__lowerCAmelCase : Optional[float] =field(
default=0.05 , metadata={
'''help''': (
'''Propability of each feature vector along the time axis to be chosen as the start of the vector'''
'''span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'''
'''vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'''
)
} , )
__lowerCAmelCase : Optional[float] =field(default=0.0 , metadata={'''help''': '''The LayerDrop probability.'''} )
@dataclass
class SCREAMING_SNAKE_CASE_ :
"""simple docstring"""
__lowerCAmelCase : Optional[str] =field(
default=_a , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} )
__lowerCAmelCase : Optional[str] =field(
default='''train+validation''' , metadata={
'''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\''''
} , )
__lowerCAmelCase : bool =field(
default=_a , metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''} )
__lowerCAmelCase : Optional[int] =field(
default=_a , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , )
__lowerCAmelCase : Optional[int] =field(
default=_a , metadata={
'''help''': (
'''For debugging purposes or quicker training, truncate the number of training examples to this '''
'''value if set.'''
)
} , )
__lowerCAmelCase : Optional[int] =field(
default=_a , metadata={
'''help''': (
'''For debugging purposes or quicker training, truncate the number of validation examples to this '''
'''value if set.'''
)
} , )
__lowerCAmelCase : List[str] =list_field(
default=[''',''', '''?''', '''.''', '''!''', '''-''', ''';''', ''':''', '''""''', '''%''', '''\'''', '''"''', '''�'''] , metadata={'''help''': '''A list of characters to remove from the transcripts.'''} , )
@dataclass
class SCREAMING_SNAKE_CASE_ :
"""simple docstring"""
__lowerCAmelCase : WavaVecaProcessor
__lowerCAmelCase : Union[bool, str] =True
__lowerCAmelCase : Optional[int] =None
__lowerCAmelCase : Optional[int] =None
__lowerCAmelCase : Optional[int] =None
__lowerCAmelCase : Optional[int] =None
def __call__( self :Dict, snake_case :List[Dict[str, Union[List[int], torch.Tensor]]]):
"""simple docstring"""
_lowercase =[{'input_values': feature['input_values']} for feature in features]
_lowercase =[{'input_ids': feature['labels']} for feature in features]
_lowercase =self.processor.pad(
snake_case, padding=self.padding, max_length=self.max_length, pad_to_multiple_of=self.pad_to_multiple_of, return_tensors='pt', )
_lowercase =self.processor.pad(
labels=snake_case, padding=self.padding, max_length=self.max_length_labels, pad_to_multiple_of=self.pad_to_multiple_of_labels, return_tensors='pt', )
# replace padding with -100 to ignore loss correctly
_lowercase =labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1), -100)
_lowercase =labels
return batch
class SCREAMING_SNAKE_CASE_ ( _a ):
"""simple docstring"""
def UpperCamelCase__ ( self :int, snake_case :nn.Module, snake_case :Dict[str, Union[torch.Tensor, Any]]):
"""simple docstring"""
model.train()
_lowercase =self._prepare_inputs(snake_case)
if self.use_amp:
with autocast():
_lowercase =self.compute_loss(snake_case, snake_case)
else:
_lowercase =self.compute_loss(snake_case, snake_case)
if self.args.n_gpu > 1:
if model.module.config.ctc_loss_reduction == "mean":
_lowercase =loss.mean()
elif model.module.config.ctc_loss_reduction == "sum":
_lowercase =loss.sum() / (inputs['labels'] >= 0).sum()
else:
raise ValueError(f'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']''')
if self.args.gradient_accumulation_steps > 1:
_lowercase =loss / self.args.gradient_accumulation_steps
if self.use_amp:
self.scaler.scale(snake_case).backward()
elif self.use_apex:
with amp.scale_loss(snake_case, self.optimizer) as scaled_loss:
scaled_loss.backward()
elif self.deepspeed:
self.deepspeed.backward(snake_case)
else:
loss.backward()
return loss.detach()
def _snake_case () -> int:
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
_lowercase =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if len(sys.argv) == 2 and sys.argv[1].endswith('.json'):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
_lowercase , _lowercase , _lowercase =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
_lowercase , _lowercase , _lowercase =parser.parse_args_into_dataclasses()
# Detecting last checkpoint.
_lowercase =None
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
_lowercase =get_last_checkpoint(training_args.output_dir)
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
raise ValueError(
f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
'Use --overwrite_output_dir to overcome.')
elif last_checkpoint is not None:
logger.info(
f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.')
# Setup logging
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout)] , )
logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
# Log on each process the small summary:
logger.warning(
f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
+ f'''distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fpaa}''')
# Set the verbosity to info of the Transformers logger (on main process only):
if is_main_process(training_args.local_rank):
transformers.utils.logging.set_verbosity_info()
logger.info('Training/evaluation parameters %s' , _snake_case)
# Set seed before initializing model.
set_seed(training_args.seed)
# Get the datasets:
_lowercase =datasets.load_dataset(
'common_voice' , data_args.dataset_config_name , split=data_args.train_split_name)
_lowercase =datasets.load_dataset('common_voice' , data_args.dataset_config_name , split='test')
# Create and save tokenizer
_lowercase =f'''[{"".join(data_args.chars_to_ignore)}]'''
def remove_special_characters(_snake_case : str):
_lowercase =re.sub(_snake_case , '' , batch['sentence']).lower() + ' '
return batch
_lowercase =train_dataset.map(_snake_case , remove_columns=['sentence'])
_lowercase =eval_dataset.map(_snake_case , remove_columns=['sentence'])
def extract_all_chars(_snake_case : int):
_lowercase =' '.join(batch['text'])
_lowercase =list(set(_snake_case))
return {"vocab": [vocab], "all_text": [all_text]}
_lowercase =train_dataset.map(
_snake_case , batched=_snake_case , batch_size=-1 , keep_in_memory=_snake_case , remove_columns=train_dataset.column_names , )
_lowercase =train_dataset.map(
_snake_case , batched=_snake_case , batch_size=-1 , keep_in_memory=_snake_case , remove_columns=eval_dataset.column_names , )
_lowercase =list(set(vocab_train['vocab'][0]) | set(vocab_test['vocab'][0]))
_lowercase ={v: k for k, v in enumerate(_snake_case)}
_lowercase =vocab_dict[' ']
del vocab_dict[" "]
_lowercase =len(_snake_case)
_lowercase =len(_snake_case)
with open('vocab.json' , 'w') as vocab_file:
json.dump(_snake_case , _snake_case)
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
_lowercase =WavaVecaCTCTokenizer(
'vocab.json' , unk_token='[UNK]' , pad_token='[PAD]' , word_delimiter_token='|' , )
_lowercase =WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=1_6000 , padding_value=0.0 , do_normalize=_snake_case , return_attention_mask=_snake_case)
_lowercase =WavaVecaProcessor(feature_extractor=_snake_case , tokenizer=_snake_case)
_lowercase =WavaVecaForCTC.from_pretrained(
model_args.model_name_or_path , cache_dir=model_args.cache_dir , activation_dropout=model_args.activation_dropout , attention_dropout=model_args.attention_dropout , hidden_dropout=model_args.hidden_dropout , feat_proj_dropout=model_args.feat_proj_dropout , mask_time_prob=model_args.mask_time_prob , gradient_checkpointing=training_args.gradient_checkpointing , layerdrop=model_args.layerdrop , ctc_loss_reduction='mean' , pad_token_id=processor.tokenizer.pad_token_id , vocab_size=len(processor.tokenizer) , )
if data_args.max_train_samples is not None:
_lowercase =min(len(_snake_case) , data_args.max_train_samples)
_lowercase =train_dataset.select(range(_snake_case))
if data_args.max_val_samples is not None:
_lowercase =eval_dataset.select(range(data_args.max_val_samples))
_lowercase =torchaudio.transforms.Resample(4_8000 , 1_6000)
# Preprocessing the datasets.
# We need to read the aduio files as arrays and tokenize the targets.
def speech_file_to_array_fn(_snake_case : str):
_lowercase , _lowercase =torchaudio.load(batch['path'])
_lowercase =resampler(_snake_case).squeeze().numpy()
_lowercase =1_6000
_lowercase =batch['text']
return batch
_lowercase =train_dataset.map(
_snake_case , remove_columns=train_dataset.column_names , num_proc=data_args.preprocessing_num_workers , )
_lowercase =eval_dataset.map(
_snake_case , remove_columns=eval_dataset.column_names , num_proc=data_args.preprocessing_num_workers , )
def prepare_dataset(_snake_case : int):
# check that all files have the correct sampling rate
assert (
len(set(batch['sampling_rate'])) == 1
), f'''Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'''
_lowercase =processor(
audio=batch['speech'] , text=batch['target_text'] , sampling_rate=batch['sampling_rate'][0])
batch.update(_snake_case)
return batch
_lowercase =train_dataset.map(
_snake_case , remove_columns=train_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_snake_case , num_proc=data_args.preprocessing_num_workers , )
_lowercase =eval_dataset.map(
_snake_case , remove_columns=eval_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_snake_case , num_proc=data_args.preprocessing_num_workers , )
# Metric
_lowercase =datasets.load_metric('wer')
def compute_metrics(_snake_case : str):
_lowercase =pred.predictions
_lowercase =np.argmax(_snake_case , axis=-1)
_lowercase =processor.tokenizer.pad_token_id
_lowercase =processor.batch_decode(_snake_case)
# we do not want to group tokens when computing the metrics
_lowercase =processor.batch_decode(pred.label_ids , group_tokens=_snake_case)
_lowercase =wer_metric.compute(predictions=_snake_case , references=_snake_case)
return {"wer": wer}
if model_args.freeze_feature_extractor:
model.freeze_feature_extractor()
# Data collator
_lowercase =DataCollatorCTCWithPadding(processor=_snake_case , padding=_snake_case)
# Initialize our Trainer
_lowercase =CTCTrainer(
model=_snake_case , data_collator=_snake_case , args=_snake_case , compute_metrics=_snake_case , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=processor.feature_extractor , )
# Training
if training_args.do_train:
if last_checkpoint is not None:
_lowercase =last_checkpoint
elif os.path.isdir(model_args.model_name_or_path):
_lowercase =model_args.model_name_or_path
else:
_lowercase =None
# Save the feature_extractor and the tokenizer
if is_main_process(training_args.local_rank):
processor.save_pretrained(training_args.output_dir)
_lowercase =trainer.train(resume_from_checkpoint=_snake_case)
trainer.save_model()
_lowercase =train_result.metrics
_lowercase =(
data_args.max_train_samples if data_args.max_train_samples is not None else len(_snake_case)
)
_lowercase =min(_snake_case , len(_snake_case))
trainer.log_metrics('train' , _snake_case)
trainer.save_metrics('train' , _snake_case)
trainer.save_state()
# Evaluation
_lowercase ={}
if training_args.do_eval:
logger.info('*** Evaluate ***')
_lowercase =trainer.evaluate()
_lowercase =data_args.max_val_samples if data_args.max_val_samples is not None else len(_snake_case)
_lowercase =min(_snake_case , len(_snake_case))
trainer.log_metrics('eval' , _snake_case)
trainer.save_metrics('eval' , _snake_case)
return results
if __name__ == "__main__":
main()
| 181 |
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available
if is_vision_available():
from PIL import Image
from transformers import (
AutoProcessor,
BertTokenizerFast,
BlipImageProcessor,
GPTaTokenizer,
InstructBlipProcessor,
PreTrainedTokenizerFast,
)
@require_vision
class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ):
"""simple docstring"""
def UpperCamelCase__ ( self :List[str]):
"""simple docstring"""
_lowercase =tempfile.mkdtemp()
_lowercase =BlipImageProcessor()
_lowercase =GPTaTokenizer.from_pretrained('hf-internal-testing/tiny-random-GPT2Model')
_lowercase =BertTokenizerFast.from_pretrained('hf-internal-testing/tiny-random-bert')
_lowercase =InstructBlipProcessor(snake_case, snake_case, snake_case)
processor.save_pretrained(self.tmpdirname)
def UpperCamelCase__ ( self :List[str], **snake_case :str):
"""simple docstring"""
return AutoProcessor.from_pretrained(self.tmpdirname, **snake_case).tokenizer
def UpperCamelCase__ ( self :Optional[Any], **snake_case :List[Any]):
"""simple docstring"""
return AutoProcessor.from_pretrained(self.tmpdirname, **snake_case).image_processor
def UpperCamelCase__ ( self :Tuple, **snake_case :Any):
"""simple docstring"""
return AutoProcessor.from_pretrained(self.tmpdirname, **snake_case).qformer_tokenizer
def UpperCamelCase__ ( self :Optional[int]):
"""simple docstring"""
shutil.rmtree(self.tmpdirname)
def UpperCamelCase__ ( self :List[str]):
"""simple docstring"""
_lowercase =[np.random.randint(255, size=(3, 30, 400), dtype=np.uinta)]
_lowercase =[Image.fromarray(np.moveaxis(snake_case, 0, -1)) for x in image_inputs]
return image_inputs
def UpperCamelCase__ ( self :List[Any]):
"""simple docstring"""
_lowercase =InstructBlipProcessor(
tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor(), qformer_tokenizer=self.get_qformer_tokenizer(), )
processor.save_pretrained(self.tmpdirname)
_lowercase =self.get_tokenizer(bos_token='(BOS)', eos_token='(EOS)')
_lowercase =self.get_image_processor(do_normalize=snake_case, padding_value=1.0)
_lowercase =InstructBlipProcessor.from_pretrained(
self.tmpdirname, bos_token='(BOS)', eos_token='(EOS)', do_normalize=snake_case, padding_value=1.0)
self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
self.assertIsInstance(processor.tokenizer, snake_case)
self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string())
self.assertIsInstance(processor.image_processor, snake_case)
self.assertIsInstance(processor.qformer_tokenizer, snake_case)
def UpperCamelCase__ ( self :Tuple):
"""simple docstring"""
_lowercase =self.get_image_processor()
_lowercase =self.get_tokenizer()
_lowercase =self.get_qformer_tokenizer()
_lowercase =InstructBlipProcessor(
tokenizer=snake_case, image_processor=snake_case, qformer_tokenizer=snake_case)
_lowercase =self.prepare_image_inputs()
_lowercase =image_processor(snake_case, return_tensors='np')
_lowercase =processor(images=snake_case, 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 UpperCamelCase__ ( self :List[Any]):
"""simple docstring"""
_lowercase =self.get_image_processor()
_lowercase =self.get_tokenizer()
_lowercase =self.get_qformer_tokenizer()
_lowercase =InstructBlipProcessor(
tokenizer=snake_case, image_processor=snake_case, qformer_tokenizer=snake_case)
_lowercase ='lower newer'
_lowercase =processor(text=snake_case)
_lowercase =tokenizer(snake_case, return_token_type_ids=snake_case)
_lowercase =qformer_tokenizer(snake_case, return_token_type_ids=snake_case)
for key in encoded_tokens.keys():
self.assertListEqual(encoded_tokens[key], encoded_processor[key])
for key in encoded_tokens_qformer.keys():
self.assertListEqual(encoded_tokens_qformer[key], encoded_processor['qformer_' + key])
def UpperCamelCase__ ( self :Any):
"""simple docstring"""
_lowercase =self.get_image_processor()
_lowercase =self.get_tokenizer()
_lowercase =self.get_qformer_tokenizer()
_lowercase =InstructBlipProcessor(
tokenizer=snake_case, image_processor=snake_case, qformer_tokenizer=snake_case)
_lowercase ='lower newer'
_lowercase =self.prepare_image_inputs()
_lowercase =processor(text=snake_case, images=snake_case)
self.assertListEqual(
list(inputs.keys()), ['input_ids', 'attention_mask', 'qformer_input_ids', 'qformer_attention_mask', 'pixel_values'], )
# test if it raises when no input is passed
with pytest.raises(snake_case):
processor()
def UpperCamelCase__ ( self :Dict):
"""simple docstring"""
_lowercase =self.get_image_processor()
_lowercase =self.get_tokenizer()
_lowercase =self.get_qformer_tokenizer()
_lowercase =InstructBlipProcessor(
tokenizer=snake_case, image_processor=snake_case, qformer_tokenizer=snake_case)
_lowercase =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
_lowercase =processor.batch_decode(snake_case)
_lowercase =tokenizer.batch_decode(snake_case)
self.assertListEqual(snake_case, snake_case)
def UpperCamelCase__ ( self :int):
"""simple docstring"""
_lowercase =self.get_image_processor()
_lowercase =self.get_tokenizer()
_lowercase =self.get_qformer_tokenizer()
_lowercase =InstructBlipProcessor(
tokenizer=snake_case, image_processor=snake_case, qformer_tokenizer=snake_case)
_lowercase ='lower newer'
_lowercase =self.prepare_image_inputs()
_lowercase =processor(text=snake_case, images=snake_case)
self.assertListEqual(
list(inputs.keys()), ['input_ids', 'attention_mask', 'qformer_input_ids', 'qformer_attention_mask', 'pixel_values'], )
| 181 | 1 |
'''simple docstring'''
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_funnel import FunnelTokenizer
UpperCAmelCase_ : Any = logging.get_logger(__name__)
UpperCAmelCase_ : List[str] = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
UpperCAmelCase_ : List[str] = [
"small",
"small-base",
"medium",
"medium-base",
"intermediate",
"intermediate-base",
"large",
"large-base",
"xlarge",
"xlarge-base",
]
UpperCAmelCase_ : str = {
"vocab_file": {
"funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt",
"funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt",
"funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt",
"funnel-transformer/medium-base": (
"https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt"
),
"funnel-transformer/intermediate": (
"https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt"
),
"funnel-transformer/intermediate-base": (
"https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt"
),
"funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt",
"funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt",
"funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt",
"funnel-transformer/xlarge-base": (
"https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json",
"funnel-transformer/small-base": (
"https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json"
),
"funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json",
"funnel-transformer/medium-base": (
"https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json"
),
"funnel-transformer/intermediate": (
"https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json"
),
"funnel-transformer/intermediate-base": (
"https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json"
),
"funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json",
"funnel-transformer/large-base": (
"https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json"
),
"funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json",
"funnel-transformer/xlarge-base": (
"https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json"
),
},
}
UpperCAmelCase_ : Dict = {f'''funnel-transformer/{name}''': 512 for name in _model_names}
UpperCAmelCase_ : List[Any] = {f'''funnel-transformer/{name}''': {"do_lower_case": True} for name in _model_names}
class a ( snake_case__ ):
'''simple docstring'''
__lowerCAmelCase : List[str] = VOCAB_FILES_NAMES
__lowerCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP
__lowerCAmelCase : Dict = PRETRAINED_INIT_CONFIGURATION
__lowerCAmelCase : Dict = FunnelTokenizer
__lowerCAmelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__lowerCAmelCase : int = 2
def __init__( self , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=True , lowerCamelCase_="<unk>" , lowerCamelCase_="<sep>" , lowerCamelCase_="<pad>" , lowerCamelCase_="<cls>" , lowerCamelCase_="<mask>" , lowerCamelCase_="<s>" , lowerCamelCase_="</s>" , lowerCamelCase_=True , lowerCamelCase_=True , lowerCamelCase_=None , lowerCamelCase_="##" , **lowerCamelCase_ , ) -> Tuple:
super().__init__(
lowerCamelCase_ , tokenizer_file=lowerCamelCase_ , do_lower_case=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , clean_text=lowerCamelCase_ , tokenize_chinese_chars=lowerCamelCase_ , strip_accents=lowerCamelCase_ , wordpieces_prefix=lowerCamelCase_ , **lowerCamelCase_ , )
_a : str = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get('lowercase' , lowerCamelCase_ ) != do_lower_case
or normalizer_state.get('strip_accents' , lowerCamelCase_ ) != strip_accents
or normalizer_state.get('handle_chinese_chars' , lowerCamelCase_ ) != tokenize_chinese_chars
):
_a : List[str] = getattr(lowerCamelCase_ , normalizer_state.pop('type' ) )
_a : List[Any] = do_lower_case
_a : Dict = strip_accents
_a : List[str] = tokenize_chinese_chars
_a : Dict = normalizer_class(**lowerCamelCase_ )
_a : Optional[int] = do_lower_case
def __UpperCamelCase ( self , lowerCamelCase_ , lowerCamelCase_=None ) -> Dict:
_a : Tuple = [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 , lowerCamelCase_ , lowerCamelCase_ = None ) -> List[int]:
_a : str = [self.sep_token_id]
_a : Union[str, Any] = [self.cls_token_id]
if token_ids_a is None:
return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0]
return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def __UpperCamelCase ( self , lowerCamelCase_ , lowerCamelCase_ = None ) -> Tuple[str]:
_a : List[str] = self._tokenizer.model.save(lowerCamelCase_ , name=lowerCamelCase_ )
return tuple(lowerCamelCase_ )
| 711 |
'''simple docstring'''
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union
import numpy as np
import PIL
from PIL import Image
from ...utils import BaseOutput, is_torch_available, is_transformers_available
@dataclass
class a ( snake_case__ ):
'''simple docstring'''
__lowerCAmelCase : Union[List[PIL.Image.Image], np.ndarray]
__lowerCAmelCase : Optional[List[bool]]
if is_transformers_available() and is_torch_available():
from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
| 424 | 0 |
"""simple docstring"""
import os
from itertools import chain
from random import randrange, shuffle
import pytest
from .sola import PokerHand
lowerCAmelCase__ = (
'''4S 3H 2C 7S 5H''',
'''9D 8H 2C 6S 7H''',
'''2D 6D 9D TH 7D''',
'''TC 8C 2S JH 6C''',
'''JH 8S TH AH QH''',
'''TS KS 5S 9S AC''',
'''KD 6S 9D TH AD''',
'''KS 8D 4D 9S 4S''', # pair
'''8C 4S KH JS 4D''', # pair
'''QH 8H KD JH 8S''', # pair
'''KC 4H KS 2H 8D''', # pair
'''KD 4S KC 3H 8S''', # pair
'''AH 8S AS KC JH''', # pair
'''3H 4C 4H 3S 2H''', # 2 pairs
'''5S 5D 2C KH KH''', # 2 pairs
'''3C KH 5D 5S KH''', # 2 pairs
'''AS 3C KH AD KH''', # 2 pairs
'''7C 7S 3S 7H 5S''', # 3 of a kind
'''7C 7S KH 2H 7H''', # 3 of a kind
'''AC KH QH AH AS''', # 3 of a kind
'''2H 4D 3C AS 5S''', # straight (low ace)
'''3C 5C 4C 2C 6H''', # straight
'''6S 8S 7S 5H 9H''', # straight
'''JS QS 9H TS KH''', # straight
'''QC KH TS JS AH''', # straight (high ace)
'''8C 9C 5C 3C TC''', # flush
'''3S 8S 9S 5S KS''', # flush
'''4C 5C 9C 8C KC''', # flush
'''JH 8H AH KH QH''', # flush
'''3D 2H 3H 2C 2D''', # full house
'''2H 2C 3S 3H 3D''', # full house
'''KH KC 3S 3H 3D''', # full house
'''JC 6H JS JD JH''', # 4 of a kind
'''JC 7H JS JD JH''', # 4 of a kind
'''JC KH JS JD JH''', # 4 of a kind
'''2S AS 4S 5S 3S''', # straight flush (low ace)
'''2D 6D 3D 4D 5D''', # straight flush
'''5C 6C 3C 7C 4C''', # straight flush
'''JH 9H TH KH QH''', # straight flush
'''JH AH TH KH QH''', # royal flush (high ace straight flush)
)
lowerCAmelCase__ = (
('''2H 3H 4H 5H 6H''', '''KS AS TS QS JS''', '''Loss'''),
('''2H 3H 4H 5H 6H''', '''AS AD AC AH JD''', '''Win'''),
('''AS AH 2H AD AC''', '''JS JD JC JH 3D''', '''Win'''),
('''2S AH 2H AS AC''', '''JS JD JC JH AD''', '''Loss'''),
('''2S AH 2H AS AC''', '''2H 3H 5H 6H 7H''', '''Win'''),
('''AS 3S 4S 8S 2S''', '''2H 3H 5H 6H 7H''', '''Win'''),
('''2H 3H 5H 6H 7H''', '''2S 3H 4H 5S 6C''', '''Win'''),
('''2S 3H 4H 5S 6C''', '''3D 4C 5H 6H 2S''', '''Tie'''),
('''2S 3H 4H 5S 6C''', '''AH AC 5H 6H AS''', '''Win'''),
('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H AS''', '''Loss'''),
('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H 7S''', '''Win'''),
('''6S AD 7H 4S AS''', '''AH AC 5H 6H 7S''', '''Loss'''),
('''2S AH 4H 5S KC''', '''AH AC 5H 6H 7S''', '''Loss'''),
('''2S 3H 6H 7S 9C''', '''7H 3C TH 6H 9S''', '''Loss'''),
('''4S 5H 6H TS AC''', '''3S 5H 6H TS AC''', '''Win'''),
('''2S AH 4H 5S 6C''', '''AD 4C 5H 6H 2C''', '''Tie'''),
('''AS AH 3H AD AC''', '''AS AH 2H AD AC''', '''Win'''),
('''AH AC 5H 5C QS''', '''AH AC 5H 5C KS''', '''Loss'''),
('''AH AC 5H 5C QS''', '''KH KC 5H 5C QS''', '''Win'''),
('''7C 7S KH 2H 7H''', '''3C 3S AH 2H 3H''', '''Win'''),
('''3C 3S AH 2H 3H''', '''7C 7S KH 2H 7H''', '''Loss'''),
('''6H 5H 4H 3H 2H''', '''5H 4H 3H 2H AH''', '''Win'''),
('''5H 4H 3H 2H AH''', '''5H 4H 3H 2H AH''', '''Tie'''),
('''5H 4H 3H 2H AH''', '''6H 5H 4H 3H 2H''', '''Loss'''),
('''AH AD KS KC AC''', '''AH KD KH AC KC''', '''Win'''),
('''2H 4D 3C AS 5S''', '''2H 4D 3C 6S 5S''', '''Loss'''),
('''2H 3S 3C 3H 2S''', '''3S 3C 2S 2H 2D''', '''Win'''),
('''4D 6D 5D 2D JH''', '''3S 8S 3H TC KH''', '''Loss'''),
('''4S 6C 8S 3S 7S''', '''AD KS 2D 7D 7C''', '''Loss'''),
('''6S 4C 7H 8C 3H''', '''5H JC AH 9D 9C''', '''Loss'''),
('''9D 9H JH TC QH''', '''3C 2S JS 5C 7H''', '''Win'''),
('''2H TC 8S AD 9S''', '''4H TS 7H 2C 5C''', '''Win'''),
('''9D 3S 2C 7S 7C''', '''JC TD 3C TC 9H''', '''Loss'''),
)
lowerCAmelCase__ = (
('''2H 3H 4H 5H 6H''', True),
('''AS AH 2H AD AC''', False),
('''2H 3H 5H 6H 7H''', True),
('''KS AS TS QS JS''', True),
('''8H 9H QS JS TH''', False),
('''AS 3S 4S 8S 2S''', True),
)
lowerCAmelCase__ = (
('''2H 3H 4H 5H 6H''', True),
('''AS AH 2H AD AC''', False),
('''2H 3H 5H 6H 7H''', False),
('''KS AS TS QS JS''', True),
('''8H 9H QS JS TH''', True),
)
lowerCAmelCase__ = (
('''2H 4D 3C AS 5S''', True, [5, 4, 3, 2, 14]),
('''2H 5D 3C AS 5S''', False, [14, 5, 5, 3, 2]),
('''JH QD KC AS TS''', False, [14, 13, 12, 11, 10]),
('''9D 3S 2C 7S 7C''', False, [9, 7, 7, 3, 2]),
)
lowerCAmelCase__ = (
('''JH AH TH KH QH''', 0),
('''JH 9H TH KH QH''', 0),
('''JC KH JS JD JH''', 7),
('''KH KC 3S 3H 3D''', 6),
('''8C 9C 5C 3C TC''', 0),
('''JS QS 9H TS KH''', 0),
('''7C 7S KH 2H 7H''', 3),
('''3C KH 5D 5S KH''', 2),
('''QH 8H KD JH 8S''', 1),
('''2D 6D 9D TH 7D''', 0),
)
lowerCAmelCase__ = (
('''JH AH TH KH QH''', 23),
('''JH 9H TH KH QH''', 22),
('''JC KH JS JD JH''', 21),
('''KH KC 3S 3H 3D''', 20),
('''8C 9C 5C 3C TC''', 19),
('''JS QS 9H TS KH''', 18),
('''7C 7S KH 2H 7H''', 17),
('''3C KH 5D 5S KH''', 16),
('''QH 8H KD JH 8S''', 15),
('''2D 6D 9D TH 7D''', 14),
)
def lowercase__ ( ):
_SCREAMING_SNAKE_CASE : str = randrange(len(UpperCAmelCase_ ) ), randrange(len(UpperCAmelCase_ ) )
_SCREAMING_SNAKE_CASE : List[str] = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)]
_SCREAMING_SNAKE_CASE : List[Any] = SORTED_HANDS[play], SORTED_HANDS[oppo]
return hand, other, expected
def lowercase__ ( lowerCamelCase = 100 ):
return (generate_random_hand() for _ in range(UpperCAmelCase_ ))
@pytest.mark.parametrize('hand, expected', UpperCAmelCase_ )
def lowercase__ ( lowerCamelCase, lowerCamelCase ):
assert PokerHand(UpperCAmelCase_ )._is_flush() == expected
@pytest.mark.parametrize('hand, expected', UpperCAmelCase_ )
def lowercase__ ( lowerCamelCase, lowerCamelCase ):
assert PokerHand(UpperCAmelCase_ )._is_straight() == expected
@pytest.mark.parametrize('hand, expected, card_values', UpperCAmelCase_ )
def lowercase__ ( lowerCamelCase, lowerCamelCase, lowerCamelCase ):
_SCREAMING_SNAKE_CASE : Dict = PokerHand(UpperCAmelCase_ )
assert player._is_five_high_straight() == expected
assert player._card_values == card_values
@pytest.mark.parametrize('hand, expected', UpperCAmelCase_ )
def lowercase__ ( lowerCamelCase, lowerCamelCase ):
assert PokerHand(UpperCAmelCase_ )._is_same_kind() == expected
@pytest.mark.parametrize('hand, expected', UpperCAmelCase_ )
def lowercase__ ( lowerCamelCase, lowerCamelCase ):
assert PokerHand(UpperCAmelCase_ )._hand_type == expected
@pytest.mark.parametrize('hand, other, expected', UpperCAmelCase_ )
def lowercase__ ( lowerCamelCase, lowerCamelCase, lowerCamelCase ):
assert PokerHand(UpperCAmelCase_ ).compare_with(PokerHand(UpperCAmelCase_ ) ) == expected
@pytest.mark.parametrize('hand, other, expected', generate_random_hands() )
def lowercase__ ( lowerCamelCase, lowerCamelCase, lowerCamelCase ):
assert PokerHand(UpperCAmelCase_ ).compare_with(PokerHand(UpperCAmelCase_ ) ) == expected
def lowercase__ ( ):
_SCREAMING_SNAKE_CASE : List[str] = [PokerHand(UpperCAmelCase_ ) for hand in SORTED_HANDS]
_SCREAMING_SNAKE_CASE : List[str] = poker_hands.copy()
shuffle(UpperCAmelCase_ )
_SCREAMING_SNAKE_CASE : Tuple = chain(sorted(UpperCAmelCase_ ) )
for index, hand in enumerate(UpperCAmelCase_ ):
assert hand == poker_hands[index]
def lowercase__ ( ):
_SCREAMING_SNAKE_CASE : List[str] = [PokerHand('2D AC 3H 4H 5S' ), PokerHand('2S 3H 4H 5S 6C' )]
pokerhands.sort(reverse=UpperCAmelCase_ )
assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C"
def lowercase__ ( ):
_SCREAMING_SNAKE_CASE : Union[str, Any] = PokerHand('2C 4S AS 3D 5C' )
_SCREAMING_SNAKE_CASE : List[str] = True
_SCREAMING_SNAKE_CASE : Union[str, Any] = [5, 4, 3, 2, 14]
for _ in range(10 ):
assert pokerhand._is_five_high_straight() == expected
assert pokerhand._card_values == expected_card_values
def lowercase__ ( ):
_SCREAMING_SNAKE_CASE : Optional[int] = 0
_SCREAMING_SNAKE_CASE : Optional[int] = os.path.abspath(os.path.dirname(UpperCAmelCase_ ) )
_SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(UpperCAmelCase_, 'poker_hands.txt' )
with open(UpperCAmelCase_ ) as file_hand:
for line in file_hand:
_SCREAMING_SNAKE_CASE : int = line[:14].strip()
_SCREAMING_SNAKE_CASE : List[Any] = line[15:].strip()
_SCREAMING_SNAKE_CASE : Optional[Any] = PokerHand(UpperCAmelCase_ ), PokerHand(UpperCAmelCase_ )
_SCREAMING_SNAKE_CASE : int = player.compare_with(UpperCAmelCase_ )
if output == "Win":
answer += 1
assert answer == 376
| 621 |
import datasets
snake_case : int = '''\
@InProceedings{conneau2018xnli,
author = "Conneau, Alexis
and Rinott, Ruty
and Lample, Guillaume
and Williams, Adina
and Bowman, Samuel R.
and Schwenk, Holger
and Stoyanov, Veselin",
title = "XNLI: Evaluating Cross-lingual Sentence Representations",
booktitle = "Proceedings of the 2018 Conference on Empirical Methods
in Natural Language Processing",
year = "2018",
publisher = "Association for Computational Linguistics",
location = "Brussels, Belgium",
}
'''
snake_case : Tuple = '''\
XNLI is a subset of a few thousand examples from MNLI which has been translated
into a 14 different languages (some low-ish resource). As with MNLI, the goal is
to predict textual entailment (does sentence A imply/contradict/neither sentence
B) and is a classification task (given two sentences, predict one of three
labels).
'''
snake_case : Union[str, Any] = '''
Computes XNLI score which is just simple accuracy.
Args:
predictions: Predicted labels.
references: Ground truth labels.
Returns:
\'accuracy\': accuracy
Examples:
>>> predictions = [0, 1]
>>> references = [0, 1]
>>> xnli_metric = datasets.load_metric("xnli")
>>> results = xnli_metric.compute(predictions=predictions, references=references)
>>> print(results)
{\'accuracy\': 1.0}
'''
def __lowerCamelCase ( UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] ):
"""simple docstring"""
return (preds == labels).mean()
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class _snake_case ( datasets.Metric ):
def SCREAMING_SNAKE_CASE__ ( self ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Value('''int64''' if self.config_name != '''sts-b''' else '''float32''' ),
'''references''': datasets.Value('''int64''' if self.config_name != '''sts-b''' else '''float32''' ),
} ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' , )
def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase ):
return {"accuracy": simple_accuracy(_lowerCamelCase , _lowerCamelCase )}
| 445 | 0 |
from typing import Any, Dict, Optional
import torch
import torch.nn.functional as F
from torch import nn
from ..utils import maybe_allow_in_graph
from .activations import get_activation
from .attention_processor import Attention
from .embeddings import CombinedTimestepLabelEmbeddings
@maybe_allow_in_graph
class __UpperCamelCase ( nn.Module ):
def __init__( self: Optional[Any] , __UpperCamelCase: int , __UpperCamelCase: int , __UpperCamelCase: int , __UpperCamelCase: Dict=0.0 , __UpperCamelCase: Optional[int] = None , __UpperCamelCase: str = "geglu" , __UpperCamelCase: Optional[int] = None , __UpperCamelCase: bool = False , __UpperCamelCase: bool = False , __UpperCamelCase: bool = False , __UpperCamelCase: bool = False , __UpperCamelCase: bool = True , __UpperCamelCase: str = "layer_norm" , __UpperCamelCase: bool = False , ):
'''simple docstring'''
super().__init__()
__magic_name__ = only_cross_attention
__magic_name__ = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
__magic_name__ = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
raise ValueError(
F'`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to'
F' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.' )
# Define 3 blocks. Each block has its own normalization layer.
# 1. Self-Attn
if self.use_ada_layer_norm:
__magic_name__ = AdaLayerNorm(__a , __a )
elif self.use_ada_layer_norm_zero:
__magic_name__ = AdaLayerNormZero(__a , __a )
else:
__magic_name__ = nn.LayerNorm(__a , elementwise_affine=__a )
__magic_name__ = Attention(
query_dim=__a , heads=__a , dim_head=__a , dropout=__a , bias=__a , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=__a , )
# 2. Cross-Attn
if cross_attention_dim is not None or double_self_attention:
# We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
# I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
# the second cross attention block.
__magic_name__ = (
AdaLayerNorm(__a , __a )
if self.use_ada_layer_norm
else nn.LayerNorm(__a , elementwise_affine=__a )
)
__magic_name__ = Attention(
query_dim=__a , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=__a , dim_head=__a , dropout=__a , bias=__a , upcast_attention=__a , ) # is self-attn if encoder_hidden_states is none
else:
__magic_name__ = None
__magic_name__ = None
# 3. Feed-forward
__magic_name__ = nn.LayerNorm(__a , elementwise_affine=__a )
__magic_name__ = FeedForward(__a , dropout=__a , activation_fn=__a , final_dropout=__a )
# let chunk size default to None
__magic_name__ = None
__magic_name__ = 0
def _SCREAMING_SNAKE_CASE ( self: List[str] , __UpperCamelCase: Optional[int] , __UpperCamelCase: int ):
'''simple docstring'''
__magic_name__ = chunk_size
__magic_name__ = dim
def _SCREAMING_SNAKE_CASE ( self: List[Any] , __UpperCamelCase: torch.FloatTensor , __UpperCamelCase: Optional[torch.FloatTensor] = None , __UpperCamelCase: Optional[torch.FloatTensor] = None , __UpperCamelCase: Optional[torch.FloatTensor] = None , __UpperCamelCase: Optional[torch.LongTensor] = None , __UpperCamelCase: Dict[str, Any] = None , __UpperCamelCase: Optional[torch.LongTensor] = None , ):
'''simple docstring'''
if self.use_ada_layer_norm:
__magic_name__ = self.norma(__a , __a )
elif self.use_ada_layer_norm_zero:
__magic_name__ = self.norma(
__a , __a , __a , hidden_dtype=hidden_states.dtype )
else:
__magic_name__ = self.norma(__a )
__magic_name__ = cross_attention_kwargs if cross_attention_kwargs is not None else {}
__magic_name__ = self.attna(
__a , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=__a , **__a , )
if self.use_ada_layer_norm_zero:
__magic_name__ = gate_msa.unsqueeze(1 ) * attn_output
__magic_name__ = attn_output + hidden_states
# 2. Cross-Attention
if self.attna is not None:
__magic_name__ = (
self.norma(__a , __a ) if self.use_ada_layer_norm else self.norma(__a )
)
__magic_name__ = self.attna(
__a , encoder_hidden_states=__a , attention_mask=__a , **__a , )
__magic_name__ = attn_output + hidden_states
# 3. Feed-forward
__magic_name__ = self.norma(__a )
if self.use_ada_layer_norm_zero:
__magic_name__ = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
if self._chunk_size is not None:
# "feed_forward_chunk_size" can be used to save memory
if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
raise ValueError(
F'`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.' )
__magic_name__ = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
__magic_name__ = torch.cat(
[self.ff(__a ) for hid_slice in norm_hidden_states.chunk(__a , dim=self._chunk_dim )] , dim=self._chunk_dim , )
else:
__magic_name__ = self.ff(__a )
if self.use_ada_layer_norm_zero:
__magic_name__ = gate_mlp.unsqueeze(1 ) * ff_output
__magic_name__ = ff_output + hidden_states
return hidden_states
class __UpperCamelCase ( nn.Module ):
def __init__( self: Optional[int] , __UpperCamelCase: int , __UpperCamelCase: Optional[int] = None , __UpperCamelCase: int = 4 , __UpperCamelCase: float = 0.0 , __UpperCamelCase: str = "geglu" , __UpperCamelCase: bool = False , ):
'''simple docstring'''
super().__init__()
__magic_name__ = int(dim * mult )
__magic_name__ = dim_out if dim_out is not None else dim
if activation_fn == "gelu":
__magic_name__ = GELU(__a , __a )
if activation_fn == "gelu-approximate":
__magic_name__ = GELU(__a , __a , approximate='tanh' )
elif activation_fn == "geglu":
__magic_name__ = GEGLU(__a , __a )
elif activation_fn == "geglu-approximate":
__magic_name__ = ApproximateGELU(__a , __a )
__magic_name__ = nn.ModuleList([] )
# project in
self.net.append(__a )
# project dropout
self.net.append(nn.Dropout(__a ) )
# project out
self.net.append(nn.Linear(__a , __a ) )
# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
if final_dropout:
self.net.append(nn.Dropout(__a ) )
def _SCREAMING_SNAKE_CASE ( self: Tuple , __UpperCamelCase: Tuple ):
'''simple docstring'''
for module in self.net:
__magic_name__ = module(__a )
return hidden_states
class __UpperCamelCase ( nn.Module ):
def __init__( self: int , __UpperCamelCase: int , __UpperCamelCase: int , __UpperCamelCase: str = "none" ):
'''simple docstring'''
super().__init__()
__magic_name__ = nn.Linear(__a , __a )
__magic_name__ = approximate
def _SCREAMING_SNAKE_CASE ( self: Optional[int] , __UpperCamelCase: int ):
'''simple docstring'''
if gate.device.type != "mps":
return F.gelu(__a , approximate=self.approximate )
# mps: gelu is not implemented for float16
return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype )
def _SCREAMING_SNAKE_CASE ( self: List[str] , __UpperCamelCase: int ):
'''simple docstring'''
__magic_name__ = self.proj(__a )
__magic_name__ = self.gelu(__a )
return hidden_states
class __UpperCamelCase ( nn.Module ):
def __init__( self: List[str] , __UpperCamelCase: int , __UpperCamelCase: int ):
'''simple docstring'''
super().__init__()
__magic_name__ = nn.Linear(__a , dim_out * 2 )
def _SCREAMING_SNAKE_CASE ( self: Any , __UpperCamelCase: Optional[Any] ):
'''simple docstring'''
if gate.device.type != "mps":
return F.gelu(__a )
# mps: gelu is not implemented for float16
return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype )
def _SCREAMING_SNAKE_CASE ( self: Tuple , __UpperCamelCase: Tuple ):
'''simple docstring'''
__magic_name__ = self.proj(__a ).chunk(2 , dim=-1 )
return hidden_states * self.gelu(__a )
class __UpperCamelCase ( nn.Module ):
def __init__( self: int , __UpperCamelCase: int , __UpperCamelCase: int ):
'''simple docstring'''
super().__init__()
__magic_name__ = nn.Linear(__a , __a )
def _SCREAMING_SNAKE_CASE ( self: Union[str, Any] , __UpperCamelCase: Any ):
'''simple docstring'''
__magic_name__ = self.proj(__a )
return x * torch.sigmoid(1.702 * x )
class __UpperCamelCase ( nn.Module ):
def __init__( self: Dict , __UpperCamelCase: List[str] , __UpperCamelCase: Tuple ):
'''simple docstring'''
super().__init__()
__magic_name__ = nn.Embedding(__a , __a )
__magic_name__ = nn.SiLU()
__magic_name__ = nn.Linear(__a , embedding_dim * 2 )
__magic_name__ = nn.LayerNorm(__a , elementwise_affine=__a )
def _SCREAMING_SNAKE_CASE ( self: Any , __UpperCamelCase: str , __UpperCamelCase: List[Any] ):
'''simple docstring'''
__magic_name__ = self.linear(self.silu(self.emb(__a ) ) )
__magic_name__ = torch.chunk(__a , 2 )
__magic_name__ = self.norm(__a ) * (1 + scale) + shift
return x
class __UpperCamelCase ( nn.Module ):
def __init__( self: Tuple , __UpperCamelCase: List[Any] , __UpperCamelCase: Tuple ):
'''simple docstring'''
super().__init__()
__magic_name__ = CombinedTimestepLabelEmbeddings(__a , __a )
__magic_name__ = nn.SiLU()
__magic_name__ = nn.Linear(__a , 6 * embedding_dim , bias=__a )
__magic_name__ = nn.LayerNorm(__a , elementwise_affine=__a , eps=1E-6 )
def _SCREAMING_SNAKE_CASE ( self: Optional[int] , __UpperCamelCase: str , __UpperCamelCase: Optional[Any] , __UpperCamelCase: Dict , __UpperCamelCase: Tuple=None ):
'''simple docstring'''
__magic_name__ = self.linear(self.silu(self.emb(__a , __a , hidden_dtype=__a ) ) )
__magic_name__ = emb.chunk(6 , dim=1 )
__magic_name__ = self.norm(__a ) * (1 + scale_msa[:, None]) + shift_msa[:, None]
return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
class __UpperCamelCase ( nn.Module ):
def __init__( self: str , __UpperCamelCase: int , __UpperCamelCase: int , __UpperCamelCase: int , __UpperCamelCase: Optional[str] = None , __UpperCamelCase: float = 1E-5 ):
'''simple docstring'''
super().__init__()
__magic_name__ = num_groups
__magic_name__ = eps
if act_fn is None:
__magic_name__ = None
else:
__magic_name__ = get_activation(__a )
__magic_name__ = nn.Linear(__a , out_dim * 2 )
def _SCREAMING_SNAKE_CASE ( self: List[str] , __UpperCamelCase: Union[str, Any] , __UpperCamelCase: Any ):
'''simple docstring'''
if self.act:
__magic_name__ = self.act(__a )
__magic_name__ = self.linear(__a )
__magic_name__ = emb[:, :, None, None]
__magic_name__ = emb.chunk(2 , dim=1 )
__magic_name__ = F.group_norm(__a , self.num_groups , eps=self.eps )
__magic_name__ = x * (1 + scale) + shift
return x
| 707 |
import os
A__ = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
def _lowercase ( a_ : str ) -> int:
'''simple docstring'''
__magic_name__ = 0
__magic_name__ = 0
while index < len(a_ ) - 1:
__magic_name__ = SYMBOLS[numerals[index]]
__magic_name__ = SYMBOLS[numerals[index + 1]]
if current_value < next_value:
total_value -= current_value
else:
total_value += current_value
index += 1
total_value += SYMBOLS[numerals[index]]
return total_value
def _lowercase ( a_ : int ) -> str:
'''simple docstring'''
__magic_name__ = ''
__magic_name__ = num // 1_0_0_0
numerals += m_count * "M"
num %= 1_0_0_0
__magic_name__ = num // 1_0_0
if c_count == 9:
numerals += "CM"
c_count -= 9
elif c_count == 4:
numerals += "CD"
c_count -= 4
if c_count >= 5:
numerals += "D"
c_count -= 5
numerals += c_count * "C"
num %= 1_0_0
__magic_name__ = num // 1_0
if x_count == 9:
numerals += "XC"
x_count -= 9
elif x_count == 4:
numerals += "XL"
x_count -= 4
if x_count >= 5:
numerals += "L"
x_count -= 5
numerals += x_count * "X"
num %= 1_0
if num == 9:
numerals += "IX"
num -= 9
elif num == 4:
numerals += "IV"
num -= 4
if num >= 5:
numerals += "V"
num -= 5
numerals += num * "I"
return numerals
def _lowercase ( a_ : str = "/p089_roman.txt" ) -> int:
'''simple docstring'''
__magic_name__ = 0
with open(os.path.dirname(a_ ) + roman_numerals_filename ) as filea:
__magic_name__ = filea.readlines()
for line in lines:
__magic_name__ = line.strip()
__magic_name__ = parse_roman_numerals(a_ )
__magic_name__ = generate_roman_numerals(a_ )
savings += len(a_ ) - len(a_ )
return savings
if __name__ == "__main__":
print(f'''{solution() = }''')
| 184 | 0 |
"""simple docstring"""
import platform
from argparse import ArgumentParser
import huggingface_hub
from .. import __version__ as version
from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
from . import BaseDiffusersCLICommand
def lowerCamelCase__ ( _lowerCamelCase ):
'''simple docstring'''
return EnvironmentCommand()
class __UpperCamelCase ( a_ ):
@staticmethod
def __lowerCamelCase ( _A ):
'''simple docstring'''
_lowerCAmelCase : Any = parser.add_parser('env' )
download_parser.set_defaults(func=_lowercase )
def __lowerCamelCase ( self ):
'''simple docstring'''
_lowerCAmelCase : Optional[Any] = huggingface_hub.__version__
_lowerCAmelCase : str = '''not installed'''
_lowerCAmelCase : Union[str, Any] = '''NA'''
if is_torch_available():
import torch
_lowerCAmelCase : Dict = torch.__version__
_lowerCAmelCase : Tuple = torch.cuda.is_available()
_lowerCAmelCase : List[Any] = '''not installed'''
if is_transformers_available():
import transformers
_lowerCAmelCase : List[str] = transformers.__version__
_lowerCAmelCase : List[str] = '''not installed'''
if is_accelerate_available():
import accelerate
_lowerCAmelCase : List[Any] = accelerate.__version__
_lowerCAmelCase : str = '''not installed'''
if is_xformers_available():
import xformers
_lowerCAmelCase : Any = xformers.__version__
_lowerCAmelCase : List[Any] = {
'''`diffusers` version''': version,
'''Platform''': platform.platform(),
'''Python version''': platform.python_version(),
'''PyTorch version (GPU?)''': F"""{pt_version} ({pt_cuda_available})""",
'''Huggingface_hub version''': hub_version,
'''Transformers version''': transformers_version,
'''Accelerate version''': accelerate_version,
'''xFormers version''': xformers_version,
'''Using GPU in script?''': '''<fill in>''',
'''Using distributed or parallel set-up in script?''': '''<fill in>''',
}
print('\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n' )
print(self.format_dict(_lowercase ) )
return info
@staticmethod
def __lowerCamelCase ( _A ):
'''simple docstring'''
return "\n".join([F"""- {prop}: {val}""" for prop, val in d.items()] ) + "\n"
| 259 | """simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
SCREAMING_SNAKE_CASE__ : Dict ={
'configuration_perceiver': ['PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PerceiverConfig', 'PerceiverOnnxConfig'],
'tokenization_perceiver': ['PerceiverTokenizer'],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE__ : Tuple =['PerceiverFeatureExtractor']
SCREAMING_SNAKE_CASE__ : int =['PerceiverImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE__ : Union[str, Any] =[
'PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST',
'PerceiverForImageClassificationConvProcessing',
'PerceiverForImageClassificationFourier',
'PerceiverForImageClassificationLearned',
'PerceiverForMaskedLM',
'PerceiverForMultimodalAutoencoding',
'PerceiverForOpticalFlow',
'PerceiverForSequenceClassification',
'PerceiverLayer',
'PerceiverModel',
'PerceiverPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig
from .tokenization_perceiver import PerceiverTokenizer
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_perceiver import PerceiverFeatureExtractor
from .image_processing_perceiver import PerceiverImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_perceiver import (
PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST,
PerceiverForImageClassificationConvProcessing,
PerceiverForImageClassificationFourier,
PerceiverForImageClassificationLearned,
PerceiverForMaskedLM,
PerceiverForMultimodalAutoencoding,
PerceiverForOpticalFlow,
PerceiverForSequenceClassification,
PerceiverLayer,
PerceiverModel,
PerceiverPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE__ : List[str] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 434 | 0 |
"""simple docstring"""
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import AutoTokenizer, BarkProcessor
from transformers.testing_utils import require_torch, slow
@require_torch
class lowercase__ ( unittest.TestCase ):
'''simple docstring'''
def lowercase__ ( self : Dict ) -> Optional[Any]:
'''simple docstring'''
UpperCAmelCase_ = "ylacombe/bark-small"
UpperCAmelCase_ = tempfile.mkdtemp()
UpperCAmelCase_ = "en_speaker_1"
UpperCAmelCase_ = "This is a test string"
UpperCAmelCase_ = "speaker_embeddings_path.json"
UpperCAmelCase_ = "speaker_embeddings"
def lowercase__ ( self : str , **_UpperCAmelCase : List[Any] ) -> Optional[Any]:
'''simple docstring'''
return AutoTokenizer.from_pretrained(self.checkpoint , **_UpperCAmelCase )
def lowercase__ ( self : List[Any] ) -> Dict:
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def lowercase__ ( self : Optional[Any] ) -> Optional[int]:
'''simple docstring'''
UpperCAmelCase_ = self.get_tokenizer()
UpperCAmelCase_ = BarkProcessor(tokenizer=_UpperCAmelCase )
processor.save_pretrained(self.tmpdirname )
UpperCAmelCase_ = BarkProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
@slow
def lowercase__ ( self : Any ) -> int:
'''simple docstring'''
UpperCAmelCase_ = BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
processor.save_pretrained(
self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , )
UpperCAmelCase_ = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" )
UpperCAmelCase_ = BarkProcessor.from_pretrained(
self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
def lowercase__ ( self : int ) -> List[Any]:
'''simple docstring'''
UpperCAmelCase_ = BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
UpperCAmelCase_ = 35
UpperCAmelCase_ = 2
UpperCAmelCase_ = 8
UpperCAmelCase_ = {
"semantic_prompt": np.ones(_UpperCAmelCase ),
"coarse_prompt": np.ones((nb_codebooks_coarse, seq_len) ),
"fine_prompt": np.ones((nb_codebooks_total, seq_len) ),
}
# test providing already loaded voice_preset
UpperCAmelCase_ = processor(text=self.input_string , voice_preset=_UpperCAmelCase )
UpperCAmelCase_ = inputs["history_prompt"]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_UpperCAmelCase , np.array([] ) ).tolist() )
# test loading voice preset from npz file
UpperCAmelCase_ = os.path.join(self.tmpdirname , "file.npz" )
np.savez(_UpperCAmelCase , **_UpperCAmelCase )
UpperCAmelCase_ = processor(text=self.input_string , voice_preset=_UpperCAmelCase )
UpperCAmelCase_ = inputs["history_prompt"]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_UpperCAmelCase , np.array([] ) ).tolist() )
# test loading voice preset from the hub
UpperCAmelCase_ = processor(text=self.input_string , voice_preset=self.voice_preset )
def lowercase__ ( self : List[str] ) -> int:
'''simple docstring'''
UpperCAmelCase_ = self.get_tokenizer()
UpperCAmelCase_ = BarkProcessor(tokenizer=_UpperCAmelCase )
UpperCAmelCase_ = processor(text=self.input_string )
UpperCAmelCase_ = tokenizer(
self.input_string , padding="max_length" , max_length=256 , add_special_tokens=_UpperCAmelCase , return_attention_mask=_UpperCAmelCase , return_token_type_ids=_UpperCAmelCase , )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
| 14 |
"""simple docstring"""
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
lowerCamelCase = logging.get_logger(__name__)
lowerCamelCase = {
"""google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""",
"""google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""",
# See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
}
class lowercase__ ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
UpperCamelCase = '''mobilenet_v1'''
def __init__( self : Tuple , _UpperCAmelCase : int=3 , _UpperCAmelCase : Union[str, Any]=224 , _UpperCAmelCase : Any=1.0 , _UpperCAmelCase : Any=8 , _UpperCAmelCase : List[Any]="relu6" , _UpperCAmelCase : List[str]=True , _UpperCAmelCase : Dict=0.999 , _UpperCAmelCase : List[Any]=0.02 , _UpperCAmelCase : List[Any]=0.001 , **_UpperCAmelCase : str , ) -> Optional[int]:
'''simple docstring'''
super().__init__(**_UpperCAmelCase )
if depth_multiplier <= 0:
raise ValueError("depth_multiplier must be greater than zero." )
UpperCAmelCase_ = num_channels
UpperCAmelCase_ = image_size
UpperCAmelCase_ = depth_multiplier
UpperCAmelCase_ = min_depth
UpperCAmelCase_ = hidden_act
UpperCAmelCase_ = tf_padding
UpperCAmelCase_ = classifier_dropout_prob
UpperCAmelCase_ = initializer_range
UpperCAmelCase_ = layer_norm_eps
class lowercase__ ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
UpperCamelCase = version.parse('''1.11''' )
@property
def lowercase__ ( self : List[Any] ) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
return OrderedDict([("pixel_values", {0: "batch"})] )
@property
def lowercase__ ( self : List[Any] ) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
if self.task == "image-classification":
return OrderedDict([("logits", {0: "batch"})] )
else:
return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})] )
@property
def lowercase__ ( self : Tuple ) -> float:
'''simple docstring'''
return 1e-4
| 14 | 1 |
'''simple docstring'''
_A: Tuple = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0],
]
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )-> Any:
__UpperCAmelCase = [False] * len(snake_case_ )
__UpperCAmelCase = [s]
__UpperCAmelCase = True
while queue:
__UpperCAmelCase = queue.pop(0 )
for ind in range(len(graph[u] ) ):
if visited[ind] is False and graph[u][ind] > 0:
queue.append(snake_case_ )
__UpperCAmelCase = True
__UpperCAmelCase = u
return visited[t]
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )-> List[str]:
__UpperCAmelCase = [-1] * (len(snake_case_ ))
__UpperCAmelCase = 0
__UpperCAmelCase = []
__UpperCAmelCase = [i[:] for i in graph] # Record original cut, copy.
while bfs(snake_case_ , snake_case_ , snake_case_ , snake_case_ ):
__UpperCAmelCase = float('Inf' )
__UpperCAmelCase = sink
while s != source:
# Find the minimum value in select path
__UpperCAmelCase = min(snake_case_ , graph[parent[s]][s] )
__UpperCAmelCase = parent[s]
max_flow += path_flow
__UpperCAmelCase = sink
while v != source:
__UpperCAmelCase = parent[v]
graph[u][v] -= path_flow
graph[v][u] += path_flow
__UpperCAmelCase = parent[v]
for i in range(len(snake_case_ ) ):
for j in range(len(graph[0] ) ):
if graph[i][j] == 0 and temp[i][j] > 0:
res.append((i, j) )
return res
if __name__ == "__main__":
print(mincut(test_graph, source=0, sink=5))
| 126 |
"""simple docstring"""
import os
import unittest
from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer
from ...test_tokenization_common import TokenizerTesterMixin
class __lowerCamelCase ( __lowercase , unittest.TestCase ):
__UpperCamelCase = PhobertTokenizer
__UpperCamelCase = False
def A__ (self ):
'''simple docstring'''
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
_lowerCAmelCase = ["""T@@""", """i""", """I""", """R@@""", """r""", """e@@"""]
_lowerCAmelCase = dict(zip(lowerCamelCase , range(len(lowerCamelCase ) ) ) )
_lowerCAmelCase = ["""#version: 0.2""", """l à</w>"""]
_lowerCAmelCase = {"""unk_token""": """<unk>"""}
_lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] )
_lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] )
with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp:
for token in vocab_tokens:
fp.write(f"""{token} {vocab_tokens[token]}\n""" )
with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp:
fp.write("""\n""".join(lowerCamelCase ) )
def A__ (self , **lowerCamelCase ):
'''simple docstring'''
kwargs.update(self.special_tokens_map )
return PhobertTokenizer.from_pretrained(self.tmpdirname , **lowerCamelCase )
def A__ (self , lowerCamelCase ):
'''simple docstring'''
_lowerCAmelCase = """Tôi là VinAI Research"""
_lowerCAmelCase = """T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>"""
return input_text, output_text
def A__ (self ):
'''simple docstring'''
_lowerCAmelCase = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
_lowerCAmelCase = """Tôi là VinAI Research"""
_lowerCAmelCase = """T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h""".split()
_lowerCAmelCase = tokenizer.tokenize(lowerCamelCase )
print(lowerCamelCase )
self.assertListEqual(lowerCamelCase , lowerCamelCase )
_lowerCAmelCase = tokens + [tokenizer.unk_token]
_lowerCAmelCase = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3]
self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase ) , lowerCamelCase ) | 156 | 0 |
'''simple docstring'''
from unittest import TestCase
from datasets import Dataset
from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters
def lowerCamelCase__ ( ) -> Dict:
'''simple docstring'''
_snake_case = {
'repo_name': ['test_repo1', 'test_repo2', 'test_repo3'],
'path': ['test_1.py', 'test_2.py', 'unit_test.py'],
'content': ['a ' * 20, 'a ' * 30, 'b ' * 7],
}
_snake_case = Dataset.from_dict(UpperCamelCase__ )
return dataset
class UpperCamelCase_ ( _lowerCamelCase ):
def lowerCAmelCase ( self ) -> List[str]:
_snake_case = get_dataset()
_snake_case = make_duplicate_clusters(lowerCAmelCase_ , 0.85 )
self.assertEqual(len(duplicate_clusters[0] ) , 2 )
def lowerCAmelCase ( self ) -> Union[str, Any]:
_snake_case = get_dataset()
_snake_case , _snake_case = deduplicate_dataset(lowerCAmelCase_ )
self.assertEqual(len(lowerCAmelCase_ ) , 2 )
print(lowerCAmelCase_ )
self.assertEqual(duplicate_clusters[0][0]['copies'] , 2 )
self.assertEqual(duplicate_clusters[0][0]['is_extreme'] , lowerCAmelCase_ )
| 700 |
import argparse
from collections import defaultdict
import yaml
UpperCAmelCase_ = """docs/source/en/_toctree.yml"""
def lowerCamelCase__ ( UpperCamelCase__ : Optional[Any] ) -> str:
'''simple docstring'''
_snake_case = defaultdict(UpperCamelCase__ )
_snake_case = []
_snake_case = []
for doc in doc_list:
if "local" in doc:
counts[doc["local"]] += 1
if doc["title"].lower() == "overview":
overview_doc.append({'local': doc['local'], 'title': doc['title']} )
else:
new_doc_list.append(UpperCamelCase__ )
_snake_case = new_doc_list
_snake_case = [key for key, value in counts.items() if value > 1]
_snake_case = []
for duplicate_key in duplicates:
_snake_case = list({doc['title'] for doc in doc_list if doc['local'] == duplicate_key} )
if len(UpperCamelCase__ ) > 1:
raise ValueError(
F'''{duplicate_key} is present several times in the documentation table of content at '''
'`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '
'others.' )
# Only add this once
new_doc.append({'local': duplicate_key, 'title': titles[0]} )
# Add none duplicate-keys
new_doc.extend([doc for doc in doc_list if 'local' not in counts or counts[doc['local']] == 1] )
_snake_case = sorted(UpperCamelCase__ , key=lambda UpperCamelCase__ : s["title"].lower() )
# "overview" gets special treatment and is always first
if len(UpperCamelCase__ ) > 1:
raise ValueError('{doc_list} has two \'overview\' docs which is not allowed.' )
overview_doc.extend(UpperCamelCase__ )
# Sort
return overview_doc
def lowerCamelCase__ ( UpperCamelCase__ : Dict=False ) -> Optional[int]:
'''simple docstring'''
with open(UpperCamelCase__ , encoding='utf-8' ) as f:
_snake_case = yaml.safe_load(f.read() )
# Get to the API doc
_snake_case = 0
while content[api_idx]["title"] != "API":
api_idx += 1
_snake_case = content[api_idx]['sections']
# Then to the model doc
_snake_case = 0
while api_doc[scheduler_idx]["title"] != "Schedulers":
scheduler_idx += 1
_snake_case = api_doc[scheduler_idx]['sections']
_snake_case = clean_doc_toc(UpperCamelCase__ )
_snake_case = False
if new_scheduler_doc != scheduler_doc:
_snake_case = True
if overwrite:
_snake_case = new_scheduler_doc
if diff:
if overwrite:
_snake_case = api_doc
with open(UpperCamelCase__ , 'w' , encoding='utf-8' ) as f:
f.write(yaml.dump(UpperCamelCase__ , allow_unicode=UpperCamelCase__ ) )
else:
raise ValueError(
'The model doc part of the table of content is not properly sorted, run `make style` to fix this.' )
def lowerCamelCase__ ( UpperCamelCase__ : Tuple=False ) -> List[Any]:
'''simple docstring'''
with open(UpperCamelCase__ , encoding='utf-8' ) as f:
_snake_case = yaml.safe_load(f.read() )
# Get to the API doc
_snake_case = 0
while content[api_idx]["title"] != "API":
api_idx += 1
_snake_case = content[api_idx]['sections']
# Then to the model doc
_snake_case = 0
while api_doc[pipeline_idx]["title"] != "Pipelines":
pipeline_idx += 1
_snake_case = False
_snake_case = api_doc[pipeline_idx]['sections']
_snake_case = []
# sort sub pipeline docs
for pipeline_doc in pipeline_docs:
if "section" in pipeline_doc:
_snake_case = pipeline_doc['section']
_snake_case = clean_doc_toc(UpperCamelCase__ )
if overwrite:
_snake_case = new_sub_pipeline_doc
new_pipeline_docs.append(UpperCamelCase__ )
# sort overall pipeline doc
_snake_case = clean_doc_toc(UpperCamelCase__ )
if new_pipeline_docs != pipeline_docs:
_snake_case = True
if overwrite:
_snake_case = new_pipeline_docs
if diff:
if overwrite:
_snake_case = api_doc
with open(UpperCamelCase__ , 'w' , encoding='utf-8' ) as f:
f.write(yaml.dump(UpperCamelCase__ , allow_unicode=UpperCamelCase__ ) )
else:
raise ValueError(
'The model doc part of the table of content is not properly sorted, run `make style` to fix this.' )
if __name__ == "__main__":
UpperCAmelCase_ = argparse.ArgumentParser()
parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
UpperCAmelCase_ = parser.parse_args()
check_scheduler_doc(args.fix_and_overwrite)
check_pipeline_doc(args.fix_and_overwrite)
| 541 | 0 |
"""simple docstring"""
from __future__ import annotations
import math
from collections.abc import Callable
def _a ( _snake_case , _snake_case , _snake_case , _snake_case = 100 , ):
"""simple docstring"""
UpperCAmelCase = x_start
UpperCAmelCase = fnc(_snake_case )
UpperCAmelCase = 0.0
for _ in range(_snake_case ):
# Approximates curve as a sequence of linear lines and sums their length
UpperCAmelCase = (x_end - x_start) / steps + xa
UpperCAmelCase = fnc(_snake_case )
length += math.hypot(xa - xa , fxa - fxa )
# Increment step
UpperCAmelCase = xa
UpperCAmelCase = fxa
return length
if __name__ == "__main__":
def _a ( _snake_case ):
"""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:""")
_UpperCamelCase = 10
while i <= 100000:
print(F"""With {i} steps: {line_length(f, -10, 10, i)}""")
i *= 10
| 341 |
"""simple docstring"""
def _a ( _snake_case ):
"""simple docstring"""
UpperCAmelCase = len(_snake_case )
for i in range(_snake_case ):
for j in range(i + 1 , _snake_case ):
if numbers[j] < numbers[i]:
UpperCAmelCase , UpperCAmelCase = numbers[j], numbers[i]
return numbers
if __name__ == "__main__":
_UpperCamelCase = input("""Enter numbers separated by a comma:\n""").strip()
_UpperCamelCase = [int(item) for item in user_input.split(""",""")]
print(exchange_sort(unsorted))
| 341 | 1 |
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
lowercase_: Optional[Any] = logging.get_logger(__name__)
lowercase_: List[Any] = {
'google/mobilenet_v1_1.0_224': 'https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json',
'google/mobilenet_v1_0.75_192': 'https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json',
# See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
}
class lowercase__ (__snake_case ):
"""simple docstring"""
__UpperCamelCase : Union[str, Any] = 'mobilenet_v1'
def __init__( self : Tuple , __a : List[str]=3 , __a : Optional[int]=2_2_4 , __a : List[str]=1.0 , __a : Any=8 , __a : Tuple="relu6" , __a : int=True , __a : Optional[Any]=0.999 , __a : Optional[int]=0.02 , __a : Tuple=0.001 , **__a : Tuple , ):
super().__init__(**__a )
if depth_multiplier <= 0:
raise ValueError("""depth_multiplier must be greater than zero.""" )
snake_case__ : Tuple = num_channels
snake_case__ : List[str] = image_size
snake_case__ : Any = depth_multiplier
snake_case__ : Tuple = min_depth
snake_case__ : Optional[Any] = hidden_act
snake_case__ : int = tf_padding
snake_case__ : str = classifier_dropout_prob
snake_case__ : int = initializer_range
snake_case__ : Any = layer_norm_eps
class lowercase__ (__snake_case ):
"""simple docstring"""
__UpperCamelCase : Tuple = version.parse('1.11' )
@property
def lowercase ( self : Optional[Any] ):
return OrderedDict([("""pixel_values""", {0: """batch"""})] )
@property
def lowercase ( self : Dict ):
if self.task == "image-classification":
return OrderedDict([("""logits""", {0: """batch"""})] )
else:
return OrderedDict([("""last_hidden_state""", {0: """batch"""}), ("""pooler_output""", {0: """batch"""})] )
@property
def lowercase ( self : Tuple ):
return 1e-4
| 127 |
from __future__ import annotations
from collections.abc import Callable
from typing import Any, Generic, TypeVar
lowercase_: Union[str, Any] = TypeVar('T')
class lowercase__ (Generic[T] ):
"""simple docstring"""
def __init__( self : List[Any] , __a : list[T] , __a : Callable[[T, T], T] ):
snake_case__ : Any | T = None
snake_case__ : int = len(__a )
snake_case__ : list[T] = [any_type for _ in range(self.N )] + arr
snake_case__ : Tuple = fnc
self.build()
def lowercase ( self : int ):
for p in range(self.N - 1 , 0 , -1 ):
snake_case__ : Tuple = self.fn(self.st[p * 2] , self.st[p * 2 + 1] )
def lowercase ( self : Optional[Any] , __a : int , __a : T ):
p += self.N
snake_case__ : Optional[int] = v
while p > 1:
snake_case__ : int = p // 2
snake_case__ : Dict = self.fn(self.st[p * 2] , self.st[p * 2 + 1] )
def lowercase ( self : int , __a : int , __a : int ): # noqa: E741
snake_case__ , snake_case__ : List[Any] = l + self.N, r + self.N
snake_case__ : T | None = None
while l <= r:
if l % 2 == 1:
snake_case__ : List[str] = self.st[l] if res is None else self.fn(__a , self.st[l] )
if r % 2 == 0:
snake_case__ : Any = self.st[r] if res is None else self.fn(__a , self.st[r] )
snake_case__ , snake_case__ : Tuple = (l + 1) // 2, (r - 1) // 2
return res
if __name__ == "__main__":
from functools import reduce
lowercase_: List[str] = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12]
lowercase_: Optional[Any] = {
0: 7,
1: 2,
2: 6,
3: -14,
4: 5,
5: 4,
6: 7,
7: -10,
8: 9,
9: 10,
10: 12,
11: 1,
}
lowercase_: Optional[Any] = SegmentTree(test_array, min)
lowercase_: Any = SegmentTree(test_array, max)
lowercase_: Optional[int] = SegmentTree(test_array, lambda a, b: a + b)
def _lowercase ( ):
"""simple docstring"""
for i in range(len(UpperCAmelCase_)):
for j in range(UpperCAmelCase_ , len(UpperCAmelCase_)):
snake_case__ : Tuple = reduce(UpperCAmelCase_ , test_array[i : j + 1])
snake_case__ : int = reduce(UpperCAmelCase_ , test_array[i : j + 1])
snake_case__ : Union[str, Any] = reduce(lambda UpperCAmelCase_ , UpperCAmelCase_: a + b , test_array[i : j + 1])
assert min_range == min_segment_tree.query(UpperCAmelCase_ , UpperCAmelCase_)
assert max_range == max_segment_tree.query(UpperCAmelCase_ , UpperCAmelCase_)
assert sum_range == sum_segment_tree.query(UpperCAmelCase_ , UpperCAmelCase_)
test_all_segments()
for index, value in test_updates.items():
lowercase_: Optional[int] = value
min_segment_tree.update(index, value)
max_segment_tree.update(index, value)
sum_segment_tree.update(index, value)
test_all_segments()
| 127 | 1 |
'''simple docstring'''
import argparse
import requests
import torch
# pip3 install salesforce-lavis
# I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis
from lavis.models import load_model_and_preprocess
from PIL import Image
from transformers import (
AutoTokenizer,
BlipaConfig,
BlipaForConditionalGeneration,
BlipaProcessor,
BlipaVisionConfig,
BlipImageProcessor,
OPTConfig,
TaConfig,
)
from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
def _a ():
"""simple docstring"""
_UpperCamelCase ='''https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png'''
_UpperCamelCase =Image.open(requests.get(__SCREAMING_SNAKE_CASE , stream=__SCREAMING_SNAKE_CASE ).raw ).convert('''RGB''' )
return image
def _a (__SCREAMING_SNAKE_CASE ):
"""simple docstring"""
_UpperCamelCase =[]
# fmt: off
# vision encoder
rename_keys.append(('''visual_encoder.cls_token''', '''vision_model.embeddings.class_embedding''') )
rename_keys.append(('''visual_encoder.pos_embed''', '''vision_model.embeddings.position_embedding''') )
rename_keys.append(('''visual_encoder.patch_embed.proj.weight''', '''vision_model.embeddings.patch_embedding.weight''') )
rename_keys.append(('''visual_encoder.patch_embed.proj.bias''', '''vision_model.embeddings.patch_embedding.bias''') )
rename_keys.append(('''ln_vision.weight''', '''vision_model.post_layernorm.weight''') )
rename_keys.append(('''ln_vision.bias''', '''vision_model.post_layernorm.bias''') )
for i in range(config.vision_config.num_hidden_layers ):
rename_keys.append((f'''visual_encoder.blocks.{i}.norm1.weight''', f'''vision_model.encoder.layers.{i}.layer_norm1.weight''') )
rename_keys.append((f'''visual_encoder.blocks.{i}.norm1.bias''', f'''vision_model.encoder.layers.{i}.layer_norm1.bias''') )
rename_keys.append((f'''visual_encoder.blocks.{i}.norm2.weight''', f'''vision_model.encoder.layers.{i}.layer_norm2.weight''') )
rename_keys.append((f'''visual_encoder.blocks.{i}.norm2.bias''', f'''vision_model.encoder.layers.{i}.layer_norm2.bias''') )
rename_keys.append((f'''visual_encoder.blocks.{i}.attn.qkv.weight''', f'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') )
rename_keys.append((f'''visual_encoder.blocks.{i}.attn.proj.weight''', f'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) )
rename_keys.append((f'''visual_encoder.blocks.{i}.attn.proj.bias''', f'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') )
rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc1.weight''', f'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') )
rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc1.bias''', f'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') )
rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc2.weight''', f'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') )
rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc2.bias''', f'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') )
# QFormer
rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.weight''', '''qformer.layernorm.weight''') )
rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.bias''', '''qformer.layernorm.bias''') )
# fmt: on
return rename_keys
def _a (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
"""simple docstring"""
_UpperCamelCase =dct.pop(__SCREAMING_SNAKE_CASE )
_UpperCamelCase =val
def _a (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
"""simple docstring"""
for i in range(config.vision_config.num_hidden_layers ):
# read in original q and v biases
_UpperCamelCase =state_dict.pop(f'''visual_encoder.blocks.{i}.attn.q_bias''' )
_UpperCamelCase =state_dict.pop(f'''visual_encoder.blocks.{i}.attn.v_bias''' )
# next, set bias in the state dict
_UpperCamelCase =torch.cat((q_bias, torch.zeros_like(__SCREAMING_SNAKE_CASE , requires_grad=__SCREAMING_SNAKE_CASE ), v_bias) )
_UpperCamelCase =qkv_bias
def _a (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
"""simple docstring"""
_UpperCamelCase =364 if '''coco''' in model_name else 224
_UpperCamelCase =BlipaVisionConfig(image_size=__SCREAMING_SNAKE_CASE ).to_dict()
# make sure the models have proper bos_token_id and eos_token_id set (important for generation)
# seems like flan-T5 models don't have bos_token_id properly set?
if "opt-2.7b" in model_name:
_UpperCamelCase =OPTConfig.from_pretrained('''facebook/opt-2.7b''' , eos_token_id=__SCREAMING_SNAKE_CASE ).to_dict()
elif "opt-6.7b" in model_name:
_UpperCamelCase =OPTConfig.from_pretrained('''facebook/opt-6.7b''' , eos_token_id=__SCREAMING_SNAKE_CASE ).to_dict()
elif "t5-xl" in model_name:
_UpperCamelCase =TaConfig.from_pretrained('''google/flan-t5-xl''' , dense_act_fn='''gelu''' , bos_token_id=1 ).to_dict()
elif "t5-xxl" in model_name:
_UpperCamelCase =TaConfig.from_pretrained('''google/flan-t5-xxl''' , dense_act_fn='''gelu''' , bos_token_id=1 ).to_dict()
_UpperCamelCase =BlipaConfig(vision_config=__SCREAMING_SNAKE_CASE , text_config=__SCREAMING_SNAKE_CASE )
return config, image_size
@torch.no_grad()
def _a (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=False ):
"""simple docstring"""
_UpperCamelCase =(
AutoTokenizer.from_pretrained('''facebook/opt-2.7b''' )
if '''opt''' in model_name
else AutoTokenizer.from_pretrained('''google/flan-t5-xl''' )
)
_UpperCamelCase =tokenizer('''\n''' , add_special_tokens=__SCREAMING_SNAKE_CASE ).input_ids[0]
_UpperCamelCase , _UpperCamelCase =get_blipa_config(__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE )
_UpperCamelCase =BlipaForConditionalGeneration(__SCREAMING_SNAKE_CASE ).eval()
_UpperCamelCase ={
'''blip2-opt-2.7b''': ('''blip2_opt''', '''pretrain_opt2.7b'''),
'''blip2-opt-6.7b''': ('''blip2_opt''', '''pretrain_opt6.7b'''),
'''blip2-opt-2.7b-coco''': ('''blip2_opt''', '''caption_coco_opt2.7b'''),
'''blip2-opt-6.7b-coco''': ('''blip2_opt''', '''caption_coco_opt6.7b'''),
'''blip2-flan-t5-xl''': ('''blip2_t5''', '''pretrain_flant5xl'''),
'''blip2-flan-t5-xl-coco''': ('''blip2_t5''', '''caption_coco_flant5xl'''),
'''blip2-flan-t5-xxl''': ('''blip2_t5''', '''pretrain_flant5xxl'''),
}
_UpperCamelCase , _UpperCamelCase =model_name_to_original[model_name]
# load original model
print('''Loading original model...''' )
_UpperCamelCase ='''cuda''' if torch.cuda.is_available() else '''cpu'''
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase =load_model_and_preprocess(
name=__SCREAMING_SNAKE_CASE , model_type=__SCREAMING_SNAKE_CASE , is_eval=__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE )
original_model.eval()
print('''Done!''' )
# update state dict keys
_UpperCamelCase =original_model.state_dict()
_UpperCamelCase =create_rename_keys(__SCREAMING_SNAKE_CASE )
for src, dest in rename_keys:
rename_key(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
# some keys can be renamed efficiently
for key, val in state_dict.copy().items():
_UpperCamelCase =state_dict.pop(__SCREAMING_SNAKE_CASE )
if key.startswith('''Qformer.bert''' ):
_UpperCamelCase =key.replace('''Qformer.bert''' , '''qformer''' )
if "attention.self" in key:
_UpperCamelCase =key.replace('''self''' , '''attention''' )
if "opt_proj" in key:
_UpperCamelCase =key.replace('''opt_proj''' , '''language_projection''' )
if "t5_proj" in key:
_UpperCamelCase =key.replace('''t5_proj''' , '''language_projection''' )
if key.startswith('''opt''' ):
_UpperCamelCase =key.replace('''opt''' , '''language''' )
if key.startswith('''t5''' ):
_UpperCamelCase =key.replace('''t5''' , '''language''' )
_UpperCamelCase =val
# read in qv biases
read_in_q_v_bias(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
_UpperCamelCase , _UpperCamelCase =hf_model.load_state_dict(__SCREAMING_SNAKE_CASE , strict=__SCREAMING_SNAKE_CASE )
assert len(__SCREAMING_SNAKE_CASE ) == 0
assert unexpected_keys == ["qformer.embeddings.position_ids"]
_UpperCamelCase =load_demo_image()
_UpperCamelCase =vis_processors['''eval'''](__SCREAMING_SNAKE_CASE ).unsqueeze(0 ).to(__SCREAMING_SNAKE_CASE )
_UpperCamelCase =tokenizer(['''\n'''] , return_tensors='''pt''' ).input_ids.to(__SCREAMING_SNAKE_CASE )
# create processor
_UpperCamelCase =BlipImageProcessor(
size={'''height''': image_size, '''width''': image_size} , image_mean=__SCREAMING_SNAKE_CASE , image_std=__SCREAMING_SNAKE_CASE )
_UpperCamelCase =BlipaProcessor(image_processor=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE )
_UpperCamelCase =processor(images=__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values.to(__SCREAMING_SNAKE_CASE )
# make sure processor creates exact same pixel values
assert torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
original_model.to(__SCREAMING_SNAKE_CASE )
hf_model.to(__SCREAMING_SNAKE_CASE )
with torch.no_grad():
if "opt" in model_name:
_UpperCamelCase =original_model({'''image''': original_pixel_values, '''text_input''': ['''''']} ).logits
_UpperCamelCase =hf_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).logits
else:
_UpperCamelCase =original_model(
{'''image''': original_pixel_values, '''text_input''': ['''\n'''], '''text_output''': ['''\n''']} ).logits
_UpperCamelCase =input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100 )
_UpperCamelCase =hf_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ).logits
assert original_logits.shape == logits.shape
print('''First values of original logits:''' , original_logits[0, :3, :3] )
print('''First values of HF logits:''' , logits[0, :3, :3] )
# assert values
if model_name == "blip2-flan-t5-xl":
_UpperCamelCase =torch.tensor(
[[-4_1.5_8_5_0, -4.4_4_4_0, -8.9_9_2_2], [-4_7.4_3_2_2, -5.9_1_4_3, -1.7_3_4_0]] , device=__SCREAMING_SNAKE_CASE )
assert torch.allclose(logits[0, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4 )
elif model_name == "blip2-flan-t5-xl-coco":
_UpperCamelCase =torch.tensor(
[[-5_7.0_1_0_9, -9.8_9_6_7, -1_2.6_2_8_0], [-6_8.6_5_7_8, -1_2.7_1_9_1, -1_0.5_0_6_5]] , device=__SCREAMING_SNAKE_CASE )
else:
# cast to same type
_UpperCamelCase =logits.dtype
assert torch.allclose(original_logits.to(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , atol=1E-2 )
print('''Looks ok!''' )
print('''Generating a caption...''' )
_UpperCamelCase =''''''
_UpperCamelCase =tokenizer(__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).input_ids.to(__SCREAMING_SNAKE_CASE )
_UpperCamelCase =original_model.generate({'''image''': original_pixel_values} )
_UpperCamelCase =hf_model.generate(
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , do_sample=__SCREAMING_SNAKE_CASE , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , )
print('''Original generation:''' , __SCREAMING_SNAKE_CASE )
_UpperCamelCase =input_ids.shape[1]
_UpperCamelCase =processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=__SCREAMING_SNAKE_CASE )
_UpperCamelCase =[text.strip() for text in output_text]
print('''HF generation:''' , __SCREAMING_SNAKE_CASE )
if pytorch_dump_folder_path is not None:
processor.save_pretrained(__SCREAMING_SNAKE_CASE )
hf_model.save_pretrained(__SCREAMING_SNAKE_CASE )
if push_to_hub:
processor.push_to_hub(f'''nielsr/{model_name}''' )
hf_model.push_to_hub(f'''nielsr/{model_name}''' )
if __name__ == "__main__":
__lowerCamelCase : List[str] = argparse.ArgumentParser()
__lowerCamelCase : str = [
'blip2-opt-2.7b',
'blip2-opt-6.7b',
'blip2-opt-2.7b-coco',
'blip2-opt-6.7b-coco',
'blip2-flan-t5-xl',
'blip2-flan-t5-xl-coco',
'blip2-flan-t5-xxl',
]
parser.add_argument(
'--model_name',
default='blip2-opt-2.7b',
choices=choices,
type=str,
help='Path to hf config.json of model to convert',
)
parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
parser.add_argument(
'--push_to_hub',
action='store_true',
help='Whether to push the model and processor to the hub after converting',
)
__lowerCamelCase : Union[str, Any] = parser.parse_args()
convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 404 |
'''simple docstring'''
import json
import os
import unittest
from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import (
VOCAB_FILES_NAMES,
GPTSanJapaneseTokenizer,
)
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class UpperCAmelCase ( lowercase_ , unittest.TestCase):
"""simple docstring"""
lowerCAmelCase_ = GPTSanJapaneseTokenizer
lowerCAmelCase_ = False
lowerCAmelCase_ = {"""do_clean_text""": False, """add_prefix_space""": False}
def UpperCamelCase__ ( self : Tuple ) -> Optional[Any]:
super().setUp()
# fmt: off
_UpperCamelCase =['''こん''', '''こんに''', '''にちは''', '''ばんは''', '''世界,㔺界''', '''、''', '''。''', '''<BR>''', '''<SP>''', '''<TAB>''', '''<URL>''', '''<EMAIL>''', '''<TEL>''', '''<DATE>''', '''<PRICE>''', '''<BLOCK>''', '''<KIGOU>''', '''<U2000U2BFF>''', '''<|emoji1|>''', '''<unk>''', '''<|bagoftoken|>''', '''<|endoftext|>''']
# fmt: on
_UpperCamelCase ={'''emoji''': {'''\ud83d\ude00''': '''<|emoji1|>'''}, '''emoji_inv''': {'''<|emoji1|>''': '''\ud83d\ude00'''}} # 😀
_UpperCamelCase ={'''unk_token''': '''<unk>'''}
_UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
_UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''emoji_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
with open(self.emoji_file , '''w''' ) as emoji_writer:
emoji_writer.write(json.dumps(UpperCamelCase__ ) )
def UpperCamelCase__ ( self : Optional[Any] , **UpperCamelCase__ : List[Any] ) -> Dict:
kwargs.update(self.special_tokens_map )
return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ )
def UpperCamelCase__ ( self : str , UpperCamelCase__ : List[str] ) -> int:
_UpperCamelCase ='''こんにちは、世界。 \nこんばんは、㔺界。😀'''
_UpperCamelCase ='''こんにちは、世界。 \nこんばんは、世界。😀'''
return input_text, output_text
def UpperCamelCase__ ( self : Union[str, Any] , UpperCamelCase__ : List[Any] ) -> List[Any]:
_UpperCamelCase , _UpperCamelCase =self.get_input_output_texts(UpperCamelCase__ )
_UpperCamelCase =tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ )
_UpperCamelCase =tokenizer.decode(UpperCamelCase__ , clean_up_tokenization_spaces=UpperCamelCase__ )
return text, ids
def UpperCamelCase__ ( self : Tuple ) -> Dict:
pass # TODO add if relevant
def UpperCamelCase__ ( self : Union[str, Any] ) -> List[Any]:
pass # TODO add if relevant
def UpperCamelCase__ ( self : Tuple ) -> int:
pass # TODO add if relevant
def UpperCamelCase__ ( self : Optional[Any] ) -> Optional[Any]:
_UpperCamelCase =self.get_tokenizer()
# Testing tokenization
_UpperCamelCase ='''こんにちは、世界。 こんばんは、㔺界。'''
_UpperCamelCase =['''こん''', '''にちは''', '''、''', '''世界''', '''。''', '''<SP>''', '''こん''', '''ばんは''', '''、''', '''㔺界''', '''。''']
_UpperCamelCase =tokenizer.tokenize(UpperCamelCase__ )
self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ )
# Testing conversion to ids without special tokens
_UpperCamelCase =[0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6]
_UpperCamelCase =tokenizer.convert_tokens_to_ids(UpperCamelCase__ )
self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ )
# Testing conversion to ids with special tokens
_UpperCamelCase =tokens + [tokenizer.unk_token]
_UpperCamelCase =[0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19]
_UpperCamelCase =tokenizer.convert_tokens_to_ids(UpperCamelCase__ )
self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ )
def UpperCamelCase__ ( self : Optional[Any] ) -> Optional[int]:
_UpperCamelCase =self.get_tokenizer()
# Testing tokenization
_UpperCamelCase ='''こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。'''
_UpperCamelCase ='''こんにちは、、、、世界。こんばんは、、、、世界。'''
_UpperCamelCase =tokenizer.encode(UpperCamelCase__ )
_UpperCamelCase =tokenizer.decode(UpperCamelCase__ )
self.assertEqual(UpperCamelCase__ , UpperCamelCase__ )
@slow
def UpperCamelCase__ ( self : str ) -> str:
_UpperCamelCase =self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' )
# Testing tokenization
_UpperCamelCase ='''こんにちは、世界。'''
_UpperCamelCase ='''こんばんは、㔺界。😀'''
_UpperCamelCase ='''こんにちは、世界。こんばんは、世界。😀'''
_UpperCamelCase =tokenizer.encode(prefix_text + input_text )
_UpperCamelCase =tokenizer.encode('''''' , prefix_text=prefix_text + input_text )
_UpperCamelCase =tokenizer.encode(UpperCamelCase__ , prefix_text=UpperCamelCase__ )
_UpperCamelCase =tokenizer.decode(UpperCamelCase__ )
_UpperCamelCase =tokenizer.decode(UpperCamelCase__ )
_UpperCamelCase =tokenizer.decode(UpperCamelCase__ )
self.assertEqual(UpperCamelCase__ , UpperCamelCase__ )
self.assertEqual(UpperCamelCase__ , UpperCamelCase__ )
self.assertEqual(UpperCamelCase__ , UpperCamelCase__ )
@slow
def UpperCamelCase__ ( self : Optional[int] ) -> Any:
_UpperCamelCase =self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' )
# Testing tokenization
_UpperCamelCase ='''こんにちは、世界。'''
_UpperCamelCase ='''こんばんは、㔺界。😀'''
_UpperCamelCase =len(tokenizer.encode(UpperCamelCase__ ) ) - 2
_UpperCamelCase =len(tokenizer.encode(UpperCamelCase__ ) ) - 2
_UpperCamelCase =[1] + [0] * (len_prefix + len_text + 1)
_UpperCamelCase =[1] * (len_prefix + len_text + 1) + [0]
_UpperCamelCase =[1] + [1] * (len_prefix) + [0] * (len_text + 1)
_UpperCamelCase =tokenizer(prefix_text + input_text ).token_type_ids
_UpperCamelCase =tokenizer('''''' , prefix_text=prefix_text + input_text ).token_type_ids
_UpperCamelCase =tokenizer(UpperCamelCase__ , prefix_text=UpperCamelCase__ ).token_type_ids
self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ )
self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ )
self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ )
@slow
def UpperCamelCase__ ( self : List[Any] ) -> Optional[Any]:
_UpperCamelCase =self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' )
_UpperCamelCase =tokenizer.encode('''あンいワ''' )
_UpperCamelCase =tokenizer.encode('''''' , prefix_text='''あンいワ''' )
_UpperCamelCase =tokenizer.encode('''いワ''' , prefix_text='''あン''' )
self.assertEqual(tokenizer.decode(UpperCamelCase__ ) , tokenizer.decode(UpperCamelCase__ ) )
self.assertEqual(tokenizer.decode(UpperCamelCase__ ) , tokenizer.decode(UpperCamelCase__ ) )
self.assertNotEqual(UpperCamelCase__ , UpperCamelCase__ )
self.assertNotEqual(UpperCamelCase__ , UpperCamelCase__ )
self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token
self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token
@slow
def UpperCamelCase__ ( self : Tuple ) -> Dict:
_UpperCamelCase =self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' )
_UpperCamelCase =[['''武田信玄''', '''は、'''], ['''織田信長''', '''の配下の、''']]
_UpperCamelCase =tokenizer(UpperCamelCase__ , padding=UpperCamelCase__ )
_UpperCamelCase =tokenizer.batch_encode_plus(UpperCamelCase__ , padding=UpperCamelCase__ )
# fmt: off
_UpperCamelCase =[[3_5993, 8640, 2_5948, 3_5998, 3_0647, 3_5675, 3_5999, 3_5999], [3_5993, 1_0382, 9868, 3_5998, 3_0646, 9459, 3_0646, 3_5675]]
_UpperCamelCase =[[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]]
_UpperCamelCase =[[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]]
# fmt: on
self.assertListEqual(x_token.input_ids , UpperCamelCase__ )
self.assertListEqual(x_token.token_type_ids , UpperCamelCase__ )
self.assertListEqual(x_token.attention_mask , UpperCamelCase__ )
self.assertListEqual(x_token_a.input_ids , UpperCamelCase__ )
self.assertListEqual(x_token_a.token_type_ids , UpperCamelCase__ )
self.assertListEqual(x_token_a.attention_mask , UpperCamelCase__ )
def UpperCamelCase__ ( self : Optional[int] ) -> int:
# Intentionally convert some words to accommodate character fluctuations unique to Japanese
pass
def UpperCamelCase__ ( self : Dict ) -> Optional[int]:
# tokenizer has no padding token
pass
| 404 | 1 |
import re
import jax.numpy as jnp
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.random import PRNGKey
from ..utils import logging
SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger(__name__)
def _a ( lowercase__ : List[Any] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Dict = r'\w+[.]\d+'
SCREAMING_SNAKE_CASE__ : Dict = re.findall(lowercase__ , lowercase__ )
for pat in pats:
SCREAMING_SNAKE_CASE__ : int = key.replace(lowercase__ , '_'.join(pat.split('.' ) ) )
return key
def _a ( lowercase__ : List[str] , lowercase__ : int , lowercase__ : List[Any] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Union[str, Any] = pt_tuple_key[:-1] + ('scale',)
if (
any('norm' in str_ for str_ in pt_tuple_key )
and (pt_tuple_key[-1] == "bias")
and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
):
SCREAMING_SNAKE_CASE__ : int = pt_tuple_key[:-1] + ('scale',)
return renamed_pt_tuple_key, pt_tensor
elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
SCREAMING_SNAKE_CASE__ : List[Any] = pt_tuple_key[:-1] + ('scale',)
return renamed_pt_tuple_key, pt_tensor
# embedding
if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
SCREAMING_SNAKE_CASE__ : Optional[int] = pt_tuple_key[:-1] + ('embedding',)
return renamed_pt_tuple_key, pt_tensor
# conv layer
SCREAMING_SNAKE_CASE__ : List[Any] = pt_tuple_key[:-1] + ('kernel',)
if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
SCREAMING_SNAKE_CASE__ : Optional[int] = pt_tensor.transpose(2 , 3 , 1 , 0 )
return renamed_pt_tuple_key, pt_tensor
# linear layer
SCREAMING_SNAKE_CASE__ : int = pt_tuple_key[:-1] + ('kernel',)
if pt_tuple_key[-1] == "weight":
SCREAMING_SNAKE_CASE__ : Dict = pt_tensor.T
return renamed_pt_tuple_key, pt_tensor
# old PyTorch layer norm weight
SCREAMING_SNAKE_CASE__ : Optional[int] = pt_tuple_key[:-1] + ('weight',)
if pt_tuple_key[-1] == "gamma":
return renamed_pt_tuple_key, pt_tensor
# old PyTorch layer norm bias
SCREAMING_SNAKE_CASE__ : Dict = pt_tuple_key[:-1] + ('bias',)
if pt_tuple_key[-1] == "beta":
return renamed_pt_tuple_key, pt_tensor
return pt_tuple_key, pt_tensor
def _a ( lowercase__ : Tuple , lowercase__ : Tuple , lowercase__ : List[str]=42 ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Optional[int] = {k: v.numpy() for k, v in pt_state_dict.items()}
# Step 2: Since the model is stateless, get random Flax params
SCREAMING_SNAKE_CASE__ : int = flax_model.init_weights(PRNGKey(lowercase__ ) )
SCREAMING_SNAKE_CASE__ : Any = flatten_dict(lowercase__ )
SCREAMING_SNAKE_CASE__ : List[Any] = {}
# Need to change some parameters name to match Flax names
for pt_key, pt_tensor in pt_state_dict.items():
SCREAMING_SNAKE_CASE__ : Any = rename_key(lowercase__ )
SCREAMING_SNAKE_CASE__ : Dict = tuple(renamed_pt_key.split('.' ) )
# Correctly rename weight parameters
SCREAMING_SNAKE_CASE__ : Dict = rename_key_and_reshape_tensor(lowercase__ , lowercase__ , lowercase__ )
if flax_key in random_flax_state_dict:
if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
raise ValueError(
f'''PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape '''
f'''{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.''' )
# also add unexpected weight so that warning is thrown
SCREAMING_SNAKE_CASE__ : Dict = jnp.asarray(lowercase__ )
return unflatten_dict(lowercase__ )
| 702 | import heapq as hq
import math
from collections.abc import Iterator
class snake_case :
def __init__( self : str , a_ : str )-> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : List[str] = str(id_ )
SCREAMING_SNAKE_CASE__ : Any = None
SCREAMING_SNAKE_CASE__ : Optional[Any] = None
SCREAMING_SNAKE_CASE__ : Any = []
SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance}
def __lt__( self : int , a_ : Tuple )-> Union[str, Any]:
"""simple docstring"""
return self.key < other.key
def __repr__( self : Any )-> Dict:
"""simple docstring"""
return self.id
def __lowercase( self : Optional[Any] , a_ : int )-> List[str]:
"""simple docstring"""
self.neighbors.append(a_ )
def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Tuple = weight
def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ):
'''simple docstring'''
graph[a - 1].add_neighbor(graph[b - 1] )
graph[b - 1].add_neighbor(graph[a - 1] )
# add the edges:
graph[a - 1].add_edge(graph[b - 1] , lowercase__ )
graph[b - 1].add_edge(graph[a - 1] , lowercase__ )
def _a ( lowercase__ : list , lowercase__ : Vertex ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Any = []
for u in graph:
SCREAMING_SNAKE_CASE__ : Dict = math.inf
SCREAMING_SNAKE_CASE__ : str = None
SCREAMING_SNAKE_CASE__ : List[str] = 0
SCREAMING_SNAKE_CASE__ : int = graph[:]
while q:
SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ )
q.remove(lowercase__ )
for v in u.neighbors:
if (v in q) and (u.edges[v.id] < v.key):
SCREAMING_SNAKE_CASE__ : int = u
SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id]
for i in range(1 , len(lowercase__ ) ):
a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) )
return a
def _a ( lowercase__ : list , lowercase__ : Vertex ):
'''simple docstring'''
for u in graph:
SCREAMING_SNAKE_CASE__ : List[str] = math.inf
SCREAMING_SNAKE_CASE__ : int = None
SCREAMING_SNAKE_CASE__ : Optional[Any] = 0
SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ )
hq.heapify(lowercase__ )
while h:
SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ )
for v in u.neighbors:
if (v in h) and (u.edges[v.id] < v.key):
SCREAMING_SNAKE_CASE__ : List[str] = u
SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id]
hq.heapify(lowercase__ )
for i in range(1 , len(lowercase__ ) ):
yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1)
def _a ( ):
'''simple docstring'''
if __name__ == "__main__":
import doctest
doctest.testmod()
| 636 | 0 |
"""simple docstring"""
def _UpperCamelCase ( UpperCamelCase ) -> int:
"""simple docstring"""
__UpperCAmelCase : List[Any] = [1]
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Any = 0, 0, 0
__UpperCAmelCase : Tuple = ugly_nums[ia] * 2
__UpperCAmelCase : List[Any] = ugly_nums[ia] * 3
__UpperCAmelCase : Optional[int] = ugly_nums[ia] * 5
for _ in range(1 , UpperCamelCase ):
__UpperCAmelCase : Union[str, Any] = min(UpperCamelCase , UpperCamelCase , UpperCamelCase )
ugly_nums.append(UpperCamelCase )
if next_num == next_a:
ia += 1
__UpperCAmelCase : Dict = ugly_nums[ia] * 2
if next_num == next_a:
ia += 1
__UpperCAmelCase : Optional[int] = ugly_nums[ia] * 3
if next_num == next_a:
ia += 1
__UpperCAmelCase : Tuple = ugly_nums[ia] * 5
return ugly_nums[-1]
if __name__ == "__main__":
from doctest import testmod
testmod(verbose=True)
print(f'''{ugly_numbers(200) = }''')
| 77 |
'''simple docstring'''
lowerCAmelCase__ = 'Alexander Joslin'
import operator as op
from .stack import Stack
def __UpperCAmelCase ( lowerCamelCase_) -> int:
UpperCamelCase__ : List[str] = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub}
UpperCamelCase__ : Stack[int] = Stack()
UpperCamelCase__ : Stack[str] = Stack()
for i in equation:
if i.isdigit():
# RULE 1
operand_stack.push(int(lowerCamelCase_))
elif i in operators:
# RULE 2
operator_stack.push(lowerCamelCase_)
elif i == ")":
# RULE 4
UpperCamelCase__ : Optional[Any] = operator_stack.peek()
operator_stack.pop()
UpperCamelCase__ : Optional[Any] = operand_stack.peek()
operand_stack.pop()
UpperCamelCase__ : List[Any] = operand_stack.peek()
operand_stack.pop()
UpperCamelCase__ : List[Any] = operators[opr](lowerCamelCase_ , lowerCamelCase_)
operand_stack.push(lowerCamelCase_)
# RULE 5
return operand_stack.peek()
if __name__ == "__main__":
lowerCAmelCase__ = '(5 + ((4 * 2) * (2 + 3)))'
# answer = 45
print(f'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
| 596 | 0 |
"""simple docstring"""
from __future__ import annotations
from random import choice
def _lowerCamelCase ( UpperCAmelCase_ : str ) -> Union[str, Any]:
"""simple docstring"""
return choice(UpperCAmelCase_ )
def _lowerCamelCase ( UpperCAmelCase_ : list[int], UpperCAmelCase_ : int ) -> int:
"""simple docstring"""
A__ = random_pivot(UpperCAmelCase_ )
# partition based on pivot
# linear time
A__ = [e for e in lst if e < pivot]
A__ = [e for e in lst if e > pivot]
# if we get lucky, pivot might be the element we want.
# we can easily see this:
# small (elements smaller than k)
# + pivot (kth element)
# + big (elements larger than k)
if len(UpperCAmelCase_ ) == k - 1:
return pivot
# pivot is in elements bigger than k
elif len(UpperCAmelCase_ ) < k - 1:
return kth_number(UpperCAmelCase_, k - len(UpperCAmelCase_ ) - 1 )
# pivot is in elements smaller than k
else:
return kth_number(UpperCAmelCase_, UpperCAmelCase_ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 562 |
"""simple docstring"""
from __future__ import annotations
from fractions import Fraction
def _lowerCamelCase ( UpperCAmelCase_ : int, UpperCAmelCase_ : int ) -> bool:
"""simple docstring"""
return (
num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den
)
def _lowerCamelCase ( UpperCAmelCase_ : int ) -> list[str]:
"""simple docstring"""
A__ = []
A__ = 11
A__ = int("1" + "0" * digit_len )
for num in range(UpperCAmelCase_, UpperCAmelCase_ ):
while den <= 99:
if (num != den) and (num % 10 == den // 10) and (den % 10 != 0):
if is_digit_cancelling(UpperCAmelCase_, UpperCAmelCase_ ):
solutions.append(F"""{num}/{den}""" )
den += 1
num += 1
A__ = 10
return solutions
def _lowerCamelCase ( UpperCAmelCase_ : int = 2 ) -> int:
"""simple docstring"""
A__ = 1.0
for fraction in fraction_list(UpperCAmelCase_ ):
A__ = Fraction(UpperCAmelCase_ )
result *= frac.denominator / frac.numerator
return int(UpperCAmelCase_ )
if __name__ == "__main__":
print(solution())
| 562 | 1 |
import pyarrow.parquet as pq
import pytest
from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config
from datasets.features.image import Image
from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def lowerCamelCase__ ( lowercase , lowercase ):
"""simple docstring"""
assert isinstance(lowercase , lowercase )
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def lowerCamelCase__ ( lowercase , lowercase , lowercase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = tmp_path / "cache"
SCREAMING_SNAKE_CASE : str = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
SCREAMING_SNAKE_CASE : int = ParquetDatasetReader(lowercase , cache_dir=lowercase , keep_in_memory=lowercase ).read()
_check_parquet_dataset(lowercase , lowercase )
@pytest.mark.parametrize(
"features" , [
None,
{"col_1": "string", "col_2": "int64", "col_3": "float64"},
{"col_1": "string", "col_2": "string", "col_3": "string"},
{"col_1": "int32", "col_2": "int32", "col_3": "int32"},
{"col_1": "float32", "col_2": "float32", "col_3": "float32"},
] , )
def lowerCamelCase__ ( lowercase , lowercase , lowercase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[Any] = tmp_path / "cache"
SCREAMING_SNAKE_CASE : int = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
SCREAMING_SNAKE_CASE : str = features.copy() if features else default_expected_features
SCREAMING_SNAKE_CASE : str = (
Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None
)
SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader(lowercase , features=lowercase , cache_dir=lowercase ).read()
_check_parquet_dataset(lowercase , lowercase )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def lowerCamelCase__ ( lowercase , lowercase , lowercase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Any = tmp_path / "cache"
SCREAMING_SNAKE_CASE : Any = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
SCREAMING_SNAKE_CASE : str = ParquetDatasetReader(lowercase , cache_dir=lowercase , split=lowercase ).read()
_check_parquet_dataset(lowercase , lowercase )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize("path_type" , [str, list] )
def lowerCamelCase__ ( lowercase , lowercase , lowercase ):
"""simple docstring"""
if issubclass(lowercase , lowercase ):
SCREAMING_SNAKE_CASE : Union[str, Any] = parquet_path
elif issubclass(lowercase , lowercase ):
SCREAMING_SNAKE_CASE : Any = [parquet_path]
SCREAMING_SNAKE_CASE : str = tmp_path / "cache"
SCREAMING_SNAKE_CASE : str = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
SCREAMING_SNAKE_CASE : str = ParquetDatasetReader(lowercase , cache_dir=lowercase ).read()
_check_parquet_dataset(lowercase , lowercase )
def lowerCamelCase__ ( lowercase , lowercase , lowercase=("train",) ):
"""simple docstring"""
assert isinstance(lowercase , lowercase )
for split in splits:
SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def lowerCamelCase__ ( lowercase , lowercase , lowercase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[int] = tmp_path / "cache"
SCREAMING_SNAKE_CASE : str = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
SCREAMING_SNAKE_CASE : List[Any] = ParquetDatasetReader(
{"train": parquet_path} , cache_dir=lowercase , keep_in_memory=lowercase ).read()
_check_parquet_datasetdict(lowercase , lowercase )
@pytest.mark.parametrize(
"features" , [
None,
{"col_1": "string", "col_2": "int64", "col_3": "float64"},
{"col_1": "string", "col_2": "string", "col_3": "string"},
{"col_1": "int32", "col_2": "int32", "col_3": "int32"},
{"col_1": "float32", "col_2": "float32", "col_3": "float32"},
] , )
def lowerCamelCase__ ( lowercase , lowercase , lowercase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : int = tmp_path / "cache"
SCREAMING_SNAKE_CASE : int = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
SCREAMING_SNAKE_CASE : Optional[int] = features.copy() if features else default_expected_features
SCREAMING_SNAKE_CASE : Dict = (
Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None
)
SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetReader({"train": parquet_path} , features=lowercase , cache_dir=lowercase ).read()
_check_parquet_datasetdict(lowercase , lowercase )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def lowerCamelCase__ ( lowercase , lowercase , lowercase ):
"""simple docstring"""
if split:
SCREAMING_SNAKE_CASE : Dict = {split: parquet_path}
else:
SCREAMING_SNAKE_CASE : Optional[Any] = "train"
SCREAMING_SNAKE_CASE : Dict = {"train": parquet_path, "test": parquet_path}
SCREAMING_SNAKE_CASE : str = tmp_path / "cache"
SCREAMING_SNAKE_CASE : Union[str, Any] = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
SCREAMING_SNAKE_CASE : int = ParquetDatasetReader(lowercase , cache_dir=lowercase ).read()
_check_parquet_datasetdict(lowercase , lowercase , splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
def lowerCamelCase__ ( lowercase , lowercase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Any = ParquetDatasetWriter(lowercase , tmp_path / "foo.parquet" )
assert writer.write() > 0
SCREAMING_SNAKE_CASE : Optional[int] = pq.ParquetFile(tmp_path / "foo.parquet" )
SCREAMING_SNAKE_CASE : Union[str, Any] = pf.read()
assert dataset.data.table == output_table
def lowerCamelCase__ ( lowercase , lowercase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : List[str] = str(shared_datadir / "test_image_rgb.jpg" )
SCREAMING_SNAKE_CASE : Union[str, Any] = {"image": [image_path]}
SCREAMING_SNAKE_CASE : Any = Features({"image": Image()} )
SCREAMING_SNAKE_CASE : List[Any] = Dataset.from_dict(lowercase , features=lowercase )
SCREAMING_SNAKE_CASE : Tuple = ParquetDatasetWriter(lowercase , tmp_path / "foo.parquet" )
assert writer.write() > 0
SCREAMING_SNAKE_CASE : Dict = Dataset.from_parquet(str(tmp_path / "foo.parquet" ) )
assert dataset.features == reloaded_dataset.features
SCREAMING_SNAKE_CASE : Dict = ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=lowercase ).read()
assert dataset.features == reloaded_iterable_dataset.features
@pytest.mark.parametrize(
"feature, expected" , [
(Features({"foo": Value("int32" )} ), None),
(Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS),
(Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS),
] , )
def lowerCamelCase__ ( lowercase , lowercase ):
"""simple docstring"""
assert get_writer_batch_size(lowercase ) == expected
| 62 |
"""simple docstring"""
UpperCAmelCase : int = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]
def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> int:
'''simple docstring'''
lowercase_ = {"""I""": 1, """V""": 5, """X""": 10, """L""": 50, """C""": 1_00, """D""": 5_00, """M""": 10_00}
lowercase_ = 0
lowercase_ = 0
while place < len(__lowerCAmelCase ):
if (place + 1 < len(__lowerCAmelCase )) and (vals[roman[place]] < vals[roman[place + 1]]):
total += vals[roman[place + 1]] - vals[roman[place]]
place += 2
else:
total += vals[roman[place]]
place += 1
return total
def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> str:
'''simple docstring'''
lowercase_ = []
for arabic, roman in ROMAN:
((lowercase_) , (lowercase_)) = divmod(__lowerCAmelCase , __lowerCAmelCase )
result.append(roman * factor )
if number == 0:
break
return "".join(__lowerCAmelCase )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 567 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tokenizers_available,
is_torch_available,
)
a__ : Optional[int] ={'configuration_reformer': ['REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ReformerConfig']}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a__ : Union[str, Any] =['ReformerTokenizer']
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a__ : int =['ReformerTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a__ : Tuple =[
'REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'ReformerAttention',
'ReformerForMaskedLM',
'ReformerForQuestionAnswering',
'ReformerForSequenceClassification',
'ReformerLayer',
'ReformerModel',
'ReformerModelWithLMHead',
'ReformerPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_reformer import ReformerTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_reformer_fast import ReformerTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_reformer import (
REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
ReformerAttention,
ReformerForMaskedLM,
ReformerForQuestionAnswering,
ReformerForSequenceClassification,
ReformerLayer,
ReformerModel,
ReformerModelWithLMHead,
ReformerPreTrainedModel,
)
else:
import sys
a__ : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 706 |
'''simple docstring'''
import unittest
from transformers import TrOCRConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device
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.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM
@require_torch
class snake_case :
"""simple docstring"""
def __init__( self : Union[str, Any] , __A : str , __A : str=9_9 , __A : Optional[Any]=1_3 , __A : Optional[int]=1_6 , __A : Optional[Any]=7 , __A : List[Any]=True , __A : List[str]=True , __A : int=True , __A : str=False , __A : List[str]=True , __A : Optional[int]=2 , __A : Optional[Any]=3_2 , __A : str=4 , __A : int=4 , __A : Union[str, Any]=3_0 , __A : Union[str, Any]=0 , __A : Optional[int]=1 , __A : List[str]=2 , __A : Tuple=None , ):
__UpperCamelCase = parent
__UpperCamelCase = batch_size
__UpperCamelCase = decoder_seq_length
# For common tests
__UpperCamelCase = self.decoder_seq_length
__UpperCamelCase = is_training
__UpperCamelCase = use_attention_mask
__UpperCamelCase = use_labels
__UpperCamelCase = vocab_size
__UpperCamelCase = d_model
__UpperCamelCase = d_model
__UpperCamelCase = decoder_layers
__UpperCamelCase = decoder_layers
__UpperCamelCase = decoder_ffn_dim
__UpperCamelCase = decoder_attention_heads
__UpperCamelCase = decoder_attention_heads
__UpperCamelCase = eos_token_id
__UpperCamelCase = bos_token_id
__UpperCamelCase = pad_token_id
__UpperCamelCase = decoder_start_token_id
__UpperCamelCase = use_cache
__UpperCamelCase = max_position_embeddings
__UpperCamelCase = None
__UpperCamelCase = decoder_seq_length
__UpperCamelCase = 2
__UpperCamelCase = 1
def _lowerCamelCase ( self : List[Any] ):
__UpperCamelCase = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size )
__UpperCamelCase = None
if self.use_attention_mask:
__UpperCamelCase = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2 )
__UpperCamelCase = None
if self.use_labels:
__UpperCamelCase = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size )
__UpperCamelCase = TrOCRConfig(
vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , )
return (config, input_ids, attention_mask, lm_labels)
def _lowerCamelCase ( self : List[Any] , __A : str , __A : str , __A : Tuple , __A : Optional[int] , ):
__UpperCamelCase = True
__UpperCamelCase = TrOCRDecoder(config=__A ).to(__A ).eval()
__UpperCamelCase = input_ids[:2]
input_ids[input_ids == 0] += 1
# first forward pass
__UpperCamelCase = model(__A , use_cache=__A )
__UpperCamelCase = model(__A )
__UpperCamelCase = model(__A , use_cache=__A )
self.parent.assertTrue(len(__A ) == len(__A ) )
self.parent.assertTrue(len(__A ) == len(__A ) + 1 )
__UpperCamelCase = outputs['past_key_values']
# create hypothetical next token and extent to next_input_ids
__UpperCamelCase = ids_tensor((2, 1) , config.vocab_size - 1 ) + 1
# append to next input_ids and
__UpperCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 )
__UpperCamelCase = model(__A )['last_hidden_state']
__UpperCamelCase = model(__A , past_key_values=__A )['last_hidden_state']
# select random slice
__UpperCamelCase = ids_tensor((1,) , output_from_past.shape[-1] ).item()
__UpperCamelCase = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
__UpperCamelCase = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
assert torch.allclose(__A , __A , atol=1e-3 )
def _lowerCamelCase ( self : int ):
__UpperCamelCase = self.prepare_config_and_inputs()
__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = config_and_inputs
__UpperCamelCase = {'input_ids': input_ids, 'attention_mask': attention_mask}
return config, inputs_dict
@require_torch
class snake_case ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str =(TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
SCREAMING_SNAKE_CASE_ : Any =(TrOCRForCausalLM,) if is_torch_available() else ()
SCREAMING_SNAKE_CASE_ : int ={"text-generation": TrOCRForCausalLM} if is_torch_available() else {}
SCREAMING_SNAKE_CASE_ : Dict =True
SCREAMING_SNAKE_CASE_ : Tuple =False
def _lowerCamelCase ( self : Dict ):
__UpperCamelCase = TrOCRStandaloneDecoderModelTester(self , is_training=__A )
__UpperCamelCase = ConfigTester(self , config_class=__A )
def _lowerCamelCase ( self : List[str] ):
pass
def _lowerCamelCase ( self : List[str] ):
pass
def _lowerCamelCase ( self : List[Any] ):
pass
def _lowerCamelCase ( self : Dict ):
self.config_tester.run_common_tests()
def _lowerCamelCase ( self : Optional[Any] ):
__UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past(*__A )
def _lowerCamelCase ( self : Union[str, Any] ):
return
@unittest.skip('The model doesn\'t support left padding' ) # and it's not used enough to be worth fixing :)
def _lowerCamelCase ( self : Optional[int] ):
pass
| 434 | 0 |
'''simple docstring'''
import argparse
import json
import numpy
import torch
from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
def __snake_case ( lowerCAmelCase : List[Any] , lowerCAmelCase : Any ):
# Load checkpoint
__UpperCAmelCase = torch.load(lowerCAmelCase , map_location='cpu' )
__UpperCAmelCase = chkpt['model']
# We have the base model one level deeper than the original XLM repository
__UpperCAmelCase = {}
for k, v in state_dict.items():
if "pred_layer" in k:
__UpperCAmelCase = v
else:
__UpperCAmelCase = v
__UpperCAmelCase = chkpt['params']
__UpperCAmelCase = {n: v for n, v in config.items() if not isinstance(lowerCAmelCase , (torch.FloatTensor, numpy.ndarray) )}
__UpperCAmelCase = chkpt['dico_word2id']
__UpperCAmelCase = {s + '</w>' if s.find('@@' ) == -1 and i > 13 else s.replace('@@' , '' ): i for s, i in vocab.items()}
# Save pytorch-model
__UpperCAmelCase = pytorch_dump_folder_path + '/' + WEIGHTS_NAME
__UpperCAmelCase = pytorch_dump_folder_path + '/' + CONFIG_NAME
__UpperCAmelCase = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['vocab_file']
print(F"""Save PyTorch model to {pytorch_weights_dump_path}""" )
torch.save(lowerCAmelCase , lowerCAmelCase )
print(F"""Save configuration file to {pytorch_config_dump_path}""" )
with open(lowerCAmelCase , 'w' , encoding='utf-8' ) as f:
f.write(json.dumps(lowerCAmelCase , indent=2 ) + '\n' )
print(F"""Save vocab file to {pytorch_config_dump_path}""" )
with open(lowerCAmelCase , 'w' , encoding='utf-8' ) as f:
f.write(json.dumps(lowerCAmelCase , indent=2 ) + '\n' )
if __name__ == "__main__":
_UpperCamelCase : Optional[int] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--xlm_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.'
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
)
_UpperCamelCase : List[str] = parser.parse_args()
convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
| 396 | '''simple docstring'''
import argparse
from collections import defaultdict
import yaml
_UpperCamelCase : int = 'docs/source/en/_toctree.yml'
def __snake_case ( lowerCAmelCase : Union[str, Any] ):
__UpperCAmelCase = defaultdict(lowerCAmelCase )
__UpperCAmelCase = []
__UpperCAmelCase = []
for doc in doc_list:
if "local" in doc:
counts[doc["local"]] += 1
if doc["title"].lower() == "overview":
overview_doc.append({'local': doc['local'], 'title': doc['title']} )
else:
new_doc_list.append(lowerCAmelCase )
__UpperCAmelCase = new_doc_list
__UpperCAmelCase = [key for key, value in counts.items() if value > 1]
__UpperCAmelCase = []
for duplicate_key in duplicates:
__UpperCAmelCase = list({doc['title'] for doc in doc_list if doc['local'] == duplicate_key} )
if len(lowerCAmelCase ) > 1:
raise ValueError(
F"""{duplicate_key} is present several times in the documentation table of content at """
'`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '
'others.' )
# Only add this once
new_doc.append({'local': duplicate_key, 'title': titles[0]} )
# Add none duplicate-keys
new_doc.extend([doc for doc in doc_list if 'local' not in counts or counts[doc['local']] == 1] )
__UpperCAmelCase = sorted(lowerCAmelCase , key=lambda lowerCAmelCase : s["title"].lower() )
# "overview" gets special treatment and is always first
if len(lowerCAmelCase ) > 1:
raise ValueError('{doc_list} has two \'overview\' docs which is not allowed.' )
overview_doc.extend(lowerCAmelCase )
# Sort
return overview_doc
def __snake_case ( lowerCAmelCase : Union[str, Any]=False ):
with open(lowerCAmelCase , encoding='utf-8' ) as f:
__UpperCAmelCase = yaml.safe_load(f.read() )
# Get to the API doc
__UpperCAmelCase = 0
while content[api_idx]["title"] != "API":
api_idx += 1
__UpperCAmelCase = content[api_idx]['sections']
# Then to the model doc
__UpperCAmelCase = 0
while api_doc[scheduler_idx]["title"] != "Schedulers":
scheduler_idx += 1
__UpperCAmelCase = api_doc[scheduler_idx]['sections']
__UpperCAmelCase = clean_doc_toc(lowerCAmelCase )
__UpperCAmelCase = False
if new_scheduler_doc != scheduler_doc:
__UpperCAmelCase = True
if overwrite:
__UpperCAmelCase = new_scheduler_doc
if diff:
if overwrite:
__UpperCAmelCase = api_doc
with open(lowerCAmelCase , 'w' , encoding='utf-8' ) as f:
f.write(yaml.dump(lowerCAmelCase , allow_unicode=lowerCAmelCase ) )
else:
raise ValueError(
'The model doc part of the table of content is not properly sorted, run `make style` to fix this.' )
def __snake_case ( lowerCAmelCase : Tuple=False ):
with open(lowerCAmelCase , encoding='utf-8' ) as f:
__UpperCAmelCase = yaml.safe_load(f.read() )
# Get to the API doc
__UpperCAmelCase = 0
while content[api_idx]["title"] != "API":
api_idx += 1
__UpperCAmelCase = content[api_idx]['sections']
# Then to the model doc
__UpperCAmelCase = 0
while api_doc[pipeline_idx]["title"] != "Pipelines":
pipeline_idx += 1
__UpperCAmelCase = False
__UpperCAmelCase = api_doc[pipeline_idx]['sections']
__UpperCAmelCase = []
# sort sub pipeline docs
for pipeline_doc in pipeline_docs:
if "section" in pipeline_doc:
__UpperCAmelCase = pipeline_doc['section']
__UpperCAmelCase = clean_doc_toc(lowerCAmelCase )
if overwrite:
__UpperCAmelCase = new_sub_pipeline_doc
new_pipeline_docs.append(lowerCAmelCase )
# sort overall pipeline doc
__UpperCAmelCase = clean_doc_toc(lowerCAmelCase )
if new_pipeline_docs != pipeline_docs:
__UpperCAmelCase = True
if overwrite:
__UpperCAmelCase = new_pipeline_docs
if diff:
if overwrite:
__UpperCAmelCase = api_doc
with open(lowerCAmelCase , 'w' , encoding='utf-8' ) as f:
f.write(yaml.dump(lowerCAmelCase , allow_unicode=lowerCAmelCase ) )
else:
raise ValueError(
'The model doc part of the table of content is not properly sorted, run `make style` to fix this.' )
if __name__ == "__main__":
_UpperCamelCase : List[str] = argparse.ArgumentParser()
parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
_UpperCamelCase : Union[str, Any] = parser.parse_args()
check_scheduler_doc(args.fix_and_overwrite)
check_pipeline_doc(args.fix_and_overwrite)
| 396 | 1 |
'''simple docstring'''
def __UpperCAmelCase ( a_: int ):
# bit count represents no. of bits in the gray code
if bit_count < 0:
raise ValueError("The given input must be positive" )
# get the generated string sequence
_UpperCAmelCase : str = gray_code_sequence_string(a_ )
#
# convert them to integers
for i in range(len(a_ ) ):
_UpperCAmelCase : Union[str, Any] = int(sequence[i], 2 )
return sequence
def __UpperCAmelCase ( a_: int ):
# The approach is a recursive one
# Base case achieved when either n = 0 or n=1
if bit_count == 0:
return ["0"]
if bit_count == 1:
return ["0", "1"]
_UpperCAmelCase : List[str] = 1 << bit_count # defines the length of the sequence
# 1<< n is equivalent to 2^n
# recursive answer will generate answer for n-1 bits
_UpperCAmelCase : Optional[Any] = gray_code_sequence_string(bit_count - 1 )
_UpperCAmelCase : Optional[Any] = []
# append 0 to first half of the smaller sequence generated
for i in range(seq_len // 2 ):
_UpperCAmelCase : str = "0" + smaller_sequence[i]
sequence.append(a_ )
# append 1 to second half ... start from the end of the list
for i in reversed(range(seq_len // 2 ) ):
_UpperCAmelCase : int = "1" + smaller_sequence[i]
sequence.append(a_ )
return sequence
if __name__ == "__main__":
import doctest
doctest.testmod() | 257 | '''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__a = logging.get_logger(__name__)
__a = {
'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json',
'google/bigbird-roberta-large': 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json',
'google/bigbird-base-trivia-itc': 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json',
# See all BigBird models at https://huggingface.co/models?filter=big_bird
}
class A__ ( UpperCamelCase ):
"""simple docstring"""
UpperCamelCase_ : List[str] = '''big_bird'''
def __init__( self : Union[str, Any] , lowerCAmelCase__ : List[Any]=5_0_3_5_8 , lowerCAmelCase__ : Dict=7_6_8 , lowerCAmelCase__ : List[str]=1_2 , lowerCAmelCase__ : List[Any]=1_2 , lowerCAmelCase__ : str=3_0_7_2 , lowerCAmelCase__ : Any="gelu_new" , lowerCAmelCase__ : Optional[int]=0.1 , lowerCAmelCase__ : Tuple=0.1 , lowerCAmelCase__ : Optional[int]=4_0_9_6 , lowerCAmelCase__ : Optional[int]=2 , lowerCAmelCase__ : str=0.02 , lowerCAmelCase__ : List[str]=1e-12 , lowerCAmelCase__ : Dict=True , lowerCAmelCase__ : List[Any]=0 , lowerCAmelCase__ : str=1 , lowerCAmelCase__ : Tuple=2 , lowerCAmelCase__ : Dict=6_6 , lowerCAmelCase__ : Optional[int]="block_sparse" , lowerCAmelCase__ : Any=True , lowerCAmelCase__ : Tuple=False , lowerCAmelCase__ : Tuple=6_4 , lowerCAmelCase__ : Optional[int]=3 , lowerCAmelCase__ : Dict=None , **lowerCAmelCase__ : str , ) -> Tuple:
"""simple docstring"""
super().__init__(
pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , sep_token_id=lowerCAmelCase__ , **lowerCAmelCase__ , )
_UpperCAmelCase : int = vocab_size
_UpperCAmelCase : str = max_position_embeddings
_UpperCAmelCase : Optional[Any] = hidden_size
_UpperCAmelCase : int = num_hidden_layers
_UpperCAmelCase : Any = num_attention_heads
_UpperCAmelCase : List[str] = intermediate_size
_UpperCAmelCase : Optional[int] = hidden_act
_UpperCAmelCase : int = hidden_dropout_prob
_UpperCAmelCase : List[Any] = attention_probs_dropout_prob
_UpperCAmelCase : Optional[int] = initializer_range
_UpperCAmelCase : Any = type_vocab_size
_UpperCAmelCase : Optional[Any] = layer_norm_eps
_UpperCAmelCase : Union[str, Any] = use_cache
_UpperCAmelCase : Dict = rescale_embeddings
_UpperCAmelCase : List[Any] = attention_type
_UpperCAmelCase : str = use_bias
_UpperCAmelCase : Optional[Any] = block_size
_UpperCAmelCase : Optional[Any] = num_random_blocks
_UpperCAmelCase : Optional[Any] = classifier_dropout
class A__ ( UpperCamelCase ):
"""simple docstring"""
@property
def _lowerCAmelCase ( self : int ) -> Mapping[str, Mapping[int, str]]:
"""simple docstring"""
if self.task == "multiple-choice":
_UpperCAmelCase : Optional[Any] = {0: "batch", 1: "choice", 2: "sequence"}
else:
_UpperCAmelCase : Optional[int] = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
] ) | 257 | 1 |
'''simple docstring'''
import os
from collections.abc import Iterator
def UpperCamelCase_ ( _UpperCAmelCase : str = "." ) -> Iterator[str]:
"""simple docstring"""
for dir_path, dir_names, filenames in os.walk(_UpperCAmelCase ):
_UpperCAmelCase : Optional[int] = [d for d in dir_names if d != "scripts" and d[0] not in "._"]
for filename in filenames:
if filename == "__init__.py":
continue
if os.path.splitext(_UpperCAmelCase )[1] in (".py", ".ipynb"):
yield os.path.join(_UpperCAmelCase , _UpperCAmelCase ).lstrip("./" )
def UpperCamelCase_ ( _UpperCAmelCase : Dict ) -> Any:
"""simple docstring"""
return F"""{i * ' '}*""" if i else "\n##"
def UpperCamelCase_ ( _UpperCAmelCase : str , _UpperCAmelCase : str ) -> str:
"""simple docstring"""
_UpperCAmelCase : Union[str, Any] = old_path.split(os.sep )
for i, new_part in enumerate(new_path.split(os.sep ) ):
if (i + 1 > len(_UpperCAmelCase ) or old_parts[i] != new_part) and new_part:
print(F"""{md_prefix(_UpperCAmelCase )} {new_part.replace('_' , ' ' ).title()}""" )
return new_path
def UpperCamelCase_ ( _UpperCAmelCase : str = "." ) -> None:
"""simple docstring"""
_UpperCAmelCase : List[str] = ""
for filepath in sorted(good_file_paths(_UpperCAmelCase ) ):
_UpperCAmelCase , _UpperCAmelCase : Dict = os.path.split(_UpperCAmelCase )
if filepath != old_path:
_UpperCAmelCase : str = print_path(_UpperCAmelCase , _UpperCAmelCase )
_UpperCAmelCase : int = (filepath.count(os.sep ) + 1) if filepath else 0
_UpperCAmelCase : Tuple = F"""{filepath}/{filename}""".replace(" " , "%20" )
_UpperCAmelCase : Tuple = os.path.splitext(filename.replace("_" , " " ).title() )[0]
print(F"""{md_prefix(_UpperCAmelCase )} [{filename}]({url})""" )
if __name__ == "__main__":
print_directory_md(""".""")
| 244 | '''simple docstring'''
def UpperCamelCase_ ( _UpperCAmelCase : int , _UpperCAmelCase : int ) -> int:
"""simple docstring"""
return number | (1 << position)
def UpperCamelCase_ ( _UpperCAmelCase : int , _UpperCAmelCase : int ) -> int:
"""simple docstring"""
return number & ~(1 << position)
def UpperCamelCase_ ( _UpperCAmelCase : int , _UpperCAmelCase : int ) -> int:
"""simple docstring"""
return number ^ (1 << position)
def UpperCamelCase_ ( _UpperCAmelCase : int , _UpperCAmelCase : int ) -> bool:
"""simple docstring"""
return ((number >> position) & 1) == 1
def UpperCamelCase_ ( _UpperCAmelCase : int , _UpperCAmelCase : int ) -> int:
"""simple docstring"""
return int((number & (1 << position)) != 0 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 244 | 1 |
"""simple docstring"""
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..bit import BitConfig
__A = logging.get_logger(__name__)
__A = {
"""Intel/dpt-large""": """https://huggingface.co/Intel/dpt-large/resolve/main/config.json""",
# See all DPT models at https://huggingface.co/models?filter=dpt
}
class _lowerCAmelCase ( a ):
"""simple docstring"""
__magic_name__ :List[str] = """dpt"""
def __init__( self , __UpperCAmelCase=7_6_8 , __UpperCAmelCase=1_2 , __UpperCAmelCase=1_2 , __UpperCAmelCase=3_0_7_2 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-12 , __UpperCAmelCase=3_8_4 , __UpperCAmelCase=1_6 , __UpperCAmelCase=3 , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=[2, 5, 8, 1_1] , __UpperCAmelCase="project" , __UpperCAmelCase=[4, 2, 1, 0.5] , __UpperCAmelCase=[9_6, 1_9_2, 3_8_4, 7_6_8] , __UpperCAmelCase=2_5_6 , __UpperCAmelCase=-1 , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=0.4 , __UpperCAmelCase=2_5_5 , __UpperCAmelCase=0.1 , __UpperCAmelCase=[1, 1_0_2_4, 2_4, 2_4] , __UpperCAmelCase=[0, 1] , __UpperCAmelCase=None , **__UpperCAmelCase , ):
'''simple docstring'''
super().__init__(**__UpperCAmelCase )
lowerCAmelCase__ :int = hidden_size
lowerCAmelCase__ :int = is_hybrid
if self.is_hybrid:
if backbone_config is None:
logger.info('Initializing the config with a `BiT` backbone.' )
lowerCAmelCase__ :List[Any] = {
'global_padding': 'same',
'layer_type': 'bottleneck',
'depths': [3, 4, 9],
'out_features': ['stage1', 'stage2', 'stage3'],
'embedding_dynamic_padding': True,
}
lowerCAmelCase__ :Union[str, Any] = BitConfig(**__UpperCAmelCase )
elif isinstance(__UpperCAmelCase , __UpperCAmelCase ):
logger.info('Initializing the config with a `BiT` backbone.' )
lowerCAmelCase__ :Optional[Any] = BitConfig(**__UpperCAmelCase )
elif isinstance(__UpperCAmelCase , __UpperCAmelCase ):
lowerCAmelCase__ :int = backbone_config
else:
raise ValueError(
F"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." )
lowerCAmelCase__ :Any = backbone_featmap_shape
lowerCAmelCase__ :int = neck_ignore_stages
if readout_type != "project":
raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.' )
else:
lowerCAmelCase__ :Any = None
lowerCAmelCase__ :List[Any] = None
lowerCAmelCase__ :Optional[Any] = []
lowerCAmelCase__ :Optional[Any] = num_hidden_layers
lowerCAmelCase__ :List[Any] = num_attention_heads
lowerCAmelCase__ :Optional[int] = intermediate_size
lowerCAmelCase__ :Optional[Any] = hidden_act
lowerCAmelCase__ :List[Any] = hidden_dropout_prob
lowerCAmelCase__ :List[str] = attention_probs_dropout_prob
lowerCAmelCase__ :Optional[Any] = initializer_range
lowerCAmelCase__ :Optional[int] = layer_norm_eps
lowerCAmelCase__ :Union[str, Any] = image_size
lowerCAmelCase__ :Any = patch_size
lowerCAmelCase__ :Optional[Any] = num_channels
lowerCAmelCase__ :Optional[Any] = qkv_bias
lowerCAmelCase__ :Tuple = backbone_out_indices
if readout_type not in ["ignore", "add", "project"]:
raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']' )
lowerCAmelCase__ :Optional[Any] = readout_type
lowerCAmelCase__ :int = reassemble_factors
lowerCAmelCase__ :Union[str, Any] = neck_hidden_sizes
lowerCAmelCase__ :Optional[int] = fusion_hidden_size
lowerCAmelCase__ :List[str] = head_in_index
lowerCAmelCase__ :Tuple = use_batch_norm_in_fusion_residual
# auxiliary head attributes (semantic segmentation)
lowerCAmelCase__ :Optional[int] = use_auxiliary_head
lowerCAmelCase__ :Dict = auxiliary_loss_weight
lowerCAmelCase__ :Optional[int] = semantic_loss_ignore_index
lowerCAmelCase__ :Union[str, Any] = semantic_classifier_dropout
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Any = copy.deepcopy(self.__dict__ )
if output["backbone_config"] is not None:
lowerCAmelCase__ :int = self.backbone_config.to_dict()
lowerCAmelCase__ :Union[str, Any] = self.__class__.model_type
return output
| 560 |
"""simple docstring"""
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 _lowerCAmelCase ( a ):
"""simple docstring"""
__magic_name__ :Optional[Any] = ["""image_processor""", """tokenizer"""]
__magic_name__ :str = """BlipImageProcessor"""
__magic_name__ :Tuple = ("""BertTokenizer""", """BertTokenizerFast""")
def __init__( self , __UpperCAmelCase , __UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase__ :Optional[int] = False
super().__init__(__UpperCAmelCase , __UpperCAmelCase )
lowerCAmelCase__ :List[str] = self.image_processor
def __call__( self , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = True , __UpperCAmelCase = False , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = 0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = True , __UpperCAmelCase = None , **__UpperCAmelCase , ):
'''simple docstring'''
if images is None and text is None:
raise ValueError('You have to specify either images or text.' )
# Get only text
if images is None:
lowerCAmelCase__ :int = self.tokenizer
lowerCAmelCase__ :str = self.tokenizer(
text=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=__UpperCAmelCase , stride=__UpperCAmelCase , pad_to_multiple_of=__UpperCAmelCase , return_attention_mask=__UpperCAmelCase , return_overflowing_tokens=__UpperCAmelCase , return_special_tokens_mask=__UpperCAmelCase , return_offsets_mapping=__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase , return_length=__UpperCAmelCase , verbose=__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase , )
return text_encoding
# add pixel_values
lowerCAmelCase__ :Dict = self.image_processor(__UpperCAmelCase , return_tensors=__UpperCAmelCase )
if text is not None:
lowerCAmelCase__ :str = self.tokenizer(
text=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=__UpperCAmelCase , stride=__UpperCAmelCase , pad_to_multiple_of=__UpperCAmelCase , return_attention_mask=__UpperCAmelCase , return_overflowing_tokens=__UpperCAmelCase , return_special_tokens_mask=__UpperCAmelCase , return_offsets_mapping=__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase , return_length=__UpperCAmelCase , verbose=__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase , )
else:
lowerCAmelCase__ :Optional[Any] = None
if text_encoding is not None:
encoding_image_processor.update(__UpperCAmelCase )
return encoding_image_processor
def snake_case ( self , *__UpperCAmelCase , **__UpperCAmelCase ):
'''simple docstring'''
return self.tokenizer.batch_decode(*__UpperCAmelCase , **__UpperCAmelCase )
def snake_case ( self , *__UpperCAmelCase , **__UpperCAmelCase ):
'''simple docstring'''
return self.tokenizer.decode(*__UpperCAmelCase , **__UpperCAmelCase )
@property
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Optional[Any] = self.tokenizer.model_input_names
lowerCAmelCase__ :Any = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
| 560 | 1 |
from __future__ import annotations
class lowercase_ :
def __init__( self , __A , __A ) -> Dict:
SCREAMING_SNAKE_CASE_ : List[Any] =text, pattern
SCREAMING_SNAKE_CASE_ : Union[str, Any] =len(SCREAMING_SNAKE_CASE__ ), len(SCREAMING_SNAKE_CASE__ )
def _snake_case ( self , __A ) -> int:
for i in range(self.patLen - 1 , -1 , -1 ):
if char == self.pattern[i]:
return i
return -1
def _snake_case ( self , __A ) -> int:
for i in range(self.patLen - 1 , -1 , -1 ):
if self.pattern[i] != self.text[current_pos + i]:
return current_pos + i
return -1
def _snake_case ( self ) -> list[int]:
SCREAMING_SNAKE_CASE_ : int =[]
for i in range(self.textLen - self.patLen + 1 ):
SCREAMING_SNAKE_CASE_ : Dict =self.mismatch_in_text(SCREAMING_SNAKE_CASE__ )
if mismatch_index == -1:
positions.append(SCREAMING_SNAKE_CASE__ )
else:
SCREAMING_SNAKE_CASE_ : Union[str, Any] =self.match_in_pattern(self.text[mismatch_index] )
SCREAMING_SNAKE_CASE_ : List[str] =(
mismatch_index - match_index
) # shifting index lgtm [py/multiple-definition]
return positions
_lowercase = """ABAABA"""
_lowercase = """AB"""
_lowercase = BoyerMooreSearch(text, pattern)
_lowercase = bms.bad_character_heuristic()
if len(positions) == 0:
print("""No match found""")
else:
print("""Pattern found in following positions: """)
print(positions)
| 443 |
"""simple docstring"""
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class _SCREAMING_SNAKE_CASE:
SCREAMING_SNAKE_CASE_ : float
SCREAMING_SNAKE_CASE_ : TreeNode | None = None
SCREAMING_SNAKE_CASE_ : TreeNode | None = None
def __lowerCamelCase ( a_ : TreeNode | None ) -> bool:
# Validation
def is_valid_tree(a_ : TreeNode | None ) -> bool:
if node is None:
return True
if not isinstance(a_ , a_ ):
return False
try:
float(node.data )
except (TypeError, ValueError):
return False
return is_valid_tree(node.left ) and is_valid_tree(node.right )
if not is_valid_tree(a_ ):
raise ValueError(
'''Each node should be type of TreeNode and data should be float.''' )
def is_binary_search_tree_recursive_check(
a_ : TreeNode | None , a_ : float , a_ : float ) -> bool:
if node is None:
return True
return (
left_bound < node.data < right_bound
and is_binary_search_tree_recursive_check(node.left , a_ , node.data )
and is_binary_search_tree_recursive_check(
node.right , node.data , a_ )
)
return is_binary_search_tree_recursive_check(a_ , -float('''inf''' ) , float('''inf''' ) )
if __name__ == "__main__":
import doctest
doctest.testmod() | 498 | 0 |
"""simple docstring"""
def a ( __UpperCAmelCase : int , __UpperCAmelCase : int ) -> int:
return int((input_a, input_a).count(0 ) != 0 )
def a ( ) -> None:
assert nand_gate(0 , 0 ) == 1
assert nand_gate(0 , 1 ) == 1
assert nand_gate(1 , 0 ) == 1
assert nand_gate(1 , 1 ) == 0
if __name__ == "__main__":
print(nand_gate(0, 0))
print(nand_gate(0, 1))
print(nand_gate(1, 0))
print(nand_gate(1, 1))
| 213 |
"""simple docstring"""
import argparse
import torch
from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert
from transformers.utils import logging
logging.set_verbosity_info()
def a ( __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : str ) -> Any:
# Initialise PyTorch model
__magic_name__: Optional[Any] = BertConfig.from_json_file(__UpperCAmelCase )
print(f'Building PyTorch model from configuration: {config}' )
__magic_name__: int = BertForPreTraining(__UpperCAmelCase )
# Load weights from tf checkpoint
load_tf_weights_in_bert(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
# Save pytorch-model
print(f'Save PyTorch model to {pytorch_dump_path}' )
torch.save(model.state_dict() , __UpperCAmelCase )
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(
'--bert_config_file',
default=None,
type=str,
required=True,
help=(
'The config json file corresponding to the pre-trained BERT model. \n'
'This specifies the model architecture.'
),
)
parser.add_argument(
'--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
)
__lowerCamelCase = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
| 213 | 1 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__UpperCAmelCase = logging.get_logger(__name__)
__UpperCAmelCase = {
's-JoL/Open-Llama-V1': 'https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json',
}
class __lowercase ( __lowerCamelCase ):
snake_case_ = """open-llama"""
def __init__( self : Dict ,A : str=100_000 ,A : str=4_096 ,A : Optional[Any]=11_008 ,A : Tuple=32 ,A : str=32 ,A : Optional[int]="silu" ,A : List[Any]=2_048 ,A : str=0.0_2 ,A : Optional[int]=1e-6 ,A : int=True ,A : Tuple=0 ,A : str=1 ,A : Any=2 ,A : Optional[Any]=False ,A : int=True ,A : Any=0.1 ,A : Optional[Any]=0.1 ,A : Optional[Any]=True ,A : Union[str, Any]=True ,A : Tuple=None ,**A : Optional[int] ,):
'''simple docstring'''
UpperCAmelCase__ : str = vocab_size
UpperCAmelCase__ : List[str] = max_position_embeddings
UpperCAmelCase__ : Union[str, Any] = hidden_size
UpperCAmelCase__ : Tuple = intermediate_size
UpperCAmelCase__ : Optional[int] = num_hidden_layers
UpperCAmelCase__ : Any = num_attention_heads
UpperCAmelCase__ : str = hidden_act
UpperCAmelCase__ : Optional[Any] = initializer_range
UpperCAmelCase__ : Optional[int] = rms_norm_eps
UpperCAmelCase__ : Any = use_cache
UpperCAmelCase__ : Optional[Any] = kwargs.pop(
"""use_memorry_efficient_attention""" ,A )
UpperCAmelCase__ : Any = hidden_dropout_prob
UpperCAmelCase__ : str = attention_dropout_prob
UpperCAmelCase__ : Optional[int] = use_stable_embedding
UpperCAmelCase__ : Tuple = shared_input_output_embedding
UpperCAmelCase__ : Tuple = 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 __lowercase ( self : Optional[Any] ):
'''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}" )
UpperCAmelCase__ : List[Any] = self.rope_scaling.get("""type""" ,A )
UpperCAmelCase__ : 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}" )
| 65 |
"""simple docstring"""
import os
from shutil import copyfile
from typing import List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
__UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__)
__UpperCAmelCase : Optional[int] = {'vocab_file': 'sentencepiece.model'}
__UpperCAmelCase : Dict = {
'vocab_file': {
'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model',
},
}
__UpperCAmelCase : str = {
'google/rembert': 2_56,
}
class __lowerCAmelCase (__UpperCamelCase ):
'''simple docstring'''
a__ = VOCAB_FILES_NAMES
a__ = PRETRAINED_VOCAB_FILES_MAP
a__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self , a , a=False , a=True , a=True , a="[CLS]" , a="[SEP]" , a="[UNK]" , a="[SEP]" , a="[PAD]" , a="[CLS]" , a="[MASK]" , **a , ):
"""simple docstring"""
super().__init__(
do_lower_case=a , remove_space=a , keep_accents=a , bos_token=a , eos_token=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , **a , )
snake_case_ :Dict = do_lower_case
snake_case_ :Tuple = remove_space
snake_case_ :List[Any] = keep_accents
snake_case_ :Union[str, Any] = vocab_file
snake_case_ :Optional[Any] = spm.SentencePieceProcessor()
self.sp_model.Load(a )
@property
def _a ( self ):
"""simple docstring"""
return len(self.sp_model )
def _a ( self ):
"""simple docstring"""
snake_case_ :List[Any] = {self.convert_ids_to_tokens(a ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self ):
"""simple docstring"""
snake_case_ :Tuple = self.__dict__.copy()
snake_case_ :List[Any] = None
return state
def __setstate__( self , a ):
"""simple docstring"""
snake_case_ :List[Any] = d
snake_case_ :Dict = spm.SentencePieceProcessor()
self.sp_model.Load(self.vocab_file )
def _a ( self , a , a=False ):
"""simple docstring"""
snake_case_ :str = self.sp_model.EncodeAsPieces(a )
return pieces
def _a ( self , a ):
"""simple docstring"""
return self.sp_model.PieceToId(a )
def _a ( self , a ):
"""simple docstring"""
return self.sp_model.IdToPiece(a )
def _a ( self , a ):
"""simple docstring"""
snake_case_ :int = self.sp_model.decode_pieces(a )
return out_string
def _a ( self , a , a = None ):
"""simple docstring"""
snake_case_ :List[Any] = [self.sep_token_id]
snake_case_ :List[Any] = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def _a ( self , a , a = None , a = False ):
"""simple docstring"""
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model." )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is not None:
return [1] + ([0] * len(a )) + [1] + ([0] * len(a )) + [1]
return [1] + ([0] * len(a )) + [1]
def _a ( self , a , a = None ):
"""simple docstring"""
snake_case_ :Any = [self.sep_token_id]
snake_case_ :Dict = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def _a ( self , a , a = None ):
"""simple docstring"""
if not os.path.isdir(a ):
logger.error("Vocabulary path ({}) should be a directory".format(a ) )
return
snake_case_ :str = os.path.join(
a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(a ):
copyfile(self.vocab_file , a )
return (out_vocab_file,)
| 584 | 0 |
def SCREAMING_SNAKE_CASE__ ( __lowerCAmelCase , __lowerCAmelCase ):
if digit_amount > 0:
return round(number - int(lowerCAmelCase_ ) , lowerCAmelCase_ )
return number - int(lowerCAmelCase_ )
if __name__ == "__main__":
print(decimal_isolate(1.5_3, 0))
print(decimal_isolate(3_5.3_4_5, 1))
print(decimal_isolate(3_5.3_4_5, 2))
print(decimal_isolate(3_5.3_4_5, 3))
print(decimal_isolate(-1_4.7_8_9, 3))
print(decimal_isolate(0, 2))
print(decimal_isolate(-1_4.1_2_3, 1))
print(decimal_isolate(-1_4.1_2_3, 2))
print(decimal_isolate(-1_4.1_2_3, 3))
| 707 |
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,
)
__magic_name__ = {
'''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:
__magic_name__ = ['''CLIPTokenizerFast''']
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ = ['''CLIPFeatureExtractor''']
__magic_name__ = ['''CLIPImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ = [
'''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''CLIPModel''',
'''CLIPPreTrainedModel''',
'''CLIPTextModel''',
'''CLIPTextModelWithProjection''',
'''CLIPVisionModel''',
'''CLIPVisionModelWithProjection''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ = [
'''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFCLIPModel''',
'''TFCLIPPreTrainedModel''',
'''TFCLIPTextModel''',
'''TFCLIPVisionModel''',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ = [
'''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
__magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 530 | 0 |
'''simple docstring'''
import argparse
A__ : Optional[Any] = """docs/source/_static/js/custom.js"""
def UpperCAmelCase__ ( UpperCAmelCase_ : Optional[int] ) -> int:
with open(UpperCAmelCase_ , encoding='utf-8' , newline='\n' ) as f:
__lowerCamelCase : Dict = f.readlines()
__lowerCamelCase : Tuple = 0
# First let's put the right version
while not lines[index].startswith('const stableVersion =' ):
index += 1
__lowerCamelCase : Dict = F'const stableVersion = "v{version}"\n'
# Then update the dictionary
while not lines[index].startswith('const versionMapping = {' ):
index += 1
# We go until the end
while not lines[index].startswith('}' ):
index += 1
# We add the new version at the end
lines[index - 1] += F' "v{version}": "v{version}",\n'
with open(UpperCAmelCase_ , 'w' , encoding='utf-8' , newline='\n' ) as f:
f.writelines(UpperCAmelCase_ )
if __name__ == "__main__":
A__ : str = argparse.ArgumentParser()
parser.add_argument("""--version""", help="""Release version.""")
A__ : Any = parser.parse_args()
update_custom_js(args.version)
| 13 |
'''simple docstring'''
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_roformer import RoFormerTokenizer
from .tokenization_utils import JiebaPreTokenizer
A__ : str = logging.get_logger(__name__)
A__ : str = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}
A__ : Tuple = {
"""vocab_file""": {
"""junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt""",
"""junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt""",
"""junnyu/roformer_chinese_char_small""": (
"""https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt"""
),
"""junnyu/roformer_chinese_char_base""": (
"""https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt"""
),
"""junnyu/roformer_small_discriminator""": (
"""https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt"""
),
"""junnyu/roformer_small_generator""": (
"""https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt"""
),
}
}
A__ : str = {
"""junnyu/roformer_chinese_small""": 1536,
"""junnyu/roformer_chinese_base""": 1536,
"""junnyu/roformer_chinese_char_small""": 512,
"""junnyu/roformer_chinese_char_base""": 512,
"""junnyu/roformer_small_discriminator""": 128,
"""junnyu/roformer_small_generator""": 128,
}
A__ : Tuple = {
"""junnyu/roformer_chinese_small""": {"""do_lower_case""": True},
"""junnyu/roformer_chinese_base""": {"""do_lower_case""": True},
"""junnyu/roformer_chinese_char_small""": {"""do_lower_case""": True},
"""junnyu/roformer_chinese_char_base""": {"""do_lower_case""": True},
"""junnyu/roformer_small_discriminator""": {"""do_lower_case""": True},
"""junnyu/roformer_small_generator""": {"""do_lower_case""": True},
}
class UpperCAmelCase_ (_UpperCAmelCase ):
"""simple docstring"""
lowerCamelCase : Union[str, Any] = VOCAB_FILES_NAMES
lowerCamelCase : int = PRETRAINED_VOCAB_FILES_MAP
lowerCamelCase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowerCamelCase : Optional[int] = PRETRAINED_INIT_CONFIGURATION
lowerCamelCase : Dict = RoFormerTokenizer
def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="[UNK]" , SCREAMING_SNAKE_CASE_="[SEP]" , SCREAMING_SNAKE_CASE_="[PAD]" , SCREAMING_SNAKE_CASE_="[CLS]" , SCREAMING_SNAKE_CASE_="[MASK]" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> Optional[Any]:
super().__init__(
SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , do_lower_case=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
__lowerCamelCase : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
pre_tok_state.get('lowercase' , SCREAMING_SNAKE_CASE_ ) != do_lower_case
or pre_tok_state.get('strip_accents' , SCREAMING_SNAKE_CASE_ ) != strip_accents
):
__lowerCamelCase : Optional[int] = getattr(SCREAMING_SNAKE_CASE_ , pre_tok_state.pop('type' ) )
__lowerCamelCase : Union[str, Any] = do_lower_case
__lowerCamelCase : str = strip_accents
__lowerCamelCase : Optional[Any] = pre_tok_class(**SCREAMING_SNAKE_CASE_ )
__lowerCamelCase : Tuple = do_lower_case
def __getstate__( self ) -> List[str]:
__lowerCamelCase : Union[str, Any] = self.__dict__.copy()
__lowerCamelCase : Dict = BertPreTokenizer()
return state
def __setstate__( self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]:
__lowerCamelCase : Optional[int] = d
__lowerCamelCase : List[Any] = self.__dict__['_tokenizer'].get_vocab()
__lowerCamelCase : Union[str, Any] = PreTokenizer.custom(JiebaPreTokenizer(SCREAMING_SNAKE_CASE_ ) )
def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> str:
__lowerCamelCase : Union[str, Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]:
__lowerCamelCase : List[str] = [self.sep_token_id]
__lowerCamelCase : Dict = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]:
__lowerCamelCase : Optional[Any] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ )
return tuple(SCREAMING_SNAKE_CASE_ )
def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ) -> Any:
__lowerCamelCase : Tuple = BertPreTokenizer()
return super().save_pretrained(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
| 13 | 1 |
'''simple docstring'''
import json
import os
import unittest
from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer
from transformers.testing_utils import slow
from ...test_tokenization_common import TokenizerTesterMixin
class __snake_case( __UpperCAmelCase , unittest.TestCase ):
'''simple docstring'''
UpperCAmelCase : Tuple = XLMTokenizer
UpperCAmelCase : int = False
def __snake_case ( self ) -> Any:
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
lowerCAmelCase = [
"""l""",
"""o""",
"""w""",
"""e""",
"""r""",
"""s""",
"""t""",
"""i""",
"""d""",
"""n""",
"""w</w>""",
"""r</w>""",
"""t</w>""",
"""lo""",
"""low""",
"""er</w>""",
"""low</w>""",
"""lowest</w>""",
"""newer</w>""",
"""wider</w>""",
"""<unk>""",
]
lowerCAmelCase = dict(zip(A_ , range(len(A_ ) ) ) )
lowerCAmelCase = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""]
lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] )
lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] )
with open(self.vocab_file , """w""" ) as fp:
fp.write(json.dumps(A_ ) )
with open(self.merges_file , """w""" ) as fp:
fp.write("""\n""".join(A_ ) )
def __snake_case ( self , A_ ) -> List[Any]:
lowerCAmelCase = """lower newer"""
lowerCAmelCase = """lower newer"""
return input_text, output_text
def __snake_case ( self ) -> int:
lowerCAmelCase = XLMTokenizer(self.vocab_file , self.merges_file )
lowerCAmelCase = """lower"""
lowerCAmelCase = ["""low""", """er</w>"""]
lowerCAmelCase = tokenizer.tokenize(A_ )
self.assertListEqual(A_ , A_ )
lowerCAmelCase = tokens + ["""<unk>"""]
lowerCAmelCase = [14, 15, 20]
self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ )
@slow
def __snake_case ( self ) -> Optional[Any]:
lowerCAmelCase = XLMTokenizer.from_pretrained("""xlm-mlm-en-2048""" )
lowerCAmelCase = tokenizer.encode("""sequence builders""" , add_special_tokens=A_ )
lowerCAmelCase = tokenizer.encode("""multi-sequence build""" , add_special_tokens=A_ )
lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(A_ )
lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(A_ , A_ )
assert encoded_sentence == [0] + text + [1]
assert encoded_pair == [0] + text + [1] + text_a + [1] | 717 |
'''simple docstring'''
def _snake_case ( _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float ) -> float:
"""simple docstring"""
if density <= 0:
raise ValueError("""Impossible fluid density""" )
if bulk_modulus <= 0:
raise ValueError("""Impossible bulk modulus""" )
return (bulk_modulus / density) ** 0.5
if __name__ == "__main__":
import doctest
doctest.testmod() | 344 | 0 |
import argparse
import torch
from torch import nn
from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration
def SCREAMING_SNAKE_CASE__ ( lowercase ) -> Optional[int]:
snake_case : Tuple = [
"""encoder.version""",
"""decoder.version""",
"""model.encoder.version""",
"""model.decoder.version""",
"""decoder.output_projection.weight""",
"""_float_tensor""",
"""encoder.embed_positions._float_tensor""",
"""decoder.embed_positions._float_tensor""",
]
for k in ignore_keys:
state_dict.pop(lowercase ,lowercase )
def SCREAMING_SNAKE_CASE__ ( lowercase ) -> Dict:
snake_case : List[str] = list(s_dict.keys() )
for key in keys:
if "transformer_layers" in key:
snake_case : Optional[Any] = s_dict.pop(lowercase )
elif "subsample" in key:
snake_case : Optional[Any] = s_dict.pop(lowercase )
def SCREAMING_SNAKE_CASE__ ( lowercase ) -> Dict:
snake_case , snake_case : Optional[Any] = emb.weight.shape
snake_case : Tuple = nn.Linear(lowercase ,lowercase ,bias=lowercase )
snake_case : int = emb.weight.data
return lin_layer
def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> Dict:
snake_case : Any = torch.load(lowercase ,map_location="""cpu""" )
snake_case : int = mam_aaa["""args"""]
snake_case : Tuple = mam_aaa["""model"""]
snake_case : Union[str, Any] = state_dict["""decoder.output_projection.weight"""]
remove_ignore_keys_(lowercase )
rename_keys(lowercase )
snake_case : List[Any] = state_dict["""decoder.embed_tokens.weight"""].shape[0]
snake_case : Optional[int] = args.share_decoder_input_output_embed
snake_case : List[Any] = [int(lowercase ) for i in args.conv_kernel_sizes.split(""",""" )]
snake_case : Optional[int] = SpeechaTextConfig(
vocab_size=lowercase ,max_source_positions=args.max_source_positions ,max_target_positions=args.max_target_positions ,encoder_layers=args.encoder_layers ,decoder_layers=args.decoder_layers ,encoder_attention_heads=args.encoder_attention_heads ,decoder_attention_heads=args.decoder_attention_heads ,encoder_ffn_dim=args.encoder_ffn_embed_dim ,decoder_ffn_dim=args.decoder_ffn_embed_dim ,d_model=args.encoder_embed_dim ,dropout=args.dropout ,attention_dropout=args.attention_dropout ,activation_dropout=args.activation_dropout ,activation_function="""relu""" ,num_conv_layers=len(lowercase ) ,conv_channels=args.conv_channels ,conv_kernel_sizes=lowercase ,input_feat_per_channel=args.input_feat_per_channel ,input_channels=args.input_channels ,tie_word_embeddings=lowercase ,num_beams=5 ,max_length=200 ,use_cache=lowercase ,decoder_start_token_id=2 ,early_stopping=lowercase ,)
snake_case : Any = SpeechaTextForConditionalGeneration(lowercase )
snake_case , snake_case : Optional[int] = model.model.load_state_dict(lowercase ,strict=lowercase )
if len(lowercase ) > 0 and not set(lowercase ) <= {
"encoder.embed_positions.weights",
"decoder.embed_positions.weights",
}:
raise ValueError(
"""Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,"""
f""" but all the following weights are missing {missing}""" )
if tie_embeds:
snake_case : Tuple = make_linear_from_emb(model.model.decoder.embed_tokens )
else:
snake_case : List[Any] = lm_head_weights
model.save_pretrained(lowercase )
if __name__ == "__main__":
lowerCamelCase : str = argparse.ArgumentParser()
# Required parameters
parser.add_argument('--fairseq_path', type=str, help='Path to the fairseq model (.pt) file.')
parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
lowerCamelCase : str = parser.parse_args()
convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
| 587 |
def SCREAMING_SNAKE_CASE__ ( lowercase ) -> list[list]:
snake_case : List[str] = current_set.copy()
for row_index, row in enumerate(lowercase ):
snake_case : List[Any] = row[0]
for column_index, column in enumerate(lowercase ):
if magnitude == 0:
snake_case : Tuple = column
continue
snake_case : Dict = column / magnitude
# Subtract to cancel term
snake_case : Union[str, Any] = current_set[0]
snake_case : int = [first_row]
snake_case : Dict = current_set[1::]
for row in current_set:
snake_case : List[Any] = []
# If first term is 0, it is already in form we want, so we preserve it
if row[0] == 0:
final_set.append(lowercase )
continue
for column_index in range(len(lowercase ) ):
temp_row.append(first_row[column_index] - row[column_index] )
final_set.append(lowercase )
# Create next recursion iteration set
if len(final_set[0] ) != 3:
snake_case : Optional[Any] = final_set[0]
snake_case : List[str] = []
snake_case : Dict = []
for row in final_set[1::]:
current_first_column.append(row[0] )
next_iteration.append(row[1::] )
snake_case : Dict = simplify(lowercase )
for i in range(len(lowercase ) ):
resultant[i].insert(0 ,current_first_column[i] )
resultant.insert(0 ,lowercase )
snake_case : List[str] = resultant
return final_set
def SCREAMING_SNAKE_CASE__ ( lowercase ) -> list:
if len(lowercase ) == 0:
raise IndexError("""solve_simultaneous() requires n lists of length n+1""" )
snake_case : List[Any] = len(lowercase ) + 1
if any(len(lowercase ) != _length for item in equations ):
raise IndexError("""solve_simultaneous() requires n lists of length n+1""" )
for row in equations:
if any(not isinstance(lowercase ,(int, float) ) for column in row ):
raise ValueError("""solve_simultaneous() requires lists of integers""" )
if len(lowercase ) == 1:
return [equations[0][-1] / equations[0][0]]
snake_case : List[Any] = equations.copy()
if any(0 in row for row in data_set ):
snake_case : Union[str, Any] = data_set.copy()
snake_case : str = []
for row_index, row in enumerate(lowercase ):
if 0 not in row:
snake_case : Optional[Any] = data_set.pop(lowercase )
break
if not full_row:
raise ValueError("""solve_simultaneous() requires at least 1 full equation""" )
data_set.insert(0 ,lowercase )
snake_case : Dict = data_set.copy()
snake_case : List[str] = simplify(lowercase )
snake_case : str = simplified[::-1]
snake_case : list = []
for row in simplified:
snake_case : List[Any] = row[-1]
if not solutions:
if row[-2] == 0:
solutions.append(0 )
continue
solutions.append(current_solution / row[-2] )
continue
snake_case : List[str] = row.copy()[: len(lowercase ) - 1 :]
while temp_row[0] == 0:
temp_row.pop(0 )
if len(lowercase ) == 0:
solutions.append(0 )
continue
snake_case : List[str] = temp_row[1::]
snake_case : str = temp_row[::-1]
for column_index, column in enumerate(lowercase ):
current_solution -= column * solutions[column_index]
solutions.append(lowercase )
snake_case : List[Any] = []
for item in solutions:
final.append(float(round(lowercase ,5 ) ) )
return final[::-1]
if __name__ == "__main__":
import doctest
doctest.testmod()
lowerCamelCase : Union[str, Any] = [
[2, 1, 1, 1, 1, 4],
[1, 2, 1, 1, 1, 5],
[1, 1, 2, 1, 1, 6],
[1, 1, 1, 2, 1, 7],
[1, 1, 1, 1, 2, 8],
]
print(solve_simultaneous(eq))
print(solve_simultaneous([[4, 2]]))
| 587 | 1 |
class UpperCAmelCase ( __snake_case ):
pass
class UpperCAmelCase ( __snake_case ):
pass
class UpperCAmelCase :
def __init__( self : int ):
"""simple docstring"""
UpperCamelCase = [
[],
[],
[],
]
def lowerCamelCase_ ( self : int , __magic_name__ : Tuple , __magic_name__ : List[str] ):
"""simple docstring"""
try:
if len(self.queues[priority] ) >= 1_0_0:
raise OverflowError("""Maximum queue size is 100""" )
self.queues[priority].append(__magic_name__ )
except IndexError:
raise ValueError("""Valid priorities are 0, 1, and 2""" )
def lowerCamelCase_ ( self : Dict ):
"""simple docstring"""
for queue in self.queues:
if queue:
return queue.pop(0 )
raise UnderFlowError("""All queues are empty""" )
def __str__( self : str ):
"""simple docstring"""
return "\n".join(F'Priority {i}: {q}' for i, q in enumerate(self.queues ) )
class UpperCAmelCase :
def __init__( self : Union[str, Any] ):
"""simple docstring"""
UpperCamelCase = []
def lowerCamelCase_ ( self : Any , __magic_name__ : str ):
"""simple docstring"""
if len(self.queue ) == 1_0_0:
raise OverFlowError("""Maximum queue size is 100""" )
self.queue.append(__magic_name__ )
def lowerCamelCase_ ( self : Optional[Any] ):
"""simple docstring"""
if not self.queue:
raise UnderFlowError("""The queue is empty""" )
else:
UpperCamelCase = min(self.queue )
self.queue.remove(__magic_name__ )
return data
def __str__( self : Optional[int] ):
"""simple docstring"""
return str(self.queue )
def _lowercase ( ):
"""simple docstring"""
UpperCamelCase = FixedPriorityQueue()
fpq.enqueue(0 , 10 )
fpq.enqueue(1 , 70 )
fpq.enqueue(0 , 100 )
fpq.enqueue(2 , 1 )
fpq.enqueue(2 , 5 )
fpq.enqueue(1 , 7 )
fpq.enqueue(2 , 4 )
fpq.enqueue(1 , 64 )
fpq.enqueue(0 , 128 )
print(_UpperCamelCase )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(_UpperCamelCase )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(fpq.dequeue() )
def _lowercase ( ):
"""simple docstring"""
UpperCamelCase = ElementPriorityQueue()
epq.enqueue(10 )
epq.enqueue(70 )
epq.enqueue(100 )
epq.enqueue(1 )
epq.enqueue(5 )
epq.enqueue(7 )
epq.enqueue(4 )
epq.enqueue(64 )
epq.enqueue(128 )
print(_UpperCamelCase )
print(epq.dequeue() )
print(epq.dequeue() )
print(epq.dequeue() )
print(epq.dequeue() )
print(epq.dequeue() )
print(_UpperCamelCase )
print(epq.dequeue() )
print(epq.dequeue() )
print(epq.dequeue() )
print(epq.dequeue() )
print(epq.dequeue() )
if __name__ == "__main__":
fixed_priority_queue()
element_priority_queue()
| 716 |
import json
import os
import unittest
from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer
from transformers.testing_utils import slow
from ...test_tokenization_common import TokenizerTesterMixin
class UpperCAmelCase ( __snake_case , unittest.TestCase ):
lowercase = XLMTokenizer
lowercase = False
def lowerCamelCase_ ( self : Optional[int] ):
"""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""",
"""w</w>""",
"""r</w>""",
"""t</w>""",
"""lo""",
"""low""",
"""er</w>""",
"""low</w>""",
"""lowest</w>""",
"""newer</w>""",
"""wider</w>""",
"""<unk>""",
]
UpperCamelCase = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) )
UpperCamelCase = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""]
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""" ) as fp:
fp.write(json.dumps(__magic_name__ ) )
with open(self.merges_file , """w""" ) as fp:
fp.write("""\n""".join(__magic_name__ ) )
def lowerCamelCase_ ( self : Any , __magic_name__ : List[str] ):
"""simple docstring"""
UpperCamelCase = """lower newer"""
UpperCamelCase = """lower newer"""
return input_text, output_text
def lowerCamelCase_ ( self : List[str] ):
"""simple docstring"""
UpperCamelCase = XLMTokenizer(self.vocab_file , self.merges_file )
UpperCamelCase = """lower"""
UpperCamelCase = ["""low""", """er</w>"""]
UpperCamelCase = tokenizer.tokenize(__magic_name__ )
self.assertListEqual(__magic_name__ , __magic_name__ )
UpperCamelCase = tokens + ["""<unk>"""]
UpperCamelCase = [1_4, 1_5, 2_0]
self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ )
@slow
def lowerCamelCase_ ( self : Optional[int] ):
"""simple docstring"""
UpperCamelCase = XLMTokenizer.from_pretrained("""xlm-mlm-en-2048""" )
UpperCamelCase = tokenizer.encode("""sequence builders""" , add_special_tokens=__magic_name__ )
UpperCamelCase = tokenizer.encode("""multi-sequence build""" , add_special_tokens=__magic_name__ )
UpperCamelCase = tokenizer.build_inputs_with_special_tokens(__magic_name__ )
UpperCamelCase = tokenizer.build_inputs_with_special_tokens(__magic_name__ , __magic_name__ )
assert encoded_sentence == [0] + text + [1]
assert encoded_pair == [0] + text + [1] + text_a + [1]
| 181 | 0 |
"""simple docstring"""
from __future__ import annotations
import time
import numpy as np
lowerCAmelCase: int =[8, 5, 9, 7]
lowerCAmelCase: Union[str, Any] =[
[2, 0, 1, 1],
[0, 1, 2, 1],
[4, 0, 0, 3],
[0, 2, 1, 0],
[1, 0, 3, 0],
]
lowerCAmelCase: Dict =[
[3, 2, 1, 4],
[0, 2, 5, 2],
[5, 1, 0, 5],
[1, 5, 3, 0],
[3, 0, 3, 3],
]
class lowerCamelCase__ :
def __init__( self , snake_case , snake_case , snake_case , ) -> None:
"""simple docstring"""
lowercase : List[str] = claim_vector
lowercase : Any = allocated_resources_table
lowercase : Optional[Any] = maximum_claim_table
def _UpperCAmelCase ( self ) -> list[int]:
"""simple docstring"""
return [
sum(p_item[i] for p_item in self.__allocated_resources_table )
for i in range(len(self.__allocated_resources_table[0] ) )
]
def _UpperCAmelCase ( self ) -> list[int]:
"""simple docstring"""
return np.array(self.__claim_vector ) - np.array(
self.__processes_resource_summation() )
def _UpperCAmelCase ( self ) -> list[list[int]]:
"""simple docstring"""
return [
list(np.array(self.__maximum_claim_table[i] ) - np.array(snake_case ) )
for i, allocated_resource in enumerate(self.__allocated_resources_table )
]
def _UpperCAmelCase ( self ) -> dict[int, list[int]]:
"""simple docstring"""
return {self.__need().index(snake_case ): i for i in self.__need()}
def _UpperCAmelCase ( self , **snake_case ) -> None:
"""simple docstring"""
lowercase : str = self.__need()
lowercase : List[str] = self.__allocated_resources_table
lowercase : Tuple = self.__available_resources()
lowercase : int = self.__need_index_manager()
for kw, val in kwargs.items():
if kw and val is True:
self.__pretty_data()
print("""_""" * 5_0 + """\n""" )
while need_list:
lowercase : List[str] = False
for each_need in need_list:
lowercase : Any = True
for index, need in enumerate(snake_case ):
if need > available_resources[index]:
lowercase : Any = False
break
if execution:
lowercase : Union[str, Any] = True
# get the original index of the process from ind_ctrl db
for original_need_index, need_clone in need_index_manager.items():
if each_need == need_clone:
lowercase : Union[str, Any] = original_need_index
print(f'''Process {process_number + 1} is executing.''' )
# remove the process run from stack
need_list.remove(snake_case )
# update available/freed resources stack
lowercase : str = np.array(snake_case ) + np.array(
alloc_resources_table[process_number] )
print(
"""Updated available resource stack for processes: """
+ """ """.join([str(snake_case ) for x in available_resources] ) )
break
if safe:
print("""The process is in a safe state.\n""" )
else:
print("""System in unsafe state. Aborting...\n""" )
break
def _UpperCAmelCase ( self ) -> Any:
"""simple docstring"""
print(""" """ * 9 + """Allocated Resource Table""" )
for item in self.__allocated_resources_table:
print(
f'''P{self.__allocated_resources_table.index(snake_case ) + 1}'''
+ """ """.join(f'''{it:>8}''' for it in item )
+ """\n""" )
print(""" """ * 9 + """System Resource Table""" )
for item in self.__maximum_claim_table:
print(
f'''P{self.__maximum_claim_table.index(snake_case ) + 1}'''
+ """ """.join(f'''{it:>8}''' for it in item )
+ """\n""" )
print(
"""Current Usage by Active Processes: """
+ """ """.join(str(snake_case ) for x in self.__claim_vector ) )
print(
"""Initial Available Resources: """
+ """ """.join(str(snake_case ) for x in self.__available_resources() ) )
time.sleep(1 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 607 |
"""simple docstring"""
import json
import os
import unittest
from transformers import BatchEncoding, MvpTokenizer, MvpTokenizerFast
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin, filter_roberta_detectors
@require_tokenizers
class lowerCamelCase__ ( __UpperCamelCase , unittest.TestCase ):
__UpperCAmelCase = MvpTokenizer
__UpperCAmelCase = MvpTokenizerFast
__UpperCAmelCase = True
__UpperCAmelCase = filter_roberta_detectors
def _UpperCAmelCase ( self ) -> Union[str, Any]:
"""simple docstring"""
super().setUp()
lowercase : Union[str, Any] = [
"""l""",
"""o""",
"""w""",
"""e""",
"""r""",
"""s""",
"""t""",
"""i""",
"""d""",
"""n""",
"""\u0120""",
"""\u0120l""",
"""\u0120n""",
"""\u0120lo""",
"""\u0120low""",
"""er""",
"""\u0120lowest""",
"""\u0120newer""",
"""\u0120wider""",
"""<unk>""",
]
lowercase : Optional[Any] = dict(zip(snake_case , range(len(snake_case ) ) ) )
lowercase : Dict = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
lowercase : int = {"""unk_token""": """<unk>"""}
lowercase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] )
lowercase : Dict = 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(snake_case ) + """\n""" )
with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp:
fp.write("""\n""".join(snake_case ) )
def _UpperCAmelCase ( self , **snake_case ) -> int:
"""simple docstring"""
kwargs.update(self.special_tokens_map )
return self.tokenizer_class.from_pretrained(self.tmpdirname , **snake_case )
def _UpperCAmelCase ( self , **snake_case ) -> Dict:
"""simple docstring"""
kwargs.update(self.special_tokens_map )
return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **snake_case )
def _UpperCAmelCase ( self , snake_case ) -> Optional[int]:
"""simple docstring"""
return "lower newer", "lower newer"
@cached_property
def _UpperCAmelCase ( self ) -> Optional[int]:
"""simple docstring"""
return MvpTokenizer.from_pretrained("""RUCAIBox/mvp""" )
@cached_property
def _UpperCAmelCase ( self ) -> Optional[Any]:
"""simple docstring"""
return MvpTokenizerFast.from_pretrained("""RUCAIBox/mvp""" )
@require_torch
def _UpperCAmelCase ( self ) -> Optional[Any]:
"""simple docstring"""
lowercase : str = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""]
lowercase : Dict = [0, 2_5_0, 2_5_1, 1_7_8_1_8, 1_3, 3_9_1_8_6, 1_9_3_8, 4, 2]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowercase : Union[str, Any] = tokenizer(snake_case , max_length=len(snake_case ) , padding=snake_case , return_tensors="""pt""" )
self.assertIsInstance(snake_case , snake_case )
self.assertEqual((2, 9) , batch.input_ids.shape )
self.assertEqual((2, 9) , batch.attention_mask.shape )
lowercase : List[Any] = batch.input_ids.tolist()[0]
self.assertListEqual(snake_case , snake_case )
# Test that special tokens are reset
@require_torch
def _UpperCAmelCase ( self ) -> Tuple:
"""simple docstring"""
lowercase : List[str] = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowercase : Any = tokenizer(snake_case , padding=snake_case , return_tensors="""pt""" )
# check if input_ids are returned and no labels
self.assertIn("""input_ids""" , snake_case )
self.assertIn("""attention_mask""" , snake_case )
self.assertNotIn("""labels""" , snake_case )
self.assertNotIn("""decoder_attention_mask""" , snake_case )
@require_torch
def _UpperCAmelCase ( self ) -> Dict:
"""simple docstring"""
lowercase : Optional[int] = [
"""Summary of the text.""",
"""Another summary.""",
]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowercase : int = tokenizer(text_target=snake_case , max_length=3_2 , padding="""max_length""" , return_tensors="""pt""" )
self.assertEqual(3_2 , targets["""input_ids"""].shape[1] )
@require_torch
def _UpperCAmelCase ( self ) -> Union[str, Any]:
"""simple docstring"""
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowercase : str = tokenizer(
["""I am a small frog""" * 1_0_2_4, """I am a small frog"""] , padding=snake_case , truncation=snake_case , return_tensors="""pt""" )
self.assertIsInstance(snake_case , snake_case )
self.assertEqual(batch.input_ids.shape , (2, 1_0_2_4) )
@require_torch
def _UpperCAmelCase ( self ) -> Dict:
"""simple docstring"""
lowercase : List[Any] = ["""A long paragraph for summarization."""]
lowercase : List[str] = [
"""Summary of the text.""",
]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowercase : List[str] = tokenizer(snake_case , text_target=snake_case , return_tensors="""pt""" )
lowercase : Union[str, Any] = inputs["""input_ids"""]
lowercase : Optional[Any] = inputs["""labels"""]
self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() )
self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() )
self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() )
self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() )
def _UpperCAmelCase ( self ) -> int:
"""simple docstring"""
pass
def _UpperCAmelCase ( self ) -> Tuple:
"""simple docstring"""
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
lowercase : List[str] = self.rust_tokenizer_class.from_pretrained(snake_case , **snake_case )
lowercase : Optional[Any] = self.tokenizer_class.from_pretrained(snake_case , **snake_case )
lowercase : str = """A, <mask> AllenNLP sentence."""
lowercase : int = tokenizer_r.encode_plus(snake_case , add_special_tokens=snake_case , return_token_type_ids=snake_case )
lowercase : str = tokenizer_p.encode_plus(snake_case , add_special_tokens=snake_case , return_token_type_ids=snake_case )
# token_type_ids should put 0 everywhere
self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) )
# attention_mask should put 1 everywhere, so sum over length should be 1
self.assertEqual(
sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , )
lowercase : Tuple = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] )
lowercase : Tuple = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] )
# Rust correctly handles the space before the mask while python doesnt
self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] )
self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] )
self.assertSequenceEqual(
snake_case , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] )
self.assertSequenceEqual(
snake_case , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] )
| 607 | 1 |
"""simple docstring"""
import copy
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
__lowerCAmelCase : List[str] = logging.get_logger(__name__)
__lowerCAmelCase : Union[str, Any] = {
'''microsoft/conditional-detr-resnet-50''': (
'''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json'''
),
}
class SCREAMING_SNAKE_CASE ( lowerCAmelCase ):
'''simple docstring'''
snake_case__ : Optional[int] = 'conditional_detr'
snake_case__ : Dict = ['past_key_values']
snake_case__ : str = {
'hidden_size': 'd_model',
'num_attention_heads': 'encoder_attention_heads',
}
def __init__( self :Optional[Any] , __magic_name__ :Optional[int]=True , __magic_name__ :Optional[int]=None , __magic_name__ :Dict=3 , __magic_name__ :List[str]=300 , __magic_name__ :List[str]=6 , __magic_name__ :Union[str, Any]=2048 , __magic_name__ :List[Any]=8 , __magic_name__ :List[Any]=6 , __magic_name__ :Any=2048 , __magic_name__ :int=8 , __magic_name__ :Tuple=0.0 , __magic_name__ :Dict=0.0 , __magic_name__ :Any=True , __magic_name__ :List[Any]="relu" , __magic_name__ :Any=256 , __magic_name__ :int=0.1 , __magic_name__ :Optional[int]=0.0 , __magic_name__ :Dict=0.0 , __magic_name__ :str=0.02 , __magic_name__ :Optional[int]=1.0 , __magic_name__ :Any=False , __magic_name__ :Tuple="sine" , __magic_name__ :Optional[int]="resnet50" , __magic_name__ :List[str]=True , __magic_name__ :int=False , __magic_name__ :str=2 , __magic_name__ :Optional[int]=5 , __magic_name__ :Optional[Any]=2 , __magic_name__ :Optional[int]=1 , __magic_name__ :Optional[int]=1 , __magic_name__ :Union[str, Any]=2 , __magic_name__ :str=5 , __magic_name__ :Tuple=2 , __magic_name__ :List[Any]=0.25 , **__magic_name__ :List[str] , ) -> int:
'''simple docstring'''
if backbone_config is not None and use_timm_backbone:
raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' )
if not use_timm_backbone:
if backbone_config is None:
logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' )
a__ = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] )
elif isinstance(__magic_name__ , __magic_name__ ):
a__ = backbone_config.get('''model_type''' )
a__ = CONFIG_MAPPING[backbone_model_type]
a__ = config_class.from_dict(__magic_name__ )
a__ = use_timm_backbone
a__ = backbone_config
a__ = num_channels
a__ = num_queries
a__ = d_model
a__ = encoder_ffn_dim
a__ = encoder_layers
a__ = encoder_attention_heads
a__ = decoder_ffn_dim
a__ = decoder_layers
a__ = decoder_attention_heads
a__ = dropout
a__ = attention_dropout
a__ = activation_dropout
a__ = activation_function
a__ = init_std
a__ = init_xavier_std
a__ = encoder_layerdrop
a__ = decoder_layerdrop
a__ = encoder_layers
a__ = auxiliary_loss
a__ = position_embedding_type
a__ = backbone
a__ = use_pretrained_backbone
a__ = dilation
# Hungarian matcher
a__ = class_cost
a__ = bbox_cost
a__ = giou_cost
# Loss coefficients
a__ = mask_loss_coefficient
a__ = dice_loss_coefficient
a__ = cls_loss_coefficient
a__ = bbox_loss_coefficient
a__ = giou_loss_coefficient
a__ = focal_alpha
super().__init__(is_encoder_decoder=__magic_name__ , **__magic_name__ )
@property
def _UpperCamelCase ( self :List[str] ) -> int:
'''simple docstring'''
return self.encoder_attention_heads
@property
def _UpperCamelCase ( self :Any ) -> int:
'''simple docstring'''
return self.d_model
def _UpperCamelCase ( self :Dict ) -> int:
'''simple docstring'''
a__ = copy.deepcopy(self.__dict__ )
if self.backbone_config is not None:
a__ = self.backbone_config.to_dict()
a__ = self.__class__.model_type
return output
class SCREAMING_SNAKE_CASE ( lowerCAmelCase ):
'''simple docstring'''
snake_case__ : Tuple = version.parse('1.11' )
@property
def _UpperCamelCase ( self :Tuple ) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
return OrderedDict(
[
('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
('''pixel_mask''', {0: '''batch'''}),
] )
@property
def _UpperCamelCase ( self :Any ) -> float:
'''simple docstring'''
return 1e-5
@property
def _UpperCamelCase ( self :int ) -> int:
'''simple docstring'''
return 12
| 700 |
"""simple docstring"""
from __future__ import annotations
__lowerCAmelCase : Union[str, Any] = list[tuple[int, int]]
__lowerCAmelCase : Optional[int] = [
[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 : Dict = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right
class SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__( self :str , __magic_name__ :int , __magic_name__ :int , __magic_name__ :int , __magic_name__ :int , __magic_name__ :float , __magic_name__ :Node | None , ) -> Tuple:
'''simple docstring'''
a__ = pos_x
a__ = pos_y
a__ = (pos_y, pos_x)
a__ = goal_x
a__ = goal_y
a__ = g_cost
a__ = parent
a__ = self.calculate_heuristic()
def _UpperCamelCase ( self :int ) -> float:
'''simple docstring'''
a__ = abs(self.pos_x - self.goal_x )
a__ = abs(self.pos_y - self.goal_y )
return dx + dy
def __lt__( self :List[str] , __magic_name__ :List[Any] ) -> bool:
'''simple docstring'''
return self.f_cost < other.f_cost
class SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__( self :Dict , __magic_name__ :tuple[int, int] , __magic_name__ :tuple[int, int] ) -> Tuple:
'''simple docstring'''
a__ = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , __magic_name__ )
a__ = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , __magic_name__ )
a__ = [self.start]
a__ = []
a__ = False
def _UpperCamelCase ( self :Union[str, Any] ) -> Path | None:
'''simple docstring'''
while self.open_nodes:
# Open Nodes are sorted using __lt__
self.open_nodes.sort()
a__ = self.open_nodes.pop(0 )
if current_node.pos == self.target.pos:
a__ = True
return self.retrace_path(__magic_name__ )
self.closed_nodes.append(__magic_name__ )
a__ = self.get_successors(__magic_name__ )
for child_node in successors:
if child_node in self.closed_nodes:
continue
if child_node not in self.open_nodes:
self.open_nodes.append(__magic_name__ )
else:
# retrieve the best current path
a__ = self.open_nodes.pop(self.open_nodes.index(__magic_name__ ) )
if child_node.g_cost < better_node.g_cost:
self.open_nodes.append(__magic_name__ )
else:
self.open_nodes.append(__magic_name__ )
if not self.reached:
return [self.start.pos]
return None
def _UpperCamelCase ( self :List[str] , __magic_name__ :Node ) -> list[Node]:
'''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(__magic_name__ ) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(
__magic_name__ , __magic_name__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , __magic_name__ , ) )
return successors
def _UpperCamelCase ( self :Any , __magic_name__ :Node | None ) -> Path:
'''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
if __name__ == "__main__":
__lowerCAmelCase : str = (0, 0)
__lowerCAmelCase : Dict = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
print('''------''')
__lowerCAmelCase : Optional[int] = GreedyBestFirst(init, goal)
__lowerCAmelCase : Tuple = greedy_bf.search()
if path:
for pos_x, pos_y in path:
__lowerCAmelCase : Tuple = 2
for elem in grid:
print(elem)
| 158 | 0 |
from __future__ import annotations
from collections.abc import Generator
import requests
from bsa import BeautifulSoup
lowerCAmelCase__: Dict = "https://www.indeed.co.in/jobs?q=mobile+app+development&l="
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE = "mumbai" ) -> Generator[tuple[str, str], None, None]:
SCREAMING_SNAKE_CASE_ : List[Any] = BeautifulSoup(requests.get(url + location ).content , 'html.parser' )
# This attribute finds out all the specifics listed in a job
for job in soup.find_all('div' , attrs={'data-tn-component': 'organicJob'} ):
SCREAMING_SNAKE_CASE_ : List[Any] = job.find('a' , attrs={'data-tn-element': 'jobTitle'} ).text.strip()
SCREAMING_SNAKE_CASE_ : Any = job.find('span' , {'class': 'company'} ).text.strip()
yield job_title, company_name
if __name__ == "__main__":
for i, job in enumerate(fetch_jobs("Bangalore"), 1):
print(f'''Job {i:>2} is {job[0]} at {job[1]}''')
| 345 |
import os
import shutil
from pathlib import Path
from typing import Optional, Union
import numpy as np
from huggingface_hub import hf_hub_download
from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging
if is_onnx_available():
import onnxruntime as ort
lowerCAmelCase__: Dict = logging.get_logger(__name__)
lowerCAmelCase__: Dict = {
"tensor(bool)": np.bool_,
"tensor(int8)": np.inta,
"tensor(uint8)": np.uinta,
"tensor(int16)": np.intaa,
"tensor(uint16)": np.uintaa,
"tensor(int32)": np.intaa,
"tensor(uint32)": np.uintaa,
"tensor(int64)": np.intaa,
"tensor(uint64)": np.uintaa,
"tensor(float16)": np.floataa,
"tensor(float)": np.floataa,
"tensor(double)": np.floataa,
}
class snake_case_ :
def __init__( self , __lowerCAmelCase=None , **__lowerCAmelCase ):
logger.info('`diffusers.OnnxRuntimeModel` is experimental and might change in the future.' )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = model
SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('model_save_dir' , __lowerCAmelCase )
SCREAMING_SNAKE_CASE_ : Optional[int] = kwargs.get('latest_model_name' , __lowerCAmelCase )
def __call__( self , **__lowerCAmelCase ):
SCREAMING_SNAKE_CASE_ : List[Any] = {k: np.array(__lowerCAmelCase ) for k, v in kwargs.items()}
return self.model.run(__lowerCAmelCase , __lowerCAmelCase )
@staticmethod
def __A ( __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None ):
if provider is None:
logger.info('No onnxruntime provider specified, using CPUExecutionProvider' )
SCREAMING_SNAKE_CASE_ : Tuple = 'CPUExecutionProvider'
return ort.InferenceSession(__lowerCAmelCase , providers=[provider] , sess_options=__lowerCAmelCase )
def __A ( self , __lowerCAmelCase , __lowerCAmelCase = None , **__lowerCAmelCase ):
SCREAMING_SNAKE_CASE_ : Optional[int] = file_name if file_name is not None else ONNX_WEIGHTS_NAME
SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_save_dir.joinpath(self.latest_model_name )
SCREAMING_SNAKE_CASE_ : int = Path(__lowerCAmelCase ).joinpath(__lowerCAmelCase )
try:
shutil.copyfile(__lowerCAmelCase , __lowerCAmelCase )
except shutil.SameFileError:
pass
# copy external weights (for models >2GB)
SCREAMING_SNAKE_CASE_ : str = self.model_save_dir.joinpath(__lowerCAmelCase )
if src_path.exists():
SCREAMING_SNAKE_CASE_ : List[str] = Path(__lowerCAmelCase ).joinpath(__lowerCAmelCase )
try:
shutil.copyfile(__lowerCAmelCase , __lowerCAmelCase )
except shutil.SameFileError:
pass
def __A ( self , __lowerCAmelCase , **__lowerCAmelCase , ):
if os.path.isfile(__lowerCAmelCase ):
logger.error(F'Provided path ({save_directory}) should be a directory, not a file' )
return
os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase )
# saving model weights/files
self._save_pretrained(__lowerCAmelCase , **__lowerCAmelCase )
@classmethod
def __A ( cls , __lowerCAmelCase , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = False , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = None , **__lowerCAmelCase , ):
SCREAMING_SNAKE_CASE_ : List[str] = file_name if file_name is not None else ONNX_WEIGHTS_NAME
# load model from local directory
if os.path.isdir(__lowerCAmelCase ):
SCREAMING_SNAKE_CASE_ : Optional[int] = OnnxRuntimeModel.load_model(
os.path.join(__lowerCAmelCase , __lowerCAmelCase ) , provider=__lowerCAmelCase , sess_options=__lowerCAmelCase )
SCREAMING_SNAKE_CASE_ : str = Path(__lowerCAmelCase )
# load model from hub
else:
# download model
SCREAMING_SNAKE_CASE_ : int = hf_hub_download(
repo_id=__lowerCAmelCase , filename=__lowerCAmelCase , use_auth_token=__lowerCAmelCase , revision=__lowerCAmelCase , cache_dir=__lowerCAmelCase , force_download=__lowerCAmelCase , )
SCREAMING_SNAKE_CASE_ : str = Path(__lowerCAmelCase ).parent
SCREAMING_SNAKE_CASE_ : Optional[Any] = Path(__lowerCAmelCase ).name
SCREAMING_SNAKE_CASE_ : Tuple = OnnxRuntimeModel.load_model(__lowerCAmelCase , provider=__lowerCAmelCase , sess_options=__lowerCAmelCase )
return cls(model=__lowerCAmelCase , **__lowerCAmelCase )
@classmethod
def __A ( cls , __lowerCAmelCase , __lowerCAmelCase = True , __lowerCAmelCase = None , __lowerCAmelCase = None , **__lowerCAmelCase , ):
SCREAMING_SNAKE_CASE_ : Tuple = None
if len(str(__lowerCAmelCase ).split('@' ) ) == 2:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = model_id.split('@' )
return cls._from_pretrained(
model_id=__lowerCAmelCase , revision=__lowerCAmelCase , cache_dir=__lowerCAmelCase , force_download=__lowerCAmelCase , use_auth_token=__lowerCAmelCase , **__lowerCAmelCase , )
| 345 | 1 |
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 : List[Any] , _A : List[Any] , _A : Optional[int]=7 , _A : Optional[Any]=3 , _A : Tuple=18 , _A : List[Any]=30 , _A : Tuple=400 , _A : Tuple=True , _A : Any=None , _A : Optional[Any]=True , _A : Any=None , _A : Optional[int]=True , _A : Union[str, Any]=[0.48_145_466, 0.4_578_275, 0.40_821_073] , _A : List[Any]=[0.26_862_954, 0.26_130_258, 0.27_577_711] , _A : Optional[int]=True , ) -> Tuple:
"""simple docstring"""
lowercase : Any = size if size is not None else {'''height''': 224, '''width''': 224}
lowercase : Dict = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
lowercase : str = parent
lowercase : List[str] = batch_size
lowercase : List[Any] = num_channels
lowercase : Any = image_size
lowercase : Optional[Any] = min_resolution
lowercase : Optional[Any] = max_resolution
lowercase : List[str] = do_resize
lowercase : int = size
lowercase : Tuple = do_center_crop
lowercase : Optional[Any] = crop_size
lowercase : List[Any] = do_normalize
lowercase : List[str] = image_mean
lowercase : int = image_std
lowercase : str = do_convert_rgb
def __a ( self : Dict ) -> Optional[int]:
"""simple docstring"""
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_convert_rgb": self.do_convert_rgb,
}
def __a ( self : Dict , _A : Dict=False , _A : List[str]=False , _A : Union[str, Any]=False ) -> Any:
"""simple docstring"""
assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"
if equal_resolution:
lowercase : Optional[int] = []
for i in range(self.batch_size ):
image_inputs.append(
np.random.randint(
255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) )
else:
lowercase : int = []
for i in range(self.batch_size ):
lowercase , lowercase : str = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 )
image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) )
if not numpify and not torchify:
# PIL expects the channel dimension as last dimension
lowercase : Any = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs]
if torchify:
lowercase : List[Any] = [torch.from_numpy(_A ) for x in image_inputs]
return image_inputs
@require_torch
@require_vision
class _A ( _lowerCamelCase , unittest.TestCase ):
_UpperCamelCase : int = ChineseCLIPImageProcessor if is_vision_available() else None
def __a ( self : Optional[Any] ) -> Union[str, Any]:
"""simple docstring"""
lowercase : Tuple = ChineseCLIPImageProcessingTester(self , do_center_crop=_A )
@property
def __a ( self : Optional[int] ) -> List[Any]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def __a ( self : Union[str, Any] ) -> str:
"""simple docstring"""
lowercase : List[Any] = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_A , '''do_resize''' ) )
self.assertTrue(hasattr(_A , '''size''' ) )
self.assertTrue(hasattr(_A , '''do_center_crop''' ) )
self.assertTrue(hasattr(_A , '''center_crop''' ) )
self.assertTrue(hasattr(_A , '''do_normalize''' ) )
self.assertTrue(hasattr(_A , '''image_mean''' ) )
self.assertTrue(hasattr(_A , '''image_std''' ) )
self.assertTrue(hasattr(_A , '''do_convert_rgb''' ) )
def __a ( self : Union[str, Any] ) -> Dict:
"""simple docstring"""
lowercase : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''height''': 224, '''width''': 224} )
self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} )
lowercase : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 )
self.assertEqual(image_processor.size , {'''shortest_edge''': 42} )
self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} )
def __a ( self : Optional[Any] ) -> List[str]:
"""simple docstring"""
pass
def __a ( self : List[Any] ) -> List[Any]:
"""simple docstring"""
lowercase : Dict = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
lowercase : int = self.image_processor_tester.prepare_inputs(equal_resolution=_A )
for image in image_inputs:
self.assertIsInstance(_A , Image.Image )
# Test not batched input
lowercase : Optional[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
lowercase : Optional[int] = image_processing(_A , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def __a ( self : Union[str, Any] ) -> List[str]:
"""simple docstring"""
lowercase : str = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
lowercase : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=_A , numpify=_A )
for image in image_inputs:
self.assertIsInstance(_A , np.ndarray )
# Test not batched input
lowercase : 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
lowercase : Optional[int] = image_processing(_A , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def __a ( self : List[str] ) -> Optional[int]:
"""simple docstring"""
lowercase : int = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
lowercase : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=_A , torchify=_A )
for image in image_inputs:
self.assertIsInstance(_A , torch.Tensor )
# Test not batched input
lowercase : List[str] = 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
lowercase : List[str] = image_processing(_A , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
@require_torch
@require_vision
class _A ( _lowerCamelCase , unittest.TestCase ):
_UpperCamelCase : Dict = ChineseCLIPImageProcessor if is_vision_available() else None
def __a ( self : int ) -> Tuple:
"""simple docstring"""
lowercase : Tuple = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=_A )
lowercase : Optional[Any] = 3
@property
def __a ( self : Optional[int] ) -> int:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def __a ( self : str ) -> Tuple:
"""simple docstring"""
lowercase : str = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_A , '''do_resize''' ) )
self.assertTrue(hasattr(_A , '''size''' ) )
self.assertTrue(hasattr(_A , '''do_center_crop''' ) )
self.assertTrue(hasattr(_A , '''center_crop''' ) )
self.assertTrue(hasattr(_A , '''do_normalize''' ) )
self.assertTrue(hasattr(_A , '''image_mean''' ) )
self.assertTrue(hasattr(_A , '''image_std''' ) )
self.assertTrue(hasattr(_A , '''do_convert_rgb''' ) )
def __a ( self : Any ) -> int:
"""simple docstring"""
pass
def __a ( self : List[Any] ) -> Optional[int]:
"""simple docstring"""
lowercase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
lowercase : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=_A )
for image in image_inputs:
self.assertIsInstance(_A , Image.Image )
# Test not batched input
lowercase : str = 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
lowercase : Any = image_processing(_A , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.expected_encoded_image_num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , ) | 596 |
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets,
# U and V such that every edge (u, v) either connects a vertex from U to V or a vertex
# from V to U. In other words, for every edge (u, v), either u belongs to U and v to V,
# or u belongs to V and v to U. We can also say that there is no edge that connects
# vertices of same set.
def snake_case( __magic_name__ ) -> Any:
'''simple docstring'''
lowercase : Union[str, Any] = [False] * len(__magic_name__ )
lowercase : int = [-1] * len(__magic_name__ )
def dfs(__magic_name__ , __magic_name__ ):
lowercase : str = True
lowercase : Tuple = c
for u in graph[v]:
if not visited[u]:
dfs(__magic_name__ , 1 - c )
for i in range(len(__magic_name__ ) ):
if not visited[i]:
dfs(__magic_name__ , 0 )
for i in range(len(__magic_name__ ) ):
for j in graph[i]:
if color[i] == color[j]:
return False
return True
# Adjacency list of graph
lowerCAmelCase_ = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []}
print(check_bipartite_dfs(graph)) | 596 | 1 |
import gc
import tempfile
import unittest
import numpy as np
import torch
from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device
lowerCamelCase__ : Dict = False
class __magic_name__ (unittest.TestCase ):
'''simple docstring'''
pass
@nightly
@require_torch_gpu
class __magic_name__ (unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE__ ( self:str ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def SCREAMING_SNAKE_CASE__ ( self:Any ):
snake_case__ = VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion''' )
# remove text_unet
pipe.remove_unused_weights()
pipe.to(__UpperCAmelCase )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
snake_case__ = '''A painting of a squirrel eating a burger '''
snake_case__ = torch.manual_seed(0 )
snake_case__ = pipe(
prompt=__UpperCAmelCase , generator=__UpperCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images
with tempfile.TemporaryDirectory() as tmpdirname:
pipe.save_pretrained(__UpperCAmelCase )
snake_case__ = VersatileDiffusionTextToImagePipeline.from_pretrained(__UpperCAmelCase )
pipe.to(__UpperCAmelCase )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
snake_case__ = generator.manual_seed(0 )
snake_case__ = pipe(
prompt=__UpperCAmelCase , generator=__UpperCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images
assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass"
def SCREAMING_SNAKE_CASE__ ( self:List[str] ):
snake_case__ = VersatileDiffusionTextToImagePipeline.from_pretrained(
'''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa )
pipe.to(__UpperCAmelCase )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
snake_case__ = '''A painting of a squirrel eating a burger '''
snake_case__ = torch.manual_seed(0 )
snake_case__ = pipe(
prompt=__UpperCAmelCase , generator=__UpperCAmelCase , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images
snake_case__ = image[0, 2_53:2_56, 2_53:2_56, -1]
assert image.shape == (1, 5_12, 5_12, 3)
snake_case__ = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
| 33 |
from scipy.stats import pearsonr
import datasets
lowerCAmelCase_ = """
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.
"""
lowerCAmelCase_ = """
Args:
predictions (`list` of `int`): Predicted class labels, as returned by a model.
references (`list` of `int`): Ground truth labels.
return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.
Returns:
pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.
p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.
Examples:
Example 1-A simple example using only predictions and references.
>>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
>>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
>>> print(round(results['pearsonr'], 2))
-0.74
Example 2-The same as Example 1, but that also returns the `p-value`.
>>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
>>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
>>> print(sorted(list(results.keys())))
['p-value', 'pearsonr']
>>> print(round(results['pearsonr'], 2))
-0.74
>>> print(round(results['p-value'], 2))
0.15
"""
lowerCAmelCase_ = """
@article{2020SciPy-NMeth,
author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
Haberland, Matt and Reddy, Tyler and Cournapeau, David and
Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
Kern, Robert and Larson, Eric and Carey, C J and
Polat, Ilhan and Feng, Yu and Moore, Eric W. and
{VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
Harris, Charles R. and Archibald, Anne M. and
Ribeiro, Antonio H. and Pedregosa, Fabian and
{van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
Computing in Python}},
journal = {Nature Methods},
year = {2020},
volume = {17},
pages = {261--272},
adsurl = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class _lowerCAmelCase ( datasets.Metric ):
def __magic_name__( self ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Value('''float''' ),
'''references''': datasets.Value('''float''' ),
} ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , )
def __magic_name__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=False ):
if return_pvalue:
lowerCAmelCase__ : Union[str, Any] = pearsonr(__UpperCAmelCase , __UpperCAmelCase )
return {"pearsonr": results[0], "p-value": results[1]}
else:
return {"pearsonr": float(pearsonr(__UpperCAmelCase , __UpperCAmelCase )[0] )}
| 678 | 0 |
'''simple docstring'''
from typing import List, Optional, Tuple, Union
import PIL
import torch
from torchvision import transforms
from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
from diffusers.schedulers import DDIMScheduler
from diffusers.utils import randn_tensor
__magic_name__ : Optional[int] = transforms.Compose(
[
transforms.Resize((256, 256)),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5]),
]
)
def A__ ( A_ ) -> List[str]:
if isinstance(A_ , torch.Tensor ):
return image
elif isinstance(A_ , PIL.Image.Image ):
_lowercase = [image]
_lowercase = [trans(img.convert("RGB" ) ) for img in image]
_lowercase = torch.stack(A_ )
return image
class UpperCamelCase__ ( lowerCamelCase__ ):
"""simple docstring"""
def __init__( self : List[str] , __A : List[str] , __A : int ):
"""simple docstring"""
super().__init__()
# make sure scheduler can always be converted to DDIM
_lowercase = DDIMScheduler.from_config(scheduler.config )
self.register_modules(unet=__A , scheduler=__A )
def snake_case ( self : Any , __A : List[str] ):
"""simple docstring"""
if strength < 0 or strength > 1:
raise ValueError(f"""The value of strength should in [0.0, 1.0] but is {strength}""" )
def snake_case ( self : Dict , __A : int , __A : Union[str, Any] , __A : Union[str, Any] ):
"""simple docstring"""
# get the original timestep using init_timestep
_lowercase = min(int(num_inference_steps * strength ) , __A )
_lowercase = max(num_inference_steps - init_timestep , 0 )
_lowercase = self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def snake_case ( self : str , __A : Union[str, Any] , __A : Optional[int] , __A : List[Any] , __A : Tuple , __A : Any , __A : Optional[Any]=None ):
"""simple docstring"""
if not isinstance(__A , (torch.Tensor, PIL.Image.Image, list) ):
raise ValueError(
f"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(__A )}""" )
_lowercase = image.to(device=__A , dtype=__A )
if isinstance(__A , __A ) and len(__A ) != batch_size:
raise ValueError(
f"""You have passed a list of generators of length {len(__A )}, but requested an effective batch"""
f""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" )
_lowercase = init_latents.shape
_lowercase = randn_tensor(__A , generator=__A , device=__A , dtype=__A )
# get latents
print("add noise to latents at timestep" , __A )
_lowercase = self.scheduler.add_noise(__A , __A , __A )
_lowercase = init_latents
return latents
@torch.no_grad()
def __call__( self : int , __A : Union[torch.FloatTensor, PIL.Image.Image] = None , __A : float = 0.8 , __A : int = 1 , __A : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A : float = 0.0 , __A : int = 5_0 , __A : Optional[bool] = None , __A : Optional[str] = "pil" , __A : bool = True , ):
"""simple docstring"""
self.check_inputs(__A )
# 2. Preprocess image
_lowercase = preprocess(__A )
# 3. set timesteps
self.scheduler.set_timesteps(__A , device=self.device )
_lowercase , _lowercase = self.get_timesteps(__A , __A , self.device )
_lowercase = timesteps[:1].repeat(__A )
# 4. Prepare latent variables
_lowercase = self.prepare_latents(__A , __A , __A , self.unet.dtype , self.device , __A )
_lowercase = latents
# 5. Denoising loop
for t in self.progress_bar(__A ):
# 1. predict noise model_output
_lowercase = self.unet(__A , __A ).sample
# 2. predict previous mean of image x_t-1 and add variance depending on eta
# eta corresponds to η in paper and should be between [0, 1]
# do x_t -> x_t-1
_lowercase = self.scheduler.step(
__A , __A , __A , eta=__A , use_clipped_model_output=__A , generator=__A , ).prev_sample
_lowercase = (image / 2 + 0.5).clamp(0 , 1 )
_lowercase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
_lowercase = self.numpy_to_pil(__A )
if not return_dict:
return (image, latent_timestep.item())
return ImagePipelineOutput(images=__A )
| 602 |
'''simple docstring'''
import argparse
import json
import re
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
MobileNetVaConfig,
MobileNetVaForImageClassification,
MobileNetVaImageProcessor,
load_tf_weights_in_mobilenet_va,
)
from transformers.utils import logging
logging.set_verbosity_info()
__magic_name__ : List[Any] = logging.get_logger(__name__)
def A__ ( A_ ) -> List[str]:
_lowercase = MobileNetVaConfig(layer_norm_eps=0.001 )
if "_quant" in model_name:
raise ValueError("Quantized models are not supported." )
_lowercase = re.match(R"^mobilenet_v1_([^_]*)_([^_]*)$" , A_ )
if matches:
_lowercase = float(matches[1] )
_lowercase = int(matches[2] )
# The TensorFlow version of MobileNetV1 predicts 1001 classes instead of
# the usual 1000. The first class (index 0) is "background".
_lowercase = 1_001
_lowercase = "imagenet-1k-id2label.json"
_lowercase = "huggingface/label-files"
_lowercase = json.load(open(hf_hub_download(A_ , A_ , repo_type="dataset" ) , "r" ) )
_lowercase = {int(A_ ) + 1: v for k, v in idalabel.items()}
_lowercase = "background"
_lowercase = idalabel
_lowercase = {v: k for k, v in idalabel.items()}
return config
def A__ ( ) -> str:
_lowercase = "http://images.cocodataset.org/val2017/000000039769.jpg"
_lowercase = Image.open(requests.get(A_ , stream=A_ ).raw )
return im
@torch.no_grad()
def A__ ( A_ , A_ , A_ , A_=False ) -> List[Any]:
_lowercase = get_mobilenet_va_config(A_ )
# Load 🤗 model
_lowercase = MobileNetVaForImageClassification(A_ ).eval()
# Load weights from TensorFlow checkpoint
load_tf_weights_in_mobilenet_va(A_ , A_ , A_ )
# Check outputs on an image, prepared by MobileNetV1ImageProcessor
_lowercase = MobileNetVaImageProcessor(
crop_size={"width": config.image_size, "height": config.image_size} , size={"shortest_edge": config.image_size + 32} , )
_lowercase = image_processor(images=prepare_img() , return_tensors="pt" )
_lowercase = model(**A_ )
_lowercase = outputs.logits
assert logits.shape == (1, 1_001)
if model_name == "mobilenet_v1_1.0_224":
_lowercase = torch.tensor([-4.1739, -1.1233, 3.1205] )
elif model_name == "mobilenet_v1_0.75_192":
_lowercase = torch.tensor([-3.9440, -2.3141, -0.3333] )
else:
_lowercase = None
if expected_logits is not None:
assert torch.allclose(logits[0, :3] , A_ , atol=1e-4 )
Path(A_ ).mkdir(exist_ok=A_ )
print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" )
model.save_pretrained(A_ )
print(F"""Saving image processor to {pytorch_dump_folder_path}""" )
image_processor.save_pretrained(A_ )
if push_to_hub:
print("Pushing to the hub..." )
_lowercase = "google/" + model_name
image_processor.push_to_hub(A_ )
model.push_to_hub(A_ )
if __name__ == "__main__":
__magic_name__ : Dict = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--model_name''',
default='''mobilenet_v1_1.0_224''',
type=str,
help='''Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.''',
)
parser.add_argument(
'''--checkpoint_path''', required=True, type=str, help='''Path to the original TensorFlow checkpoint (.ckpt file).'''
)
parser.add_argument(
'''--pytorch_dump_folder_path''', required=True, type=str, help='''Path to the output PyTorch model directory.'''
)
parser.add_argument(
'''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
)
__magic_name__ : Union[str, Any] = parser.parse_args()
convert_movilevit_checkpoint(
args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub
)
| 602 | 1 |
"""simple docstring"""
from operator import delitem, getitem, setitem
import pytest
from data_structures.hashing.hash_map import HashMap
def UpperCamelCase (SCREAMING_SNAKE_CASE ):
return getitem, k
def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
return setitem, k, v
def UpperCamelCase (SCREAMING_SNAKE_CASE ):
return delitem, k
def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE ):
try:
return fun(_lowerCamelCase , *_lowerCamelCase ), None
except Exception as e:
return None, e
__magic_name__ : List[str] = (
_set("""key_a""", """val_a"""),
_set("""key_b""", """val_b"""),
)
__magic_name__ : Optional[Any] = [
_set("""key_a""", """val_a"""),
_set("""key_a""", """val_b"""),
]
__magic_name__ : Optional[int] = [
_set("""key_a""", """val_a"""),
_set("""key_b""", """val_b"""),
_del("""key_a"""),
_del("""key_b"""),
_set("""key_a""", """val_a"""),
_del("""key_a"""),
]
__magic_name__ : Dict = [
_get("""key_a"""),
_del("""key_a"""),
_set("""key_a""", """val_a"""),
_del("""key_a"""),
_del("""key_a"""),
_get("""key_a"""),
]
__magic_name__ : int = [
*[_set(x, x) for x in range(5)], # guaranteed upsize
]
__magic_name__ : Any = [
*[_set(x, x) for x in range(5)], # guaranteed upsize
*[_del(x) for x in range(5)],
_set("""key_a""", """val_b"""),
]
@pytest.mark.parametrize(
"""operations""" , (
pytest.param(_add_items , id="""add items""" ),
pytest.param(_overwrite_items , id="""overwrite items""" ),
pytest.param(_delete_items , id="""delete items""" ),
pytest.param(_access_absent_items , id="""access absent items""" ),
pytest.param(_add_with_resize_up , id="""add with resize up""" ),
pytest.param(_add_with_resize_down , id="""add with resize down""" ),
) , )
def UpperCamelCase (SCREAMING_SNAKE_CASE ):
UpperCamelCase : Any = HashMap(initial_block_size=4 )
UpperCamelCase : Any = {}
for _, (fun, *args) in enumerate(_lowerCamelCase ):
UpperCamelCase , UpperCamelCase : Any = _run_operation(_lowerCamelCase , _lowerCamelCase , *_lowerCamelCase )
UpperCamelCase , UpperCamelCase : List[Any] = _run_operation(_lowerCamelCase , _lowerCamelCase , *_lowerCamelCase )
assert my_res == py_res
assert str(_lowerCamelCase ) == str(_lowerCamelCase )
assert set(_lowerCamelCase ) == set(_lowerCamelCase )
assert len(_lowerCamelCase ) == len(_lowerCamelCase )
assert set(my.items() ) == set(py.items() )
def UpperCamelCase ():
def is_public(SCREAMING_SNAKE_CASE ) -> bool:
return not name.startswith("""_""" )
UpperCamelCase : Union[str, Any] = {name for name in dir({} ) if is_public(_lowerCamelCase )}
UpperCamelCase : Union[str, Any] = {name for name in dir(HashMap() ) if is_public(_lowerCamelCase )}
assert dict_public_names > hash_public_names
| 102 |
"""simple docstring"""
import unittest
from transformers import is_tf_available
from transformers.testing_utils import require_tf
if is_tf_available():
import tensorflow as tf
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from transformers import GradientAccumulator, create_optimizer
@require_tf
class a ( unittest.TestCase ):
def UpperCamelCase ( self : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Dict ) -> str:
self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) )
for a, b in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
self.assertAlmostEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , delta=__SCREAMING_SNAKE_CASE )
def UpperCamelCase ( self : List[Any] ) -> int:
lowerCamelCase_ = GradientAccumulator()
accumulator([tf.constant([1.0, 2.0] )] )
accumulator([tf.constant([-2.0, 1.0] )] )
accumulator([tf.constant([-1.0, 2.0] )] )
with self.assertRaises(__SCREAMING_SNAKE_CASE ):
accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] )
self.assertEqual(accumulator.step , 3 )
self.assertEqual(len(accumulator.gradients ) , 1 )
self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1e-2 )
accumulator.reset()
self.assertEqual(accumulator.step , 0 )
self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1e-2 )
def UpperCamelCase ( self : str ) -> Any:
lowerCamelCase_ = None
ops.enable_eager_execution_internal()
lowerCamelCase_ = tf.config.list_physical_devices('CPU' )
if len(__SCREAMING_SNAKE_CASE ) == 1:
tf.config.set_logical_device_configuration(
physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] )
lowerCamelCase_ = tf.config.list_logical_devices(device_type='CPU' )
lowerCamelCase_ = tf.distribute.MirroredStrategy(devices=devices[:2] )
with strategy.scope():
lowerCamelCase_ = GradientAccumulator()
lowerCamelCase_ = tf.Variable([4.0, 3.0] )
lowerCamelCase_ , lowerCamelCase_ = create_optimizer(5e-5 , 10 , 5 )
lowerCamelCase_ = tf.Variable([0.0, 0.0] , trainable=__SCREAMING_SNAKE_CASE )
def accumulate_on_replica(__SCREAMING_SNAKE_CASE : Union[str, Any] ):
accumulator([gradient] )
def apply_on_replica():
optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) )
@tf.function
def accumulate(__SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Any ):
with strategy.scope():
lowerCamelCase_ = strategy.experimental_local_results(__SCREAMING_SNAKE_CASE )
local_variables[0].assign(__SCREAMING_SNAKE_CASE )
local_variables[1].assign(__SCREAMING_SNAKE_CASE )
strategy.run(__SCREAMING_SNAKE_CASE , args=(gradient_placeholder,) )
@tf.function
def apply_grad():
with strategy.scope():
strategy.run(__SCREAMING_SNAKE_CASE )
def _check_local_values(__SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[str] ):
lowerCamelCase_ = strategy.experimental_local_results(accumulator._gradients[0] )
self.assertListAlmostEqual(values[0].value() , __SCREAMING_SNAKE_CASE , tol=1e-2 )
self.assertListAlmostEqual(values[1].value() , __SCREAMING_SNAKE_CASE , tol=1e-2 )
accumulate([1.0, 2.0] , [-1.0, 1.0] )
accumulate([3.0, -1.0] , [-1.0, -1.0] )
accumulate([-2.0, 2.0] , [3.0, -2.0] )
self.assertEqual(accumulator.step , 3 )
_check_local_values([2.0, 3.0] , [1.0, -2.0] )
apply_grad()
self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1e-2 )
accumulator.reset()
self.assertEqual(accumulator.step , 0 )
_check_local_values([0.0, 0.0] , [0.0, 0.0] )
| 549 | 0 |
'''simple docstring'''
def __lowercase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = " " ) -> list:
"""simple docstring"""
__a = []
__a = 0
for index, char in enumerate(__SCREAMING_SNAKE_CASE ):
if char == separator:
split_words.append(string[last_index:index] )
__a = index + 1
elif index + 1 == len(__SCREAMING_SNAKE_CASE ):
split_words.append(string[last_index : index + 1] )
return split_words
if __name__ == "__main__":
from doctest import testmod
testmod()
| 201 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
SCREAMING_SNAKE_CASE_ = {
'configuration_rag': ['RagConfig'],
'retrieval_rag': ['RagRetriever'],
'tokenization_rag': ['RagTokenizer'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = [
'RagModel',
'RagPreTrainedModel',
'RagSequenceForGeneration',
'RagTokenForGeneration',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = [
'TFRagModel',
'TFRagPreTrainedModel',
'TFRagSequenceForGeneration',
'TFRagTokenForGeneration',
]
if TYPE_CHECKING:
from .configuration_rag import RagConfig
from .retrieval_rag import RagRetriever
from .tokenization_rag import RagTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_rag import (
TFRagModel,
TFRagPreTrainedModel,
TFRagSequenceForGeneration,
TFRagTokenForGeneration,
)
else:
import sys
SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 201 | 1 |
"""simple docstring"""
from typing import Any
class __a :
def __init__( self , a__ ):
_lowerCamelCase = data
_lowerCamelCase = None
def __repr__( self ):
return F'Node({self.data})'
class __a :
def __init__( self ):
_lowerCamelCase = None
def __iter__( self ):
_lowerCamelCase = self.head
while node:
yield node.data
_lowerCamelCase = node.next
def __len__( self ):
return sum(1 for _ in self )
def __repr__( self ):
return "->".join([str(a__ ) for item in self] )
def __getitem__( self , a__ ):
if not 0 <= index < len(self ):
raise ValueError('list index out of range.' )
for i, node in enumerate(self ):
if i == index:
return node
return None
def __setitem__( self , a__ , a__ ):
if not 0 <= index < len(self ):
raise ValueError('list index out of range.' )
_lowerCamelCase = self.head
for _ in range(a__ ):
_lowerCamelCase = current.next
_lowerCamelCase = data
def snake_case_ ( self , a__ ):
self.insert_nth(len(self ) , a__ )
def snake_case_ ( self , a__ ):
self.insert_nth(0 , a__ )
def snake_case_ ( self , a__ , a__ ):
if not 0 <= index <= len(self ):
raise IndexError('list index out of range' )
_lowerCamelCase = Node(a__ )
if self.head is None:
_lowerCamelCase = new_node
elif index == 0:
_lowerCamelCase = self.head # link new_node to head
_lowerCamelCase = new_node
else:
_lowerCamelCase = self.head
for _ in range(index - 1 ):
_lowerCamelCase = temp.next
_lowerCamelCase = temp.next
_lowerCamelCase = new_node
def snake_case_ ( self ): # print every node data
print(self )
def snake_case_ ( self ):
return self.delete_nth(0 )
def snake_case_ ( self ): # delete from tail
return self.delete_nth(len(self ) - 1 )
def snake_case_ ( self , a__ = 0 ):
if not 0 <= index <= len(self ) - 1: # test if index is valid
raise IndexError('List index out of range.' )
_lowerCamelCase = self.head # default first node
if index == 0:
_lowerCamelCase = self.head.next
else:
_lowerCamelCase = self.head
for _ in range(index - 1 ):
_lowerCamelCase = temp.next
_lowerCamelCase = temp.next
_lowerCamelCase = temp.next.next
return delete_node.data
def snake_case_ ( self ):
return self.head is None
def snake_case_ ( self ):
_lowerCamelCase = None
_lowerCamelCase = self.head
while current:
# Store the current node's next node.
_lowerCamelCase = current.next
# Make the current node's next point backwards
_lowerCamelCase = prev
# Make the previous node be the current node
_lowerCamelCase = current
# Make the current node the next node (to progress iteration)
_lowerCamelCase = next_node
# Return prev in order to put the head at the end
_lowerCamelCase = prev
def SCREAMING_SNAKE_CASE_ ( )-> None:
_lowerCamelCase = LinkedList()
assert linked_list.is_empty() is True
assert str(snake_case ) == ""
try:
linked_list.delete_head()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
try:
linked_list.delete_tail()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
for i in range(10 ):
assert len(snake_case ) == i
linked_list.insert_nth(snake_case , i + 1 )
assert str(snake_case ) == "->".join(str(snake_case ) for i in range(1 , 11 ) )
linked_list.insert_head(0 )
linked_list.insert_tail(11 )
assert str(snake_case ) == "->".join(str(snake_case ) for i in range(0 , 12 ) )
assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9 ) == 10
assert linked_list.delete_tail() == 11
assert len(snake_case ) == 9
assert str(snake_case ) == "->".join(str(snake_case ) for i in range(1 , 10 ) )
assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True
for i in range(0 , 9 ):
_lowerCamelCase = -i
assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True
linked_list.reverse()
assert str(snake_case ) == "->".join(str(snake_case ) for i in range(-8 , 1 ) )
def SCREAMING_SNAKE_CASE_ ( )-> None:
_lowerCamelCase = [
-9,
100,
Node(77_345_112 ),
'dlrow olleH',
7,
5_555,
0,
-1_9_2.5_5_5_5_5,
'Hello, world!',
7_7.9,
Node(10 ),
None,
None,
1_2.2_0,
]
_lowerCamelCase = LinkedList()
for i in test_input:
linked_list.insert_tail(snake_case )
# Check if it's empty or not
assert linked_list.is_empty() is False
assert (
str(snake_case ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->"
"-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the head
_lowerCamelCase = linked_list.delete_head()
assert result == -9
assert (
str(snake_case ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the tail
_lowerCamelCase = linked_list.delete_tail()
assert result == 1_2.2
assert (
str(snake_case ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None"
)
# Delete a node in specific location in linked list
_lowerCamelCase = linked_list.delete_nth(10 )
assert result is None
assert (
str(snake_case ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None"
)
# Add a Node instance to its head
linked_list.insert_head(Node('Hello again, world!' ) )
assert (
str(snake_case )
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None"
)
# Add None to its tail
linked_list.insert_tail(snake_case )
assert (
str(snake_case )
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None"
)
# Reverse the linked list
linked_list.reverse()
assert (
str(snake_case )
== "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->"
"7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)"
)
def SCREAMING_SNAKE_CASE_ ( )-> Any:
from doctest import testmod
testmod()
_lowerCamelCase = LinkedList()
linked_list.insert_head(input('Inserting 1st at head ' ).strip() )
linked_list.insert_head(input('Inserting 2nd at head ' ).strip() )
print('\nPrint list:' )
linked_list.print_list()
linked_list.insert_tail(input('\nInserting 1st at tail ' ).strip() )
linked_list.insert_tail(input('Inserting 2nd at tail ' ).strip() )
print('\nPrint list:' )
linked_list.print_list()
print('\nDelete head' )
linked_list.delete_head()
print('Delete tail' )
linked_list.delete_tail()
print('\nPrint list:' )
linked_list.print_list()
print('\nReverse linked list' )
linked_list.reverse()
print('\nPrint list:' )
linked_list.print_list()
print('\nString representation of linked list:' )
print(snake_case )
print('\nReading/changing Node data using indexing:' )
print(f'Element at Position 1: {linked_list[1]}' )
_lowerCamelCase = input('Enter New Value: ' ).strip()
print('New list:' )
print(snake_case )
print(f'length of linked_list is : {len(snake_case )}' )
if __name__ == "__main__":
main()
| 650 |
"""simple docstring"""
from __future__ import annotations
from fractions import Fraction
def SCREAMING_SNAKE_CASE_ ( snake_case : int , snake_case : int )-> bool:
return (
num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den
)
def SCREAMING_SNAKE_CASE_ ( snake_case : int )-> list[str]:
_lowerCamelCase = []
_lowerCamelCase = 11
_lowerCamelCase = int('1' + '0' * digit_len )
for num in range(snake_case , snake_case ):
while den <= 99:
if (num != den) and (num % 10 == den // 10) and (den % 10 != 0):
if is_digit_cancelling(snake_case , snake_case ):
solutions.append(f'{num}/{den}' )
den += 1
num += 1
_lowerCamelCase = 10
return solutions
def SCREAMING_SNAKE_CASE_ ( snake_case : int = 2 )-> int:
_lowerCamelCase = 1.0
for fraction in fraction_list(snake_case ):
_lowerCamelCase = Fraction(snake_case )
result *= frac.denominator / frac.numerator
return int(snake_case )
if __name__ == "__main__":
print(solution())
| 650 | 1 |
import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to properly calculate the metrics on the
# validation dataset when in a distributed system, and builds off the
# `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
# - single CPU or single GPU
# - multi GPUS (using PyTorch distributed mode)
# - (multi) TPUs
# - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################
lowercase = 1_6
lowercase = 3_2
def lowerCamelCase_ ( UpperCamelCase__ : Accelerator, UpperCamelCase__ : int = 16 ):
'''simple docstring'''
UpperCamelCase__ = AutoTokenizer.from_pretrained('''bert-base-cased''' )
UpperCamelCase__ = load_dataset('''glue''', '''mrpc''' )
def tokenize_function(UpperCamelCase__ : Dict ):
# max_length=None => use the model max length (it's actually the default)
UpperCamelCase__ = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=UpperCamelCase__, max_length=UpperCamelCase__ )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
UpperCamelCase__ = datasets.map(
UpperCamelCase__, batched=UpperCamelCase__, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
UpperCamelCase__ = tokenized_datasets.rename_column('''label''', '''labels''' )
def collate_fn(UpperCamelCase__ : Dict ):
# On TPU it's best to pad everything to the same length or training will be very slow.
UpperCamelCase__ = 128 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
UpperCamelCase__ = 16
elif accelerator.mixed_precision != "no":
UpperCamelCase__ = 8
else:
UpperCamelCase__ = None
return tokenizer.pad(
UpperCamelCase__, padding='''longest''', max_length=UpperCamelCase__, pad_to_multiple_of=UpperCamelCase__, return_tensors='''pt''', )
# Instantiate dataloaders.
UpperCamelCase__ = DataLoader(
tokenized_datasets['''train'''], shuffle=UpperCamelCase__, collate_fn=UpperCamelCase__, batch_size=UpperCamelCase__ )
UpperCamelCase__ = DataLoader(
tokenized_datasets['''validation'''], shuffle=UpperCamelCase__, collate_fn=UpperCamelCase__, batch_size=UpperCamelCase__ )
return train_dataloader, eval_dataloader
# For testing only
if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
lowercase = mocked_dataloaders # noqa: F811
def lowerCamelCase_ ( UpperCamelCase__ : Optional[Any], UpperCamelCase__ : str ):
'''simple docstring'''
if os.environ.get('''TESTING_MOCKED_DATALOADERS''', UpperCamelCase__ ) == "1":
UpperCamelCase__ = 2
# Initialize accelerator
UpperCamelCase__ = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
UpperCamelCase__ = config['''lr''']
UpperCamelCase__ = int(config['''num_epochs'''] )
UpperCamelCase__ = int(config['''seed'''] )
UpperCamelCase__ = int(config['''batch_size'''] )
UpperCamelCase__ = evaluate.load('''glue''', '''mrpc''' )
# If the batch size is too big we use gradient accumulation
UpperCamelCase__ = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
UpperCamelCase__ = batch_size // MAX_GPU_BATCH_SIZE
UpperCamelCase__ = MAX_GPU_BATCH_SIZE
set_seed(UpperCamelCase__ )
UpperCamelCase__ , UpperCamelCase__ = get_dataloaders(UpperCamelCase__, UpperCamelCase__ )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
UpperCamelCase__ = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''', return_dict=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).
UpperCamelCase__ = model.to(accelerator.device )
# Instantiate optimizer
UpperCamelCase__ = AdamW(params=model.parameters(), lr=UpperCamelCase__ )
# Instantiate scheduler
UpperCamelCase__ = get_linear_schedule_with_warmup(
optimizer=UpperCamelCase__, num_warmup_steps=100, num_training_steps=(len(UpperCamelCase__ ) * num_epochs) // gradient_accumulation_steps, )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = accelerator.prepare(
UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ )
# Now we train the model
for epoch in range(UpperCamelCase__ ):
model.train()
for step, batch in enumerate(UpperCamelCase__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
UpperCamelCase__ = model(**UpperCamelCase__ )
UpperCamelCase__ = outputs.loss
UpperCamelCase__ = loss / gradient_accumulation_steps
accelerator.backward(UpperCamelCase__ )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
UpperCamelCase__ = 0
for step, batch in enumerate(UpperCamelCase__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
UpperCamelCase__ = model(**UpperCamelCase__ )
UpperCamelCase__ = outputs.logits.argmax(dim=-1 )
UpperCamelCase__ , UpperCamelCase__ = accelerator.gather((predictions, batch['''labels''']) )
# New Code #
# First we check if it's a distributed system
if accelerator.use_distributed:
# Then see if we're on the last batch of our eval dataloader
if step == len(UpperCamelCase__ ) - 1:
# Last batch needs to be truncated on distributed systems as it contains additional samples
UpperCamelCase__ = predictions[: len(eval_dataloader.dataset ) - samples_seen]
UpperCamelCase__ = references[: len(eval_dataloader.dataset ) - samples_seen]
else:
# Otherwise we add the number of samples seen
samples_seen += references.shape[0]
# All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`:
# accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=UpperCamelCase__, references=UpperCamelCase__, )
UpperCamelCase__ = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(F"""epoch {epoch}:""", UpperCamelCase__ )
def lowerCamelCase_ ( ):
'''simple docstring'''
UpperCamelCase__ = argparse.ArgumentParser(description='''Simple example of training script.''' )
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.''' )
UpperCamelCase__ = parser.parse_args()
UpperCamelCase__ = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
training_function(UpperCamelCase__, UpperCamelCase__ )
if __name__ == "__main__":
main()
| 591 | import argparse
import fairseq
import torch
from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging
logging.set_verbosity_info()
lowercase = logging.get_logger(__name__)
lowercase = {
"""post_extract_proj""": """feature_projection.projection""",
"""encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""",
"""self_attn.k_proj""": """encoder.layers.*.attention.k_proj""",
"""self_attn.v_proj""": """encoder.layers.*.attention.v_proj""",
"""self_attn.q_proj""": """encoder.layers.*.attention.q_proj""",
"""self_attn.out_proj""": """encoder.layers.*.attention.out_proj""",
"""self_attn_layer_norm""": """encoder.layers.*.layer_norm""",
"""fc1""": """encoder.layers.*.feed_forward.intermediate_dense""",
"""fc2""": """encoder.layers.*.feed_forward.output_dense""",
"""final_layer_norm""": """encoder.layers.*.final_layer_norm""",
"""encoder.layer_norm""": """encoder.layer_norm""",
"""encoder.layer_norm_for_extract""": """layer_norm_for_extract""",
"""w2v_model.layer_norm""": """feature_projection.layer_norm""",
"""quantizer.weight_proj""": """quantizer.weight_proj""",
"""quantizer.vars""": """quantizer.codevectors""",
"""project_q""": """project_q""",
"""final_proj""": """project_hid""",
"""w2v_encoder.proj""": """lm_head""",
"""label_embs_concat""": """label_embeddings_concat""",
"""mask_emb""": """masked_spec_embed""",
"""spk_proj""": """speaker_proj""",
}
lowercase = [
"""lm_head""",
"""quantizer.weight_proj""",
"""quantizer.codevectors""",
"""project_q""",
"""project_hid""",
"""label_embeddings_concat""",
"""speaker_proj""",
"""layer_norm_for_extract""",
]
def lowerCamelCase_ ( UpperCamelCase__ : int, UpperCamelCase__ : str, UpperCamelCase__ : List[str], UpperCamelCase__ : Optional[Any], UpperCamelCase__ : List[str] ):
'''simple docstring'''
for attribute in key.split('''.''' ):
UpperCamelCase__ = getattr(UpperCamelCase__, UpperCamelCase__ )
if weight_type is not None:
UpperCamelCase__ = getattr(UpperCamelCase__, UpperCamelCase__ ).shape
else:
UpperCamelCase__ = 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":
UpperCamelCase__ = value
elif weight_type == "weight_g":
UpperCamelCase__ = value
elif weight_type == "weight_v":
UpperCamelCase__ = value
elif weight_type == "bias":
UpperCamelCase__ = value
else:
UpperCamelCase__ = value
logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" )
def lowerCamelCase_ ( UpperCamelCase__ : List[str], UpperCamelCase__ : List[str] ):
'''simple docstring'''
UpperCamelCase__ = []
UpperCamelCase__ = fairseq_model.state_dict()
UpperCamelCase__ = hf_model.unispeech_sat.feature_extractor
for name, value in fairseq_dict.items():
UpperCamelCase__ = False
if "conv_layers" in name:
load_conv_layer(
UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, hf_model.config.feat_extract_norm == '''group''', )
UpperCamelCase__ = True
else:
for key, mapped_key in MAPPING.items():
UpperCamelCase__ = '''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]:
if "layer_norm_for_extract" in name and (".".join(name.split('''.''' )[:-1] ) != key):
# special case since naming is very similar
continue
UpperCamelCase__ = True
if "*" in mapped_key:
UpperCamelCase__ = name.split(UpperCamelCase__ )[0].split('''.''' )[-2]
UpperCamelCase__ = mapped_key.replace('''*''', UpperCamelCase__ )
if "weight_g" in name:
UpperCamelCase__ = '''weight_g'''
elif "weight_v" in name:
UpperCamelCase__ = '''weight_v'''
elif "bias" in name:
UpperCamelCase__ = '''bias'''
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
UpperCamelCase__ = '''weight'''
else:
UpperCamelCase__ = None
set_recursively(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ )
continue
if not is_used:
unused_weights.append(UpperCamelCase__ )
logger.warning(F"""Unused weights: {unused_weights}""" )
def lowerCamelCase_ ( UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : List[Any], UpperCamelCase__ : Optional[int], UpperCamelCase__ : Optional[Any] ):
'''simple docstring'''
UpperCamelCase__ = full_name.split('''conv_layers.''' )[-1]
UpperCamelCase__ = name.split('''.''' )
UpperCamelCase__ = int(items[0] )
UpperCamelCase__ = 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.""" )
UpperCamelCase__ = 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.""" )
UpperCamelCase__ = value
logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
raise ValueError(
F"""{full_name} has size {value.shape}, but"""
F""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""" )
UpperCamelCase__ = value
logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
raise ValueError(
F"""{full_name} has size {value.shape}, but"""
F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" )
UpperCamelCase__ = value
logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
else:
unused_weights.append(UpperCamelCase__ )
@torch.no_grad()
def lowerCamelCase_ ( UpperCamelCase__ : int, UpperCamelCase__ : Dict, UpperCamelCase__ : Union[str, Any]=None, UpperCamelCase__ : List[str]=None, UpperCamelCase__ : List[Any]=True ):
'''simple docstring'''
if config_path is not None:
UpperCamelCase__ = UniSpeechSatConfig.from_pretrained(UpperCamelCase__ )
else:
UpperCamelCase__ = UniSpeechSatConfig()
UpperCamelCase__ = ''''''
if is_finetuned:
UpperCamelCase__ = UniSpeechSatForCTC(UpperCamelCase__ )
else:
UpperCamelCase__ = UniSpeechSatForPreTraining(UpperCamelCase__ )
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path], arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} )
UpperCamelCase__ = model[0].eval()
recursively_load_weights(UpperCamelCase__, UpperCamelCase__ )
hf_wavavec.save_pretrained(UpperCamelCase__ )
if __name__ == "__main__":
lowercase = argparse.ArgumentParser()
parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""")
parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""")
parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
parser.add_argument(
"""--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not"""
)
lowercase = parser.parse_args()
convert_unispeech_sat_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
)
| 591 | 1 |
from __future__ import annotations
from decimal import Decimal
from numpy import array
def __a ( __UpperCAmelCase : list[list[float]] ) -> list[list[float]]:
"""simple docstring"""
lowerCamelCase_ : List[str] = Decimal
# Check if the provided matrix has 2 rows and 2 columns
# since this implementation only works for 2x2 matrices
if len(__UpperCAmelCase ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2:
# Calculate the determinant of the matrix
lowerCamelCase_ : str = float(
d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) )
if determinant == 0:
raise ValueError("This matrix has no inverse." )
# Creates a copy of the matrix with swapped positions of the elements
lowerCamelCase_ : Dict = [[0.0, 0.0], [0.0, 0.0]]
lowerCamelCase_ , lowerCamelCase_ : Optional[int] = matrix[1][1], matrix[0][0]
lowerCamelCase_ , lowerCamelCase_ : Dict = -matrix[1][0], -matrix[0][1]
# Calculate the inverse of the matrix
return [
[(float(d(__UpperCAmelCase ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix
]
elif (
len(__UpperCAmelCase ) == 3
and len(matrix[0] ) == 3
and len(matrix[1] ) == 3
and len(matrix[2] ) == 3
):
# Calculate the determinant of the matrix using Sarrus rule
lowerCamelCase_ : Dict = float(
(
(d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] ))
+ (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] ))
+ (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] ))
)
- (
(d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] ))
+ (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] ))
+ (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] ))
) )
if determinant == 0:
raise ValueError("This matrix has no inverse." )
# Creating cofactor matrix
lowerCamelCase_ : str = [
[d(0.0 ), d(0.0 ), d(0.0 )],
[d(0.0 ), d(0.0 ), d(0.0 )],
[d(0.0 ), d(0.0 ), d(0.0 )],
]
lowerCamelCase_ : Optional[Any] = (d(matrix[1][1] ) * d(matrix[2][2] )) - (
d(matrix[1][2] ) * d(matrix[2][1] )
)
lowerCamelCase_ : List[str] = -(
(d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] ))
)
lowerCamelCase_ : Dict = (d(matrix[1][0] ) * d(matrix[2][1] )) - (
d(matrix[1][1] ) * d(matrix[2][0] )
)
lowerCamelCase_ : Dict = -(
(d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] ))
)
lowerCamelCase_ : List[Any] = (d(matrix[0][0] ) * d(matrix[2][2] )) - (
d(matrix[0][2] ) * d(matrix[2][0] )
)
lowerCamelCase_ : Union[str, Any] = -(
(d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] ))
)
lowerCamelCase_ : int = (d(matrix[0][1] ) * d(matrix[1][2] )) - (
d(matrix[0][2] ) * d(matrix[1][1] )
)
lowerCamelCase_ : Optional[Any] = -(
(d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] ))
)
lowerCamelCase_ : Tuple = (d(matrix[0][0] ) * d(matrix[1][1] )) - (
d(matrix[0][1] ) * d(matrix[1][0] )
)
# Transpose the cofactor matrix (Adjoint matrix)
lowerCamelCase_ : Dict = array(__UpperCAmelCase )
for i in range(3 ):
for j in range(3 ):
lowerCamelCase_ : Optional[Any] = cofactor_matrix[j][i]
# Inverse of the matrix using the formula (1/determinant) * adjoint matrix
lowerCamelCase_ : Any = array(__UpperCAmelCase )
for i in range(3 ):
for j in range(3 ):
inverse_matrix[i][j] /= d(__UpperCAmelCase )
# Calculate the inverse of the matrix
return [[float(d(__UpperCAmelCase ) ) or 0.0 for n in row] for row in inverse_matrix]
raise ValueError("Please provide a matrix of size 2x2 or 3x3." )
| 488 |
from functools import lru_cache
def __a ( __UpperCAmelCase : int ) -> set:
"""simple docstring"""
lowerCamelCase_ : List[str] = 2
lowerCamelCase_ : Any = set()
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.add(__UpperCAmelCase )
if n > 1:
factors.add(__UpperCAmelCase )
return factors
@lru_cache
def __a ( __UpperCAmelCase : int ) -> int:
"""simple docstring"""
return len(unique_prime_factors(__UpperCAmelCase ) )
def __a ( __UpperCAmelCase : list ) -> bool:
"""simple docstring"""
return len(set(__UpperCAmelCase ) ) in (0, 1)
def __a ( __UpperCAmelCase : int ) -> list:
"""simple docstring"""
lowerCamelCase_ : Tuple = 2
while True:
# Increment each value of a generated range
lowerCamelCase_ : Union[str, Any] = [base + i for i in range(__UpperCAmelCase )]
# Run elements through out unique_prime_factors function
# Append our target number to the end.
lowerCamelCase_ : Any = [upf_len(__UpperCAmelCase ) for x in group]
checker.append(__UpperCAmelCase )
# If all numbers in the list are equal, return the group variable.
if equality(__UpperCAmelCase ):
return group
# Increment our base variable by 1
base += 1
def __a ( __UpperCAmelCase : int = 4 ) -> int:
"""simple docstring"""
lowerCamelCase_ : int = run(__UpperCAmelCase )
return results[0] if len(__UpperCAmelCase ) else None
if __name__ == "__main__":
print(solution())
| 488 | 1 |
"""simple docstring"""
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 lowerCAmelCase__ ( _UpperCamelCase : Tuple ) -> str:
"""simple docstring"""
snake_case = fname.split(os.path.sep )[-1]
return re.search(r'^(.*)_\d+\.jpg$' , A__ ).groups()[0]
class lowerCAmelCase_ ( __lowerCamelCase ):
"""simple docstring"""
def __init__( self , lowerCAmelCase , lowerCAmelCase=None , lowerCAmelCase=None ):
"""simple docstring"""
snake_case = file_names
snake_case = image_transform
snake_case = label_to_id
def __len__( self ):
"""simple docstring"""
return len(self.file_names )
def __getitem__( self , lowerCAmelCase ):
"""simple docstring"""
snake_case = self.file_names[idx]
snake_case = PIL.Image.open(UpperCamelCase_ )
snake_case = raw_image.convert('RGB' )
if self.image_transform is not None:
snake_case = self.image_transform(UpperCamelCase_ )
snake_case = extract_label(UpperCamelCase_ )
if self.label_to_id is not None:
snake_case = self.label_to_id[label]
return {"image": image, "label": label}
def lowerCAmelCase__ ( _UpperCamelCase : List[Any] , _UpperCamelCase : List[Any] ) -> Any:
"""simple docstring"""
if args.with_tracking:
snake_case = Accelerator(
cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='all' , project_dir=args.project_dir )
else:
snake_case = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
snake_case = config['lr']
snake_case = int(config['num_epochs'] )
snake_case = int(config['seed'] )
snake_case = int(config['batch_size'] )
snake_case = config['image_size']
if not isinstance(A__ , (list, tuple) ):
snake_case = (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":
snake_case = args.checkpointing_steps
elif args.checkpointing_steps.isdigit():
snake_case = int(args.checkpointing_steps )
else:
raise ValueError(
f"""Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.""" )
else:
snake_case = None
# We need to initialize the trackers we use, and also store our configuration
if args.with_tracking:
snake_case = os.path.split(A__ )[-1].split('.' )[0]
accelerator.init_trackers(A__ , A__ )
# Grab all the image filenames
snake_case = [os.path.join(args.data_dir , A__ ) for fname in os.listdir(args.data_dir ) if fname.endswith('.jpg' )]
# Build the label correspondences
snake_case = [extract_label(A__ ) for fname in file_names]
snake_case = list(set(A__ ) )
id_to_label.sort()
snake_case = {lbl: i for i, lbl in enumerate(A__ )}
# Set the seed before splitting the data.
np.random.seed(A__ )
torch.manual_seed(A__ )
torch.cuda.manual_seed_all(A__ )
# Split our filenames between train and validation
snake_case = np.random.permutation(len(A__ ) )
snake_case = int(0.8 * len(A__ ) )
snake_case = random_perm[:cut]
snake_case = random_perm[cut:]
# For training we use a simple RandomResizedCrop
snake_case = Compose([RandomResizedCrop(A__ , scale=(0.5, 1.0) ), ToTensor()] )
snake_case = PetsDataset(
[file_names[i] for i in train_split] , image_transform=A__ , label_to_id=A__ )
# For evaluation, we use a deterministic Resize
snake_case = Compose([Resize(A__ ), ToTensor()] )
snake_case = PetsDataset([file_names[i] for i in eval_split] , image_transform=A__ , label_to_id=A__ )
# Instantiate dataloaders.
snake_case = DataLoader(A__ , shuffle=A__ , batch_size=A__ , num_workers=4 )
snake_case = DataLoader(A__ , shuffle=A__ , batch_size=A__ , num_workers=4 )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
snake_case = create_model('resnet50d' , pretrained=A__ , num_classes=len(A__ ) )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
snake_case = model.to(accelerator.device )
# Freezing the base model
for param in model.parameters():
snake_case = False
for param in model.get_classifier().parameters():
snake_case = True
# We normalize the batches of images to be a bit faster.
snake_case = torch.tensor(model.default_cfg['mean'] )[None, :, None, None].to(accelerator.device )
snake_case = torch.tensor(model.default_cfg['std'] )[None, :, None, None].to(accelerator.device )
# Instantiate optimizer
snake_case = torch.optim.Adam(params=model.parameters() , lr=lr / 2_5 )
# Instantiate learning rate scheduler
snake_case = OneCycleLR(optimizer=A__ , max_lr=A__ , epochs=A__ , steps_per_epoch=len(A__ ) )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
snake_case ,snake_case ,snake_case ,snake_case ,snake_case = accelerator.prepare(
A__ , A__ , A__ , A__ , A__ )
# We need to keep track of how many total steps we have iterated over
snake_case = 0
# We also need to keep track of the starting epoch so files are named properly
snake_case = 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 )
snake_case = os.path.basename(args.resume_from_checkpoint )
else:
# Get the most recent checkpoint
snake_case = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()]
dirs.sort(key=os.path.getctime )
snake_case = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
# Extract `epoch_{i}` or `step_{i}`
snake_case = os.path.splitext(A__ )[0]
if "epoch" in training_difference:
snake_case = int(training_difference.replace('epoch_' , '' ) ) + 1
snake_case = None
else:
snake_case = int(training_difference.replace('step_' , '' ) )
snake_case = resume_step // len(A__ )
resume_step -= starting_epoch * len(A__ )
# Now we train the model
for epoch in range(A__ , A__ ):
model.train()
if args.with_tracking:
snake_case = 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
snake_case = accelerator.skip_first_batches(A__ , A__ )
overall_step += resume_step
else:
# After the first iteration though, we need to go back to the original dataloader
snake_case = train_dataloader
for batch in active_dataloader:
# We could avoid this line since we set the accelerator with `device_placement=True`.
snake_case = {k: v.to(accelerator.device ) for k, v in batch.items()}
snake_case = (batch['image'] - mean) / std
snake_case = model(A__ )
snake_case = torch.nn.functional.cross_entropy(A__ , batch['label'] )
# We keep track of the loss at each epoch
if args.with_tracking:
total_loss += loss.detach().float()
accelerator.backward(A__ )
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
if isinstance(A__ , A__ ):
snake_case = f"""step_{overall_step}"""
if overall_step % checkpointing_steps == 0:
if args.output_dir is not None:
snake_case = os.path.join(args.output_dir , A__ )
accelerator.save_state(A__ )
model.eval()
snake_case = 0
snake_case = 0
for step, batch in enumerate(A__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
snake_case = {k: v.to(accelerator.device ) for k, v in batch.items()}
snake_case = (batch['image'] - mean) / std
with torch.no_grad():
snake_case = model(A__ )
snake_case = outputs.argmax(dim=-1 )
snake_case ,snake_case = accelerator.gather_for_metrics((predictions, batch['label']) )
snake_case = predictions == references
num_elems += accurate_preds.shape[0]
accurate += accurate_preds.long().sum()
snake_case = accurate.item() / num_elems
# Use accelerator.print to print only on the main process.
accelerator.print(f"""epoch {epoch}: {1_0_0 * eval_metric:.2f}""" )
if args.with_tracking:
accelerator.log(
{
'accuracy': 1_0_0 * eval_metric,
'train_loss': total_loss.item() / len(A__ ),
'epoch': epoch,
} , step=A__ , )
if checkpointing_steps == "epoch":
snake_case = f"""epoch_{epoch}"""
if args.output_dir is not None:
snake_case = os.path.join(args.output_dir , A__ )
accelerator.save_state(A__ )
if args.with_tracking:
accelerator.end_training()
def lowerCAmelCase__ ( ) -> Optional[int]:
"""simple docstring"""
snake_case = argparse.ArgumentParser(description='Simple example of training script.' )
parser.add_argument('--data_dir' , required=A__ , 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=A__ , default=A__ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose'
'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'
'and an Nvidia Ampere GPU.' , )
parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' )
parser.add_argument(
'--checkpointing_steps' , type=A__ , default=A__ , 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=A__ , 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=A__ , default=A__ , 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=A__ , default='logs' , help='Location on where to store experiment tracking logs` and relevent project information' , )
snake_case = parser.parse_args()
snake_case = {'lr': 3e-2, 'num_epochs': 3, 'seed': 4_2, 'batch_size': 6_4, 'image_size': 2_2_4}
training_function(A__ , A__ )
if __name__ == "__main__":
main()
| 714 | """simple docstring"""
import os
from argparse import ArgumentParser, Namespace
from ..data import SingleSentenceClassificationProcessor as Processor
from ..pipelines import TextClassificationPipeline
from ..utils import is_tf_available, is_torch_available, logging
from . import BaseTransformersCLICommand
if not is_tf_available() and not is_torch_available():
raise RuntimeError("At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training")
# TF training parameters
SCREAMING_SNAKE_CASE__ = False
SCREAMING_SNAKE_CASE__ = False
def lowerCAmelCase__ ( _UpperCamelCase : Namespace ) -> List[str]:
"""simple docstring"""
return TrainCommand(_UpperCamelCase )
class lowerCAmelCase_ ( lowerCAmelCase ):
"""simple docstring"""
@staticmethod
def snake_case ( lowerCAmelCase ):
"""simple docstring"""
snake_case = parser.add_parser('train' , help='CLI tool to train a model on a task.' )
train_parser.add_argument(
'--train_data' , type=lowerCAmelCase , required=lowerCAmelCase , help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.' , )
train_parser.add_argument(
'--column_label' , type=lowerCAmelCase , default=0 , help='Column of the dataset csv file with example labels.' )
train_parser.add_argument(
'--column_text' , type=lowerCAmelCase , default=1 , help='Column of the dataset csv file with example texts.' )
train_parser.add_argument(
'--column_id' , type=lowerCAmelCase , default=2 , help='Column of the dataset csv file with example ids.' )
train_parser.add_argument(
'--skip_first_row' , action='store_true' , help='Skip the first row of the csv file (headers).' )
train_parser.add_argument('--validation_data' , type=lowerCAmelCase , default='' , help='path to validation dataset.' )
train_parser.add_argument(
'--validation_split' , type=lowerCAmelCase , default=0.1 , help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.' , )
train_parser.add_argument('--output' , type=lowerCAmelCase , default='./' , help='path to saved the trained model.' )
train_parser.add_argument(
'--task' , type=lowerCAmelCase , default='text_classification' , help='Task to train the model on.' )
train_parser.add_argument(
'--model' , type=lowerCAmelCase , default='bert-base-uncased' , help='Model\'s name or path to stored model.' )
train_parser.add_argument('--train_batch_size' , type=lowerCAmelCase , default=32 , help='Batch size for training.' )
train_parser.add_argument('--valid_batch_size' , type=lowerCAmelCase , default=64 , help='Batch size for validation.' )
train_parser.add_argument('--learning_rate' , type=lowerCAmelCase , default=3E-5 , help='Learning rate.' )
train_parser.add_argument('--adam_epsilon' , type=lowerCAmelCase , default=1E-08 , help='Epsilon for Adam optimizer.' )
train_parser.set_defaults(func=lowerCAmelCase )
def __init__( self , lowerCAmelCase ):
"""simple docstring"""
snake_case = logging.get_logger('transformers-cli/training' )
snake_case = 'tf' if is_tf_available() else 'torch'
os.makedirs(args.output , exist_ok=lowerCAmelCase )
snake_case = args.output
snake_case = args.column_label
snake_case = args.column_text
snake_case = args.column_id
self.logger.info(F"""Loading {args.task} pipeline for {args.model}""" )
if args.task == "text_classification":
snake_case = TextClassificationPipeline.from_pretrained(args.model )
elif args.task == "token_classification":
raise NotImplementedError
elif args.task == "question_answering":
raise NotImplementedError
self.logger.info(F"""Loading dataset from {args.train_data}""" )
snake_case = Processor.create_from_csv(
args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , )
snake_case = None
if args.validation_data:
self.logger.info(F"""Loading validation dataset from {args.validation_data}""" )
snake_case = Processor.create_from_csv(
args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , )
snake_case = args.validation_split
snake_case = args.train_batch_size
snake_case = args.valid_batch_size
snake_case = args.learning_rate
snake_case = args.adam_epsilon
def snake_case ( self ):
"""simple docstring"""
if self.framework == "tf":
return self.run_tf()
return self.run_torch()
def snake_case ( self ):
"""simple docstring"""
raise NotImplementedError
def snake_case ( self ):
"""simple docstring"""
self.pipeline.fit(
self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , )
# Save trained pipeline
self.pipeline.save_pretrained(self.output )
| 104 | 0 |
import os
import numpy
import onnx
def A_ ( _UpperCAmelCase , _UpperCAmelCase ):
SCREAMING_SNAKE_CASE_: Dict = a.name
SCREAMING_SNAKE_CASE_: Optional[int] = b.name
SCREAMING_SNAKE_CASE_: Tuple = ""
SCREAMING_SNAKE_CASE_: Union[str, Any] = ""
SCREAMING_SNAKE_CASE_: str = a == b
SCREAMING_SNAKE_CASE_: Tuple = name_a
SCREAMING_SNAKE_CASE_: Any = name_b
return res
def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ):
for i, input_name in enumerate(node_proto.input ):
if input_name == name:
node_proto.input.insert(_UpperCAmelCase , _UpperCAmelCase )
node_proto.input.pop(i + 1 )
if node_proto.op_type == "If":
_graph_replace_input_with(node_proto.attribute[0].g , _UpperCAmelCase , _UpperCAmelCase )
_graph_replace_input_with(node_proto.attribute[1].g , _UpperCAmelCase , _UpperCAmelCase )
if node_proto.op_type == "Loop":
_graph_replace_input_with(node_proto.attribute[0].g , _UpperCAmelCase , _UpperCAmelCase )
def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ):
for n in graph_proto.node:
_node_replace_input_with(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ):
SCREAMING_SNAKE_CASE_: int = list(model.graph.initializer )
SCREAMING_SNAKE_CASE_: Optional[int] = list(model_without_ext.graph.initializer )
for i, ref_i in ind_to_replace:
assert inits_with_data[i].name == inits[i].name
assert inits_with_data[ref_i].name == inits[ref_i].name
assert i > ref_i
SCREAMING_SNAKE_CASE_: int = inits[i].name
SCREAMING_SNAKE_CASE_: List[Any] = inits[ref_i].name
model_without_ext.graph.initializer.remove(inits[i] )
# for n in model.graph.node:
_graph_replace_input_with(model_without_ext.graph , _UpperCAmelCase , _UpperCAmelCase )
def A_ ( _UpperCAmelCase ):
SCREAMING_SNAKE_CASE_: int = os.path.dirname(_UpperCAmelCase )
SCREAMING_SNAKE_CASE_: Tuple = os.path.basename(_UpperCAmelCase )
SCREAMING_SNAKE_CASE_: Optional[Any] = onnx.load(os.path.join(_UpperCAmelCase , _UpperCAmelCase ) )
SCREAMING_SNAKE_CASE_: Tuple = list(model.graph.initializer )
SCREAMING_SNAKE_CASE_: Union[str, Any] = set()
SCREAMING_SNAKE_CASE_: Union[str, Any] = {}
SCREAMING_SNAKE_CASE_: int = []
SCREAMING_SNAKE_CASE_: Any = 0
for i in range(len(_UpperCAmelCase ) ):
if i in dup_set:
continue
for j in range(i + 1 , len(_UpperCAmelCase ) ):
if j in dup_set:
continue
if _is_equal_tensor_proto(inits[i] , inits[j] ):
dup_set.add(_UpperCAmelCase )
dup_set.add(_UpperCAmelCase )
SCREAMING_SNAKE_CASE_: Dict = inits[j].data_type
SCREAMING_SNAKE_CASE_: Optional[int] = numpy.prod(inits[j].dims )
if dtype == 1:
mem_size *= 4
elif dtype == 6:
mem_size *= 4
elif dtype == 7 or dtype == 11:
mem_size *= 8
else:
print("unexpected data type: " , _UpperCAmelCase )
total_reduced_size += mem_size
SCREAMING_SNAKE_CASE_: List[Any] = inits[i].name
SCREAMING_SNAKE_CASE_: List[str] = inits[j].name
if name_i in dup_map:
dup_map[name_i].append(_UpperCAmelCase )
else:
SCREAMING_SNAKE_CASE_: List[str] = [name_j]
ind_to_replace.append((j, i) )
print("total reduced size: " , total_reduced_size / 10_24 / 10_24 / 10_24 , "GB" )
SCREAMING_SNAKE_CASE_: List[str] = sorted(_UpperCAmelCase )
_remove_dup_initializers_from_model(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
SCREAMING_SNAKE_CASE_: Union[str, Any] = "optimized_" + model_file_name
SCREAMING_SNAKE_CASE_: Union[str, Any] = os.path.join(_UpperCAmelCase , _UpperCAmelCase )
onnx.save(_UpperCAmelCase , _UpperCAmelCase )
return new_model
| 671 |
from math import asin, atan, cos, radians, sin, sqrt, tan
lowerCAmelCase : Union[str, Any] = 637_8137.0
lowerCAmelCase : int = 635_6752.31_4245
lowerCAmelCase : Union[str, Any] = 6378137
def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ):
SCREAMING_SNAKE_CASE_: List[Any] = (AXIS_A - AXIS_B) / AXIS_A
SCREAMING_SNAKE_CASE_: str = atan((1 - flattening) * tan(radians(_UpperCAmelCase ) ) )
SCREAMING_SNAKE_CASE_: Optional[int] = atan((1 - flattening) * tan(radians(_UpperCAmelCase ) ) )
SCREAMING_SNAKE_CASE_: Any = radians(_UpperCAmelCase )
SCREAMING_SNAKE_CASE_: Dict = radians(_UpperCAmelCase )
# Equation
SCREAMING_SNAKE_CASE_: str = sin((phi_a - phi_a) / 2 )
SCREAMING_SNAKE_CASE_: List[Any] = sin((lambda_a - lambda_a) / 2 )
# Square both values
sin_sq_phi *= sin_sq_phi
sin_sq_lambda *= sin_sq_lambda
SCREAMING_SNAKE_CASE_: Tuple = sqrt(sin_sq_phi + (cos(_UpperCAmelCase ) * cos(_UpperCAmelCase ) * sin_sq_lambda) )
return 2 * RADIUS * asin(_UpperCAmelCase )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 671 | 1 |
import gc
import unittest
from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
from diffusers.utils import is_flax_available, slow
from diffusers.utils.testing_utils import require_flax
if is_flax_available():
import jax
import jax.numpy as jnp
from flax.jax_utils import replicate
from flax.training.common_utils import shard
@slow
@require_flax
class a__ ( unittest.TestCase ):
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
__a , __a = FlaxStableDiffusionPipeline.from_pretrained(
'stabilityai/stable-diffusion-2' , revision='bf16' , dtype=jnp.bfloataa , )
__a = 'A painting of a squirrel eating a burger'
__a = jax.device_count()
__a = num_samples * [prompt]
__a = sd_pipe.prepare_inputs(UpperCAmelCase )
__a = replicate(UpperCAmelCase )
__a = shard(UpperCAmelCase )
__a = jax.random.PRNGKey(0 )
__a = jax.random.split(UpperCAmelCase , jax.device_count() )
__a = sd_pipe(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , num_inference_steps=2_5 , jit=UpperCAmelCase )[0]
assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3)
__a = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
__a = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]
__a = jnp.asarray(jax.device_get(image_slice.flatten() ) )
__a = jnp.array([0.4_238, 0.4_414, 0.4_395, 0.4_453, 0.4_629, 0.4_590, 0.4_531, 0.45_508, 0.4_512] )
print(f'''output_slice: {output_slice}''' )
assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
__a = 'stabilityai/stable-diffusion-2'
__a , __a = FlaxDPMSolverMultistepScheduler.from_pretrained(UpperCAmelCase , subfolder='scheduler' )
__a , __a = FlaxStableDiffusionPipeline.from_pretrained(
UpperCAmelCase , scheduler=UpperCAmelCase , revision='bf16' , dtype=jnp.bfloataa , )
__a = scheduler_params
__a = 'A painting of a squirrel eating a burger'
__a = jax.device_count()
__a = num_samples * [prompt]
__a = sd_pipe.prepare_inputs(UpperCAmelCase )
__a = replicate(UpperCAmelCase )
__a = shard(UpperCAmelCase )
__a = jax.random.PRNGKey(0 )
__a = jax.random.split(UpperCAmelCase , jax.device_count() )
__a = sd_pipe(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , num_inference_steps=2_5 , jit=UpperCAmelCase )[0]
assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3)
__a = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
__a = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]
__a = jnp.asarray(jax.device_get(image_slice.flatten() ) )
__a = jnp.array([0.4_336, 0.42_969, 0.4_453, 0.4_199, 0.4_297, 0.4_531, 0.4_434, 0.4_434, 0.4_297] )
print(f'''output_slice: {output_slice}''' )
assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
| 246 | import warnings
from ...utils import logging
from .image_processing_beit import BeitImageProcessor
lowerCamelCase_ : Dict = logging.get_logger(__name__)
class a__ ( __snake_case ):
def __init__( self , *UpperCAmelCase , **UpperCAmelCase ) -> None:
warnings.warn(
'The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'
' use BeitImageProcessor instead.' , UpperCAmelCase , )
super().__init__(*UpperCAmelCase , **UpperCAmelCase )
| 246 | 1 |
from random import randint
from tempfile import TemporaryFile
import numpy as np
def lowerCamelCase__ ( lowercase , lowercase , lowercase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : str = 0
if start < end:
SCREAMING_SNAKE_CASE : int = randint(lowercase , lowercase )
SCREAMING_SNAKE_CASE : int = a[end]
SCREAMING_SNAKE_CASE : str = a[pivot]
SCREAMING_SNAKE_CASE : Dict = temp
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = _in_place_partition(lowercase , lowercase , lowercase )
count += _in_place_quick_sort(lowercase , lowercase , p - 1 )
count += _in_place_quick_sort(lowercase , p + 1 , lowercase )
return count
def lowerCamelCase__ ( lowercase , lowercase , lowercase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : int = 0
SCREAMING_SNAKE_CASE : Any = randint(lowercase , lowercase )
SCREAMING_SNAKE_CASE : Optional[int] = a[end]
SCREAMING_SNAKE_CASE : Any = a[pivot]
SCREAMING_SNAKE_CASE : List[str] = temp
SCREAMING_SNAKE_CASE : List[Any] = start - 1
for index in range(lowercase , lowercase ):
count += 1
if a[index] < a[end]: # check if current val is less than pivot value
SCREAMING_SNAKE_CASE : Optional[Any] = new_pivot_index + 1
SCREAMING_SNAKE_CASE : Dict = a[new_pivot_index]
SCREAMING_SNAKE_CASE : List[Any] = a[index]
SCREAMING_SNAKE_CASE : Optional[int] = temp
SCREAMING_SNAKE_CASE : Any = a[new_pivot_index + 1]
SCREAMING_SNAKE_CASE : Optional[Any] = a[end]
SCREAMING_SNAKE_CASE : Tuple = temp
return new_pivot_index + 1, count
snake_case = TemporaryFile()
snake_case = 100 # 1000 elements are to be sorted
snake_case , snake_case = 0, 1 # mean and standard deviation
snake_case = np.random.normal(mu, sigma, p)
np.save(outfile, X)
print("""The array is""")
print(X)
outfile.seek(0) # using the same array
snake_case = np.load(outfile)
snake_case = len(M) - 1
snake_case = _in_place_quick_sort(M, 0, r)
print(
"""No of Comparisons for 100 elements selected from a standard normal distribution"""
"""is :"""
)
print(z)
| 62 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
from ..models.clipseg import CLIPSegForImageSegmentation
from ..utils import is_vision_available, requires_backends
from .base import PipelineTool
if is_vision_available():
from PIL import Image
class SCREAMING_SNAKE_CASE ( lowerCAmelCase ):
'''simple docstring'''
UpperCamelCase_ : Optional[Any] = (
'''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.'''
'''It takes two arguments named `image` which should be the original image, and `label` which should be a text '''
'''describing the elements what should be identified in the segmentation mask. The tool returns the mask.'''
)
UpperCamelCase_ : Union[str, Any] = '''CIDAS/clipseg-rd64-refined'''
UpperCamelCase_ : Any = '''image_segmenter'''
UpperCamelCase_ : int = CLIPSegForImageSegmentation
UpperCamelCase_ : Optional[Any] = ['''image''', '''text''']
UpperCamelCase_ : int = ['''image''']
def __init__( self : str , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ):
requires_backends(self , ["vision"] )
super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ )
def _A ( self : Tuple , UpperCAmelCase_ : "Image" , UpperCAmelCase_ : str ):
return self.pre_processor(text=[label] , images=[image] , padding=UpperCAmelCase_ , return_tensors="pt" )
def _A ( self : str , UpperCAmelCase_ : Optional[Any] ):
with torch.no_grad():
SCREAMING_SNAKE_CASE : str = self.model(**UpperCAmelCase_ ).logits
return logits
def _A ( self : Union[str, Any] , UpperCAmelCase_ : List[str] ):
SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy()
SCREAMING_SNAKE_CASE : Optional[int] = 0
SCREAMING_SNAKE_CASE : str = 1
return Image.fromarray((array * 255).astype(np.uinta ) )
| 62 | 1 |
def _a ( UpperCamelCase_ : str , UpperCamelCase_ : list[str] ) -> str:
"""simple docstring"""
lowerCAmelCase__ = ""
for word_or_phrase in separated:
if not isinstance(UpperCamelCase_ , UpperCamelCase_ ):
raise Exception("join() accepts only strings to be joined" )
joined += word_or_phrase + separator
return joined.strip(UpperCamelCase_ )
if __name__ == "__main__":
from doctest import testmod
testmod()
| 115 |
def _a ( UpperCamelCase_ : Any , UpperCamelCase_ : List[str] ) -> List[Any]:
"""simple docstring"""
lowerCAmelCase__ = 0
lowerCAmelCase__ = len(UpperCamelCase_ ) - 1
while left <= right:
# avoid divided by 0 during interpolation
if sorted_collection[left] == sorted_collection[right]:
if sorted_collection[left] == item:
return left
else:
return None
lowerCAmelCase__ = left + ((item - sorted_collection[left]) * (right - left)) // (
sorted_collection[right] - sorted_collection[left]
)
# out of range check
if point < 0 or point >= len(UpperCamelCase_ ):
return None
lowerCAmelCase__ = sorted_collection[point]
if current_item == item:
return point
else:
if point < left:
lowerCAmelCase__ = left
lowerCAmelCase__ = point
elif point > right:
lowerCAmelCase__ = right
lowerCAmelCase__ = point
else:
if item < current_item:
lowerCAmelCase__ = point - 1
else:
lowerCAmelCase__ = point + 1
return None
def _a ( UpperCamelCase_ : List[str] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> List[Any]:
"""simple docstring"""
if sorted_collection[left] == sorted_collection[right]:
if sorted_collection[left] == item:
return left
else:
return None
lowerCAmelCase__ = left + ((item - sorted_collection[left]) * (right - left)) // (
sorted_collection[right] - sorted_collection[left]
)
# out of range check
if point < 0 or point >= len(UpperCamelCase_ ):
return None
if sorted_collection[point] == item:
return point
elif point < left:
return interpolation_search_by_recursion(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
elif point > right:
return interpolation_search_by_recursion(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
else:
if sorted_collection[point] > item:
return interpolation_search_by_recursion(
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , point - 1 )
else:
return interpolation_search_by_recursion(
UpperCamelCase_ , UpperCamelCase_ , point + 1 , UpperCamelCase_ )
def _a ( UpperCamelCase_ : Optional[Any] ) -> Tuple:
"""simple docstring"""
if collection != sorted(UpperCamelCase_ ):
raise ValueError("Collection must be ascending sorted" )
return True
if __name__ == "__main__":
import sys
a_ = 0
if debug == 1:
a_ = [10, 30, 40, 45, 50, 66, 77, 93]
try:
__assert_sorted(collection)
except ValueError:
sys.exit('''Sequence must be ascending sorted to apply interpolation search''')
a_ = 67
a_ = interpolation_search(collection, target)
if result is not None:
print(F"{target} found at positions: {result}")
else:
print('''Not found''')
| 115 | 1 |
import argparse
import json
import os
import fairseq
import torch
from fairseq.data import Dictionary
# Register SEW's fairseq modules
from sew_asapp import tasks # noqa: F401
from transformers import (
SEWConfig,
SEWForCTC,
SEWModel,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaProcessor,
logging,
)
logging.set_verbosity_info()
_UpperCAmelCase : int = logging.get_logger(__name__)
_UpperCAmelCase : Optional[int] = {
"""post_extract_proj""": """feature_projection""",
"""encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""",
"""self_attn.k_proj""": """encoder.layers.*.attention.k_proj""",
"""self_attn.v_proj""": """encoder.layers.*.attention.v_proj""",
"""self_attn.q_proj""": """encoder.layers.*.attention.q_proj""",
"""self_attn.out_proj""": """encoder.layers.*.attention.out_proj""",
"""self_attn_layer_norm""": """encoder.layers.*.layer_norm""",
"""fc1""": """encoder.layers.*.feed_forward.intermediate_dense""",
"""fc2""": """encoder.layers.*.feed_forward.output_dense""",
"""final_layer_norm""": """encoder.layers.*.final_layer_norm""",
"""encoder.upsample.0""": """encoder.upsample.projection""",
"""encoder.layer_norm""": """encoder.layer_norm""",
"""w2v_model.layer_norm""": """layer_norm""",
"""w2v_encoder.proj""": """lm_head""",
"""mask_emb""": """masked_spec_embed""",
}
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> List[Any]:
for attribute in key.split('.' ):
lowerCamelCase__ : List[str] = getattr(_UpperCAmelCase , _UpperCAmelCase )
if weight_type is not None:
lowerCamelCase__ : Dict = getattr(_UpperCAmelCase , _UpperCAmelCase ).shape
else:
lowerCamelCase__ : Optional[Any] = hf_pointer.shape
assert hf_shape == value.shape, (
F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be"""
F""" {value.shape} for {full_name}"""
)
if weight_type == "weight":
lowerCamelCase__ : List[Any] = value
elif weight_type == "weight_g":
lowerCamelCase__ : Optional[int] = value
elif weight_type == "weight_v":
lowerCamelCase__ : int = value
elif weight_type == "bias":
lowerCamelCase__ : Dict = value
else:
lowerCamelCase__ : List[Any] = value
logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" )
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> List[str]:
lowerCamelCase__ : List[str] = []
lowerCamelCase__ : Any = fairseq_model.state_dict()
lowerCamelCase__ : List[Any] = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor
for name, value in fairseq_dict.items():
lowerCamelCase__ : str = False
if "conv_layers" in name:
load_conv_layer(
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , hf_model.config.feat_extract_norm == 'group' , )
lowerCamelCase__ : Any = True
else:
for key, mapped_key in MAPPING.items():
lowerCamelCase__ : Optional[Any] = 'sew.' + mapped_key if (is_finetuned and mapped_key != 'lm_head') else mapped_key
if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]:
lowerCamelCase__ : Optional[int] = True
if "*" in mapped_key:
lowerCamelCase__ : int = name.split(_UpperCAmelCase )[0].split('.' )[-2]
lowerCamelCase__ : Dict = mapped_key.replace('*' , _UpperCAmelCase )
if "weight_g" in name:
lowerCamelCase__ : Dict = 'weight_g'
elif "weight_v" in name:
lowerCamelCase__ : str = 'weight_v'
elif "weight" in name:
lowerCamelCase__ : Dict = 'weight'
elif "bias" in name:
lowerCamelCase__ : List[Any] = 'bias'
else:
lowerCamelCase__ : Optional[Any] = None
set_recursively(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
continue
if not is_used:
unused_weights.append(_UpperCAmelCase )
logger.warning(F"""Unused weights: {unused_weights}""" )
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> List[str]:
lowerCamelCase__ : Optional[int] = full_name.split('conv_layers.' )[-1]
lowerCamelCase__ : List[Any] = name.split('.' )
lowerCamelCase__ : Optional[Any] = int(items[0] )
lowerCamelCase__ : Optional[Any] = int(items[1] )
if type_id == 0:
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
F"""{full_name} has size {value.shape}, but"""
F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."""
)
lowerCamelCase__ : int = value
logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
F"""{full_name} has size {value.shape}, but"""
F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."""
)
lowerCamelCase__ : Any = value
logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"""
" found."
)
lowerCamelCase__ : str = value
logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
F"""{full_name} has size {value.shape}, but"""
F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."""
)
lowerCamelCase__ : Dict = value
logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
else:
unused_weights.append(_UpperCAmelCase )
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> int:
lowerCamelCase__ : List[str] = SEWConfig()
if is_finetuned:
lowerCamelCase__ : List[Any] = model.wav_encoder.wav_model.cfg
else:
lowerCamelCase__ : Dict = model.cfg
lowerCamelCase__ : Any = fs_config.conv_bias
lowerCamelCase__ : Optional[int] = eval(fs_config.conv_feature_layers )
lowerCamelCase__ : str = [x[0] for x in conv_layers]
lowerCamelCase__ : List[Any] = [x[1] for x in conv_layers]
lowerCamelCase__ : Any = [x[2] for x in conv_layers]
lowerCamelCase__ : Union[str, Any] = 'gelu'
lowerCamelCase__ : int = 'layer' if fs_config.extractor_mode == 'layer_norm' else 'group'
lowerCamelCase__ : Dict = 0.0
lowerCamelCase__ : Optional[int] = fs_config.activation_fn.name
lowerCamelCase__ : Tuple = fs_config.encoder_embed_dim
lowerCamelCase__ : Union[str, Any] = 0.02
lowerCamelCase__ : Optional[Any] = fs_config.encoder_ffn_embed_dim
lowerCamelCase__ : int = 1e-5
lowerCamelCase__ : Optional[int] = fs_config.encoder_layerdrop
lowerCamelCase__ : Tuple = fs_config.encoder_attention_heads
lowerCamelCase__ : Union[str, Any] = fs_config.conv_pos_groups
lowerCamelCase__ : Tuple = fs_config.conv_pos
lowerCamelCase__ : List[str] = len(_UpperCAmelCase )
lowerCamelCase__ : Optional[Any] = fs_config.encoder_layers
lowerCamelCase__ : int = fs_config.squeeze_factor
# take care of any params that are overridden by the Wav2VecCtc model
if is_finetuned:
lowerCamelCase__ : Dict = model.cfg
lowerCamelCase__ : Optional[int] = fs_config.final_dropout
lowerCamelCase__ : Optional[int] = fs_config.layerdrop
lowerCamelCase__ : Optional[Any] = fs_config.activation_dropout
lowerCamelCase__ : Tuple = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0
lowerCamelCase__ : List[Any] = fs_config.attention_dropout
lowerCamelCase__ : Optional[Any] = fs_config.dropout_input
lowerCamelCase__ : Optional[int] = fs_config.dropout
lowerCamelCase__ : Optional[int] = fs_config.mask_channel_length
lowerCamelCase__ : int = fs_config.mask_channel_prob
lowerCamelCase__ : Tuple = fs_config.mask_length
lowerCamelCase__ : List[str] = fs_config.mask_prob
lowerCamelCase__ : List[str] = 'Wav2Vec2FeatureExtractor'
lowerCamelCase__ : str = 'Wav2Vec2CTCTokenizer'
return config
@torch.no_grad()
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=True ) -> Any:
if is_finetuned:
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : int = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} )
else:
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] )
if config_path is not None:
lowerCamelCase__ : int = SEWConfig.from_pretrained(_UpperCAmelCase )
else:
lowerCamelCase__ : int = convert_config(model[0] , _UpperCAmelCase )
lowerCamelCase__ : Union[str, Any] = model[0].eval()
lowerCamelCase__ : Optional[int] = True if config.feat_extract_norm == 'layer' else False
lowerCamelCase__ : List[Any] = WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=_UpperCAmelCase , return_attention_mask=_UpperCAmelCase , )
if is_finetuned:
if dict_path:
lowerCamelCase__ : Optional[Any] = Dictionary.load(_UpperCAmelCase )
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
lowerCamelCase__ : int = target_dict.pad_index
lowerCamelCase__ : List[str] = target_dict.bos_index
lowerCamelCase__ : str = target_dict.pad_index
lowerCamelCase__ : Any = target_dict.bos_index
lowerCamelCase__ : Tuple = target_dict.eos_index
lowerCamelCase__ : Optional[Any] = len(target_dict.symbols )
lowerCamelCase__ : Optional[Any] = os.path.join(_UpperCAmelCase , 'vocab.json' )
if not os.path.isdir(_UpperCAmelCase ):
logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(_UpperCAmelCase ) )
return
os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase )
with open(_UpperCAmelCase , 'w' , encoding='utf-8' ) as vocab_handle:
json.dump(target_dict.indices , _UpperCAmelCase )
lowerCamelCase__ : Optional[int] = WavaVecaCTCTokenizer(
_UpperCAmelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=_UpperCAmelCase , )
lowerCamelCase__ : Optional[Any] = WavaVecaProcessor(feature_extractor=_UpperCAmelCase , tokenizer=_UpperCAmelCase )
processor.save_pretrained(_UpperCAmelCase )
lowerCamelCase__ : int = SEWForCTC(_UpperCAmelCase )
else:
lowerCamelCase__ : Optional[Any] = SEWModel(_UpperCAmelCase )
feature_extractor.save_pretrained(_UpperCAmelCase )
recursively_load_weights(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
hf_model.save_pretrained(_UpperCAmelCase )
if __name__ == "__main__":
_UpperCAmelCase : str = argparse.ArgumentParser()
parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""")
parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""")
parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
parser.add_argument(
"""--is_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not"""
)
_UpperCAmelCase : Union[str, Any] = parser.parse_args()
convert_sew_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned
)
| 295 |
def snake_case ( lowerCamelCase ):
'''simple docstring'''
if collection == []:
return []
# get some information about the collection
__lowercase = len(lowerCamelCase )
__lowercase = max(lowerCamelCase )
__lowercase = min(lowerCamelCase )
# create the counting array
__lowercase = coll_max + 1 - coll_min
__lowercase = [0] * counting_arr_length
# count how much a number appears in the collection
for number in collection:
counting_arr[number - coll_min] += 1
# sum each position with it's predecessors. now, counting_arr[i] tells
# us how many elements <= i has in the collection
for i in range(1 , lowerCamelCase ):
__lowercase = counting_arr[i] + counting_arr[i - 1]
# create the output collection
__lowercase = [0] * coll_len
# place the elements in the output, respecting the original order (stable
# sort) from end to begin, updating counting_arr
for i in reversed(range(0 , lowerCamelCase ) ):
__lowercase = collection[i]
counting_arr[collection[i] - coll_min] -= 1
return ordered
def snake_case ( lowerCamelCase ):
'''simple docstring'''
return "".join([chr(lowerCamelCase ) for i in counting_sort([ord(lowerCamelCase ) for c in string] )] )
if __name__ == "__main__":
# Test string sort
assert counting_sort_string("""thisisthestring""") == "eghhiiinrsssttt"
__UpperCamelCase : str = input("""Enter numbers separated by a comma:\n""").strip()
__UpperCamelCase : Union[str, Any] = [int(item) for item in user_input.split(""",""")]
print(counting_sort(unsorted))
| 80 | 0 |
"""simple docstring"""
import os
import socket
from contextlib import contextmanager
import torch
from ..commands.config.default import write_basic_config # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version
if is_deepspeed_available():
from deepspeed import DeepSpeedEngine
if is_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
def _lowerCAmelCase ( UpperCamelCase_ ):
if is_torch_version("""<""" , """2.0.0""" ) or not hasattr(UpperCamelCase_ , """_dynamo""" ):
return False
return isinstance(UpperCamelCase_ , torch._dynamo.eval_frame.OptimizedModule )
def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ = True ):
__SCREAMING_SNAKE_CASE = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)
__SCREAMING_SNAKE_CASE = is_compiled_module(UpperCamelCase_ )
if is_compiled:
__SCREAMING_SNAKE_CASE = model
__SCREAMING_SNAKE_CASE = model._orig_mod
if is_deepspeed_available():
options += (DeepSpeedEngine,)
while isinstance(UpperCamelCase_ , UpperCamelCase_ ):
__SCREAMING_SNAKE_CASE = model.module
if not keep_fpaa_wrapper:
__SCREAMING_SNAKE_CASE = getattr(UpperCamelCase_ , """forward""" )
__SCREAMING_SNAKE_CASE = model.__dict__.pop("""_original_forward""" , UpperCamelCase_ )
if original_forward is not None:
while hasattr(UpperCamelCase_ , """__wrapped__""" ):
__SCREAMING_SNAKE_CASE = forward.__wrapped__
if forward == original_forward:
break
__SCREAMING_SNAKE_CASE = forward
if getattr(UpperCamelCase_ , """_converted_to_transformer_engine""" , UpperCamelCase_ ):
convert_model(UpperCamelCase_ , to_transformer_engine=UpperCamelCase_ )
if is_compiled:
__SCREAMING_SNAKE_CASE = model
__SCREAMING_SNAKE_CASE = compiled_model
return model
def _lowerCAmelCase ( ):
PartialState().wait_for_everyone()
def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ):
if PartialState().distributed_type == DistributedType.TPU:
xm.save(UpperCamelCase_ , UpperCamelCase_ )
elif PartialState().local_process_index == 0:
torch.save(UpperCamelCase_ , UpperCamelCase_ )
@contextmanager
def _lowerCAmelCase ( **UpperCamelCase_ ):
for key, value in kwargs.items():
__SCREAMING_SNAKE_CASE = str(UpperCamelCase_ )
yield
for key in kwargs:
if key.upper() in os.environ:
del os.environ[key.upper()]
def _lowerCAmelCase ( UpperCamelCase_ ):
if not hasattr(UpperCamelCase_ , """__qualname__""" ) and not hasattr(UpperCamelCase_ , """__name__""" ):
__SCREAMING_SNAKE_CASE = getattr(UpperCamelCase_ , """__class__""" , UpperCamelCase_ )
if hasattr(UpperCamelCase_ , """__qualname__""" ):
return obj.__qualname__
if hasattr(UpperCamelCase_ , """__name__""" ):
return obj.__name__
return str(UpperCamelCase_ )
def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ):
for key, value in source.items():
if isinstance(UpperCamelCase_ , UpperCamelCase_ ):
__SCREAMING_SNAKE_CASE = destination.setdefault(UpperCamelCase_ , {} )
merge_dicts(UpperCamelCase_ , UpperCamelCase_ )
else:
__SCREAMING_SNAKE_CASE = value
return destination
def _lowerCAmelCase ( UpperCamelCase_ = None ):
if port is None:
__SCREAMING_SNAKE_CASE = 2_9500
with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s:
return s.connect_ex(("""localhost""", port) ) == 0
| 706 |
"""simple docstring"""
import json
import os
from functools import lru_cache
from typing import TYPE_CHECKING, List, Optional, Tuple
import regex as re
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
if TYPE_CHECKING:
from transformers.pipelines.conversational import Conversation
__magic_name__ = logging.get_logger(__name__)
__magic_name__ = {
"vocab_file": "vocab.json",
"merges_file": "merges.txt",
"tokenizer_config_file": "tokenizer_config.json",
}
__magic_name__ = {
"vocab_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"},
"merges_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"},
"tokenizer_config_file": {
"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json"
},
}
__magic_name__ = {"facebook/blenderbot-3B": 128}
@lru_cache()
# Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
def _lowerCAmelCase ( ):
__SCREAMING_SNAKE_CASE = (
list(range(ord("""!""" ) , ord("""~""" ) + 1 ) ) + list(range(ord("""¡""" ) , ord("""¬""" ) + 1 ) ) + list(range(ord("""®""" ) , ord("""ÿ""" ) + 1 ) )
)
__SCREAMING_SNAKE_CASE = bs[:]
__SCREAMING_SNAKE_CASE = 0
for b in range(2**8 ):
if b not in bs:
bs.append(UpperCamelCase_ )
cs.append(2**8 + n )
n += 1
__SCREAMING_SNAKE_CASE = [chr(UpperCamelCase_ ) for n in cs]
return dict(zip(UpperCamelCase_ , UpperCamelCase_ ) )
def _lowerCAmelCase ( UpperCamelCase_ ):
__SCREAMING_SNAKE_CASE = set()
__SCREAMING_SNAKE_CASE = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
__SCREAMING_SNAKE_CASE = char
return pairs
class SCREAMING_SNAKE_CASE_ ( __a ):
"""simple docstring"""
__lowercase : Tuple = VOCAB_FILES_NAMES
__lowercase : Any = PRETRAINED_VOCAB_FILES_MAP
__lowercase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__lowercase : Optional[int] = ['''input_ids''', '''attention_mask''']
def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__="replace" , lowerCAmelCase__="<s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__="<s>" , lowerCAmelCase__="<unk>" , lowerCAmelCase__="<pad>" , lowerCAmelCase__="<mask>" , lowerCAmelCase__=False , **lowerCAmelCase__ , ):
__SCREAMING_SNAKE_CASE = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__) if isinstance(lowerCAmelCase__ , lowerCAmelCase__) else bos_token
__SCREAMING_SNAKE_CASE = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__) if isinstance(lowerCAmelCase__ , lowerCAmelCase__) else eos_token
__SCREAMING_SNAKE_CASE = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__) if isinstance(lowerCAmelCase__ , lowerCAmelCase__) else sep_token
__SCREAMING_SNAKE_CASE = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__) if isinstance(lowerCAmelCase__ , lowerCAmelCase__) else cls_token
__SCREAMING_SNAKE_CASE = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__) if isinstance(lowerCAmelCase__ , lowerCAmelCase__) else unk_token
__SCREAMING_SNAKE_CASE = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__) if isinstance(lowerCAmelCase__ , lowerCAmelCase__) else pad_token
# Mask token behave like a normal word, i.e. include the space before it
__SCREAMING_SNAKE_CASE = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__) if isinstance(lowerCAmelCase__ , lowerCAmelCase__) else mask_token
super().__init__(
errors=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ , **lowerCAmelCase__ , )
with open(lowerCAmelCase__ , encoding="""utf-8""") as vocab_handle:
__SCREAMING_SNAKE_CASE = json.load(lowerCAmelCase__)
__SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()}
__SCREAMING_SNAKE_CASE = errors # how to handle errors in decoding
__SCREAMING_SNAKE_CASE = bytes_to_unicode()
__SCREAMING_SNAKE_CASE = {v: k for k, v in self.byte_encoder.items()}
with open(lowerCAmelCase__ , encoding="""utf-8""") as merges_handle:
__SCREAMING_SNAKE_CASE = merges_handle.read().split("""\n""")[1:-1]
__SCREAMING_SNAKE_CASE = [tuple(merge.split()) for merge in bpe_merges]
__SCREAMING_SNAKE_CASE = dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__))))
__SCREAMING_SNAKE_CASE = {}
__SCREAMING_SNAKE_CASE = add_prefix_space
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
__SCREAMING_SNAKE_CASE = re.compile(R"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
@property
# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot
def snake_case_ ( self):
return len(self.encoder)
def snake_case_ ( self):
return dict(self.encoder , **self.added_tokens_encoder)
def snake_case_ ( self , lowerCAmelCase__):
if token in self.cache:
return self.cache[token]
__SCREAMING_SNAKE_CASE = tuple(lowerCAmelCase__)
__SCREAMING_SNAKE_CASE = get_pairs(lowerCAmelCase__)
if not pairs:
return token
while True:
__SCREAMING_SNAKE_CASE = min(lowerCAmelCase__ , key=lambda lowerCAmelCase__: self.bpe_ranks.get(lowerCAmelCase__ , float("""inf""")))
if bigram not in self.bpe_ranks:
break
__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = bigram
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = 0
while i < len(lowerCAmelCase__):
try:
__SCREAMING_SNAKE_CASE = word.index(lowerCAmelCase__ , lowerCAmelCase__)
except ValueError:
new_word.extend(word[i:])
break
else:
new_word.extend(word[i:j])
__SCREAMING_SNAKE_CASE = j
if word[i] == first and i < len(lowerCAmelCase__) - 1 and word[i + 1] == second:
new_word.append(first + second)
i += 2
else:
new_word.append(word[i])
i += 1
__SCREAMING_SNAKE_CASE = tuple(lowerCAmelCase__)
__SCREAMING_SNAKE_CASE = new_word
if len(lowerCAmelCase__) == 1:
break
else:
__SCREAMING_SNAKE_CASE = get_pairs(lowerCAmelCase__)
__SCREAMING_SNAKE_CASE = """ """.join(lowerCAmelCase__)
__SCREAMING_SNAKE_CASE = word
return word
def snake_case_ ( self , lowerCAmelCase__):
__SCREAMING_SNAKE_CASE = []
for token in re.findall(self.pat , lowerCAmelCase__):
__SCREAMING_SNAKE_CASE = """""".join(
self.byte_encoder[b] for b in token.encode("""utf-8""")) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCAmelCase__).split(""" """))
return bpe_tokens
def snake_case_ ( self , lowerCAmelCase__):
return self.encoder.get(lowerCAmelCase__ , self.encoder.get(self.unk_token))
def snake_case_ ( self , lowerCAmelCase__):
return self.decoder.get(lowerCAmelCase__)
def snake_case_ ( self , lowerCAmelCase__):
__SCREAMING_SNAKE_CASE = """""".join(lowerCAmelCase__)
__SCREAMING_SNAKE_CASE = bytearray([self.byte_decoder[c] for c in text]).decode("""utf-8""" , errors=self.errors)
return text
def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None):
if not os.path.isdir(lowerCAmelCase__):
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
return
__SCREAMING_SNAKE_CASE = os.path.join(
lowerCAmelCase__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""])
__SCREAMING_SNAKE_CASE = os.path.join(
lowerCAmelCase__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""])
with open(lowerCAmelCase__ , """w""" , encoding="""utf-8""") as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase__ , ensure_ascii=lowerCAmelCase__) + """\n""")
__SCREAMING_SNAKE_CASE = 0
with open(lowerCAmelCase__ , """w""" , encoding="""utf-8""") as writer:
writer.write("""#version: 0.2\n""")
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda lowerCAmelCase__: kv[1]):
if index != token_index:
logger.warning(
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
""" Please check that the tokenizer is not corrupted!""")
__SCREAMING_SNAKE_CASE = token_index
writer.write(""" """.join(lowerCAmelCase__) + """\n""")
index += 1
return vocab_file, merge_file
def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = False):
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__)) + [1]
return [1] + ([0] * len(lowerCAmelCase__)) + [1, 1] + ([0] * len(lowerCAmelCase__)) + [1]
def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None):
__SCREAMING_SNAKE_CASE = [self.sep_token_id]
__SCREAMING_SNAKE_CASE = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]
def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__=False , **lowerCAmelCase__):
__SCREAMING_SNAKE_CASE = kwargs.pop("""add_prefix_space""" , self.add_prefix_space)
if (is_split_into_words or add_prefix_space) and (len(lowerCAmelCase__) > 0 and not text[0].isspace()):
__SCREAMING_SNAKE_CASE = """ """ + text
return (text, kwargs)
def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None):
return token_ids_a + [self.eos_token_id]
def snake_case_ ( self , lowerCAmelCase__):
__SCREAMING_SNAKE_CASE = []
for is_user, text in conversation.iter_texts():
if is_user:
# We need to space prefix as it's being done within blenderbot
inputs.append(""" """ + text)
else:
# Generated responses should contain them already.
inputs.append(lowerCAmelCase__)
__SCREAMING_SNAKE_CASE = """ """.join(lowerCAmelCase__)
__SCREAMING_SNAKE_CASE = self.encode(lowerCAmelCase__)
if len(lowerCAmelCase__) > self.model_max_length:
__SCREAMING_SNAKE_CASE = input_ids[-self.model_max_length :]
logger.warning(f"Trimmed input from conversation as it was longer than {self.model_max_length} tokens.")
return input_ids
| 248 | 0 |
import random
import unittest
import torch
from diffusers import IFInpaintingPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device
from ..pipeline_params import (
TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin
@skip_mps
class lowerCamelCase( __snake_case , __snake_case , unittest.TestCase ):
'''simple docstring'''
__magic_name__ = IFInpaintingPipeline
__magic_name__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'width', 'height'}
__magic_name__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
__magic_name__ = PipelineTesterMixin.required_optional_params - {'latents'}
def lowerCAmelCase__ ( self ):
return self._get_dummy_components()
def lowerCAmelCase__ ( self , snake_case_ , snake_case_=0 ):
if str(snake_case_ ).startswith('mps' ):
_A = torch.manual_seed(snake_case_ )
else:
_A = torch.Generator(device=snake_case_ ).manual_seed(snake_case_ )
_A = floats_tensor((1, 3, 32, 32) , rng=random.Random(snake_case_ ) ).to(snake_case_ )
_A = floats_tensor((1, 3, 32, 32) , rng=random.Random(snake_case_ ) ).to(snake_case_ )
_A = {
'prompt': 'A painting of a squirrel eating a burger',
'image': image,
'mask_image': mask_image,
'generator': generator,
'num_inference_steps': 2,
'output_type': 'numpy',
}
return inputs
@unittest.skipIf(
torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , )
def lowerCAmelCase__ ( self ):
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 )
def lowerCAmelCase__ ( self ):
self._test_save_load_optional_components()
@unittest.skipIf(torch_device != 'cuda' , reason='float16 requires CUDA' )
def lowerCAmelCase__ ( self ):
# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
super().test_save_load_floataa(expected_max_diff=1E-1 )
def lowerCAmelCase__ ( self ):
self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 )
def lowerCAmelCase__ ( self ):
self._test_save_load_local()
def lowerCAmelCase__ ( self ):
self._test_inference_batch_single_identical(
expected_max_diff=1E-2 , )
| 27 |
def a__ ( A_ ):
'''simple docstring'''
if len(A_ ) < 2:
return collection
def circle_sort_util(A_, A_, A_ ) -> bool:
__magic_name__ = False
if low == high:
return swapped
__magic_name__ = low
__magic_name__ = high
while left < right:
if collection[left] > collection[right]:
__magic_name__ , __magic_name__ = (
collection[right],
collection[left],
)
__magic_name__ = True
left += 1
right -= 1
if left == right and collection[left] > collection[right + 1]:
__magic_name__ , __magic_name__ = (
collection[right + 1],
collection[left],
)
__magic_name__ = True
__magic_name__ = low + int((high - low) / 2 )
__magic_name__ = circle_sort_util(A_, A_, A_ )
__magic_name__ = circle_sort_util(A_, mid + 1, A_ )
return swapped or left_swap or right_swap
__magic_name__ = True
while is_not_sorted is True:
__magic_name__ = circle_sort_util(A_, 0, len(A_ ) - 1 )
return collection
if __name__ == "__main__":
__lowerCAmelCase : Union[str, Any] = input('Enter numbers separated by a comma:\n').strip()
__lowerCAmelCase : Tuple = [int(item) for item in user_input.split(',')]
print(circle_sort(unsorted))
| 529 | 0 |
import warnings
from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401
warnings.warn(
"""The `inpainting.py` script is outdated. Please use directly `from diffusers import"""
""" StableDiffusionInpaintPipeline` instead."""
)
| 716 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCAmelCase_ : Tuple = logging.get_logger(__name__)
UpperCAmelCase_ : List[str] = {
"""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 lowercase__ ( __A ):
__UpperCamelCase = """fnet"""
def __init__( self , _lowercase=32_000 , _lowercase=768 , _lowercase=12 , _lowercase=3_072 , _lowercase="gelu_new" , _lowercase=0.1 , _lowercase=512 , _lowercase=4 , _lowercase=0.02 , _lowercase=1e-12 , _lowercase=False , _lowercase=512 , _lowercase=3 , _lowercase=1 , _lowercase=2 , **_lowercase , ):
super().__init__(pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase , **_lowercase )
lowerCAmelCase_ : Optional[Any] = vocab_size
lowerCAmelCase_ : List[str] = max_position_embeddings
lowerCAmelCase_ : str = hidden_size
lowerCAmelCase_ : Any = num_hidden_layers
lowerCAmelCase_ : Optional[int] = intermediate_size
lowerCAmelCase_ : int = hidden_act
lowerCAmelCase_ : List[str] = hidden_dropout_prob
lowerCAmelCase_ : Tuple = initializer_range
lowerCAmelCase_ : int = type_vocab_size
lowerCAmelCase_ : str = layer_norm_eps
lowerCAmelCase_ : Optional[Any] = use_tpu_fourier_optimizations
lowerCAmelCase_ : Union[str, Any] = tpu_short_seq_length
| 440 | 0 |
'''simple docstring'''
from collections import deque
def __snake_case ( SCREAMING_SNAKE_CASE_ : Dict ) -> int:
"""simple docstring"""
UpperCAmelCase = len(SCREAMING_SNAKE_CASE_ )
UpperCAmelCase = deque()
UpperCAmelCase = [False for _ in range(SCREAMING_SNAKE_CASE_ )]
UpperCAmelCase = [-1 for _ in range(SCREAMING_SNAKE_CASE_ )]
UpperCAmelCase = index_of[:]
def strong_connect(SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Dict ):
UpperCAmelCase = index # the number when this node is seen
UpperCAmelCase = index # lowest rank node reachable from here
index += 1
stack.append(SCREAMING_SNAKE_CASE_ )
UpperCAmelCase = True
for w in g[v]:
if index_of[w] == -1:
UpperCAmelCase = strong_connect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCAmelCase = (
lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
)
elif on_stack[w]:
UpperCAmelCase = (
lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
)
if lowlink_of[v] == index_of[v]:
UpperCAmelCase = []
UpperCAmelCase = stack.pop()
UpperCAmelCase = False
component.append(SCREAMING_SNAKE_CASE_ )
while w != v:
UpperCAmelCase = stack.pop()
UpperCAmelCase = False
component.append(SCREAMING_SNAKE_CASE_ )
components.append(SCREAMING_SNAKE_CASE_ )
return index
UpperCAmelCase = []
for v in range(SCREAMING_SNAKE_CASE_ ):
if index_of[v] == -1:
strong_connect(SCREAMING_SNAKE_CASE_ , 0 , SCREAMING_SNAKE_CASE_ )
return components
def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Tuple ) -> Any:
"""simple docstring"""
UpperCAmelCase = [[] for _ in range(SCREAMING_SNAKE_CASE_ )]
for u, v in edges:
g[u].append(SCREAMING_SNAKE_CASE_ )
return g
if __name__ == "__main__":
# Test
a__ : Optional[int] = 7
a__ : Dict = [0, 0, 1, 2, 3, 3, 4, 4, 6]
a__ : List[str] = [1, 3, 2, 0, 1, 4, 5, 6, 5]
a__ : Optional[int] = [(u, v) for u, v in zip(source, target)]
a__ : str = create_graph(n_vertices, edges)
assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
| 51 |
"""simple docstring"""
def lowercase (_snake_case ) -> str:
'''simple docstring'''
if isinstance(_snake_case ,_snake_case ):
raise TypeError("'float' object cannot be interpreted as an integer" )
if isinstance(_snake_case ,_snake_case ):
raise TypeError("'str' object cannot be interpreted as an integer" )
if num == 0:
return "0b0"
__UpperCamelCase = False
if num < 0:
__UpperCamelCase = True
__UpperCamelCase = -num
__UpperCamelCase = []
while num > 0:
binary.insert(0 ,num % 2 )
num >>= 1
if negative:
return "-0b" + "".join(str(_snake_case ) for e in binary )
return "0b" + "".join(str(_snake_case ) for e in binary )
if __name__ == "__main__":
import doctest
doctest.testmod() | 505 | 0 |
def A__ ( _a : str , _a : int ):
'''simple docstring'''
snake_case__ : list[list[str]] =[[] for _ in range(_a )]
snake_case__ : str =key - 1
if key <= 0:
raise ValueError("""Height of grid can't be 0 or negative""" )
if key == 1 or len(_a ) <= key:
return input_string
for position, character in enumerate(_a ):
snake_case__ : List[str] =position % (lowest * 2) # puts it in bounds
snake_case__ : Optional[int] =min(_a , lowest * 2 - num ) # creates zigzag pattern
temp_grid[num].append(_a )
snake_case__ : Tuple =["""""".join(_a ) for row in temp_grid]
snake_case__ : Union[str, Any] ="""""".join(_a )
return output_string
def A__ ( _a : str , _a : int ):
'''simple docstring'''
snake_case__ : Dict =[]
snake_case__ : Any =key - 1
if key <= 0:
raise ValueError("""Height of grid can't be 0 or negative""" )
if key == 1:
return input_string
snake_case__ : list[list[str]] =[[] for _ in range(_a )] # generates template
for position in range(len(_a ) ):
snake_case__ : str =position % (lowest * 2) # puts it in bounds
snake_case__ : str =min(_a , lowest * 2 - num ) # creates zigzag pattern
temp_grid[num].append("""*""" )
snake_case__ : Optional[int] =0
for row in temp_grid: # fills in the characters
snake_case__ : Tuple =input_string[counter : counter + len(_a )]
grid.append(list(_a ) )
counter += len(_a )
snake_case__ : str ="""""" # reads as zigzag
for position in range(len(_a ) ):
snake_case__ : Optional[Any] =position % (lowest * 2) # puts it in bounds
snake_case__ : Dict =min(_a , lowest * 2 - num ) # creates zigzag pattern
output_string += grid[num][0]
grid[num].pop(0 )
return output_string
def A__ ( _a : str ):
'''simple docstring'''
snake_case__ : Any ={}
for key_guess in range(1 , len(_a ) ): # tries every key
snake_case__ : Optional[Any] =decrypt(_a , _a )
return results
if __name__ == "__main__":
import doctest
doctest.testmod()
| 448 |
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast
from ...utils import logging
if TYPE_CHECKING:
from ...feature_extraction_utils import FeatureExtractionMixin
from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import TensorType
__lowerCamelCase : Optional[int] = logging.get_logger(__name__)
__lowerCamelCase : Optional[int] = {
"""openai/whisper-base""": """https://huggingface.co/openai/whisper-base/resolve/main/config.json""",
}
# fmt: off
__lowerCamelCase : int = [
1, 2, 7, 8, 9, 10, 14, 25,
26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
63, 90, 91, 92, 93, 3_57, 3_66, 4_38, 5_32, 6_85,
7_05, 7_96, 9_30, 10_58, 12_20, 12_67, 12_79, 13_03, 13_43, 13_77,
13_91, 16_35, 17_82, 18_75, 21_62, 23_61, 24_88, 34_67, 40_08, 42_11,
46_00, 48_08, 52_99, 58_55, 63_29, 72_03, 96_09, 99_59, 1_05_63, 1_07_86,
1_14_20, 1_17_09, 1_19_07, 1_31_63, 1_36_97, 1_37_00, 1_48_08, 1_53_06, 1_64_10, 1_67_91,
1_79_92, 1_92_03, 1_95_10, 2_07_24, 2_23_05, 2_29_35, 2_70_07, 3_01_09, 3_04_20, 3_34_09,
3_49_49, 4_02_83, 4_04_93, 4_05_49, 4_72_82, 4_91_46, 5_02_57, 5_03_59, 5_03_60, 5_03_61
]
__lowerCamelCase : Dict = [
1, 2, 7, 8, 9, 10, 14, 25,
26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
63, 90, 91, 92, 93, 3_59, 5_03, 5_22, 5_42, 8_73,
8_93, 9_02, 9_18, 9_22, 9_31, 13_50, 18_53, 19_82, 24_60, 26_27,
32_46, 32_53, 32_68, 35_36, 38_46, 39_61, 41_83, 46_67, 65_85, 66_47,
72_73, 90_61, 93_83, 1_04_28, 1_09_29, 1_19_38, 1_20_33, 1_23_31, 1_25_62, 1_37_93,
1_41_57, 1_46_35, 1_52_65, 1_56_18, 1_65_53, 1_66_04, 1_83_62, 1_89_56, 2_00_75, 2_16_75,
2_25_20, 2_61_30, 2_61_61, 2_64_35, 2_82_79, 2_94_64, 3_16_50, 3_23_02, 3_24_70, 3_68_65,
4_28_63, 4_74_25, 4_98_70, 5_02_54, 5_02_58, 5_03_60, 5_03_61, 5_03_62
]
class _lowercase ( _A ):
_a : List[Any] = 'whisper'
_a : Any = ['past_key_values']
_a : Dict = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}
def __init__( self , a=5_1_8_6_5 , a=8_0 , a=6 , a=4 , a=6 , a=4 , a=1_5_3_6 , a=1_5_3_6 , a=0.0 , a=0.0 , a=5_0_2_5_7 , a=True , a=True , a="gelu" , a=2_5_6 , a=0.0 , a=0.0 , a=0.0 , a=0.02 , a=False , a=1_5_0_0 , a=4_4_8 , a=5_0_2_5_6 , a=5_0_2_5_6 , a=5_0_2_5_6 , a=None , a=[2_2_0, 5_0_2_5_6] , a=False , a=2_5_6 , a=False , a=0.05 , a=1_0 , a=2 , a=0.0 , a=1_0 , a=0 , a=7 , **a , ):
snake_case__ : Union[str, Any] =vocab_size
snake_case__ : int =num_mel_bins
snake_case__ : Tuple =d_model
snake_case__ : Optional[Any] =encoder_layers
snake_case__ : List[Any] =encoder_attention_heads
snake_case__ : Dict =decoder_layers
snake_case__ : Optional[Any] =decoder_attention_heads
snake_case__ : str =decoder_ffn_dim
snake_case__ : str =encoder_ffn_dim
snake_case__ : List[Any] =dropout
snake_case__ : Optional[Any] =attention_dropout
snake_case__ : Tuple =activation_dropout
snake_case__ : int =activation_function
snake_case__ : List[str] =init_std
snake_case__ : List[str] =encoder_layerdrop
snake_case__ : int =decoder_layerdrop
snake_case__ : Union[str, Any] =use_cache
snake_case__ : Tuple =encoder_layers
snake_case__ : int =scale_embedding # scale factor will be sqrt(d_model) if True
snake_case__ : Tuple =max_source_positions
snake_case__ : Union[str, Any] =max_target_positions
# Audio Classification-specific parameters. Feel free to ignore for other classes.
snake_case__ : str =classifier_proj_size
snake_case__ : List[str] =use_weighted_layer_sum
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
snake_case__ : Dict =apply_spec_augment
snake_case__ : Tuple =mask_time_prob
snake_case__ : Union[str, Any] =mask_time_length
snake_case__ : List[Any] =mask_time_min_masks
snake_case__ : Optional[int] =mask_feature_prob
snake_case__ : int =mask_feature_length
snake_case__ : Dict =mask_feature_min_masks
snake_case__ : Optional[Any] =median_filter_width
super().__init__(
pad_token_id=a , bos_token_id=a , eos_token_id=a , is_encoder_decoder=a , decoder_start_token_id=a , suppress_tokens=a , begin_suppress_tokens=a , **a , )
class _lowercase ( _A ):
@property
def lowercase__ ( self ):
snake_case__ : Union[str, Any] =OrderedDict(
[
("""input_features""", {0: """batch""", 1: """feature_size""", 2: """encoder_sequence"""}),
] )
if self.use_past:
snake_case__ : List[Any] ={0: """batch"""}
else:
snake_case__ : int ={0: """batch""", 1: """decoder_sequence"""}
if self.use_past:
self.fill_with_past_key_values_(a , direction="""inputs""" )
return common_inputs
def lowercase__ ( self , a , a = -1 , a = -1 , a = False , a = None , a = 2_2_0_5_0 , a = 5.0 , a = 2_2_0 , ):
snake_case__ : Union[str, Any] =OrderedDict()
snake_case__ : Optional[int] =OnnxConfig.generate_dummy_inputs(
self , preprocessor=preprocessor.feature_extractor , batch_size=a , framework=a , sampling_rate=a , time_duration=a , frequency=a , )
snake_case__ : Any =encoder_inputs["""input_features"""].shape[2]
snake_case__ : Dict =encoder_sequence_length // 2 if self.use_past else seq_length
snake_case__ : List[Any] =super().generate_dummy_inputs(
preprocessor.tokenizer , a , a , a , a )
snake_case__ : int =encoder_inputs.pop("""input_features""" )
snake_case__ : List[Any] =decoder_inputs.pop("""decoder_input_ids""" )
if "past_key_values" in decoder_inputs:
snake_case__ : int =decoder_inputs.pop("""past_key_values""" )
return dummy_inputs
@property
def lowercase__ ( self ):
return 1e-3
| 448 | 1 |
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_barthez import BarthezTokenizer
else:
UpperCamelCase = None
UpperCamelCase = logging.get_logger(__name__)
UpperCamelCase = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}
UpperCamelCase = {
"vocab_file": {
"moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model",
"moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model",
"moussaKam/barthez-orangesum-title": (
"https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model"
),
},
"tokenizer_file": {
"moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json",
"moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json",
"moussaKam/barthez-orangesum-title": (
"https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json"
),
},
}
UpperCamelCase = {
"moussaKam/mbarthez": 1_024,
"moussaKam/barthez": 1_024,
"moussaKam/barthez-orangesum-title": 1_024,
}
UpperCamelCase = "▁"
class lowerCAmelCase_ ( lowercase ):
"""simple docstring"""
_snake_case : List[str] = VOCAB_FILES_NAMES
_snake_case : Any = PRETRAINED_VOCAB_FILES_MAP
_snake_case : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_snake_case : Any = ["""input_ids""", """attention_mask"""]
_snake_case : Tuple = BarthezTokenizer
def __init__( self :Union[str, Any] , lowerCamelCase__ :str=None , lowerCamelCase__ :Union[str, Any]=None , lowerCamelCase__ :List[Any]="<s>" , lowerCamelCase__ :Optional[int]="</s>" , lowerCamelCase__ :Dict="</s>" , lowerCamelCase__ :Optional[int]="<s>" , lowerCamelCase__ :List[Any]="<unk>" , lowerCamelCase__ :Union[str, Any]="<pad>" , lowerCamelCase__ :int="<mask>" , **lowerCamelCase__ :Any , ):
# Mask token behave like a normal word, i.e. include the space before it
UpperCamelCase__ :Any = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else mask_token
super().__init__(
lowerCamelCase__ , tokenizer_file=lowerCamelCase__ , bos_token=lowerCamelCase__ , eos_token=lowerCamelCase__ , unk_token=lowerCamelCase__ , sep_token=lowerCamelCase__ , cls_token=lowerCamelCase__ , pad_token=lowerCamelCase__ , mask_token=lowerCamelCase__ , **lowerCamelCase__ , )
UpperCamelCase__ :int = vocab_file
UpperCamelCase__ :Optional[int] = False if not self.vocab_file else True
def __a ( self :Optional[Any] , lowerCamelCase__ :List[int] , lowerCamelCase__ :Optional[List[int]] = None ):
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
UpperCamelCase__ :List[Any] = [self.cls_token_id]
UpperCamelCase__ :Dict = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def __a ( self :List[Any] , lowerCamelCase__ :List[int] , lowerCamelCase__ :Optional[List[int]] = None ):
UpperCamelCase__ :Union[str, Any] = [self.sep_token_id]
UpperCamelCase__ :List[str] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def __a ( self :Any , lowerCamelCase__ :str , lowerCamelCase__ :Optional[str] = None ):
if not self.can_save_slow_tokenizer:
raise ValueError(
"""Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
"""tokenizer.""" )
if not os.path.isdir(lowerCamelCase__ ):
logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" )
return
UpperCamelCase__ :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__ ):
copyfile(self.vocab_file , lowerCamelCase__ )
return (out_vocab_file,) | 45 |
"""simple docstring"""
__UpperCAmelCase : List[str] = {str(digit): digit**5 for digit in range(10)}
def A ( _A ):
"""simple docstring"""
return sum(DIGITS_FIFTH_POWER[digit] for digit in str(_A ) )
def A ( ):
"""simple docstring"""
return sum(
number
for number in range(1_000, 1_000_000 )
if number == digits_fifth_powers_sum(_A ) )
if __name__ == "__main__":
print(solution())
| 584 | 0 |
_A = [
"DownloadConfig",
"DownloadManager",
"DownloadMode",
"StreamingDownloadManager",
]
from .download_config import DownloadConfig
from .download_manager import DownloadManager, DownloadMode
from .streaming_download_manager import StreamingDownloadManager
| 716 |
from __future__ import annotations
_A = list[tuple[int, int]]
_A = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
_A = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right
class _lowerCAmelCase :
def __init__( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , ) -> Tuple:
lowerCAmelCase_ = pos_x
lowerCAmelCase_ = pos_y
lowerCAmelCase_ = (pos_y, pos_x)
lowerCAmelCase_ = goal_x
lowerCAmelCase_ = goal_y
lowerCAmelCase_ = g_cost
lowerCAmelCase_ = parent
lowerCAmelCase_ = self.calculate_heuristic()
def __a ( self ) -> float:
lowerCAmelCase_ = abs(self.pos_x - self.goal_x )
lowerCAmelCase_ = abs(self.pos_y - self.goal_y )
return dx + dy
def __lt__( self , _UpperCamelCase ) -> bool:
return self.f_cost < other.f_cost
class _lowerCAmelCase :
def __init__( self , _UpperCamelCase , _UpperCamelCase ) -> Tuple:
lowerCAmelCase_ = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , _UpperCamelCase )
lowerCAmelCase_ = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99_999 , _UpperCamelCase )
lowerCAmelCase_ = [self.start]
lowerCAmelCase_ = []
lowerCAmelCase_ = False
def __a ( self ) -> Path | None:
while self.open_nodes:
# Open Nodes are sorted using __lt__
self.open_nodes.sort()
lowerCAmelCase_ = self.open_nodes.pop(0 )
if current_node.pos == self.target.pos:
lowerCAmelCase_ = True
return self.retrace_path(_UpperCamelCase )
self.closed_nodes.append(_UpperCamelCase )
lowerCAmelCase_ = self.get_successors(_UpperCamelCase )
for child_node in successors:
if child_node in self.closed_nodes:
continue
if child_node not in self.open_nodes:
self.open_nodes.append(_UpperCamelCase )
else:
# retrieve the best current path
lowerCAmelCase_ = self.open_nodes.pop(self.open_nodes.index(_UpperCamelCase ) )
if child_node.g_cost < better_node.g_cost:
self.open_nodes.append(_UpperCamelCase )
else:
self.open_nodes.append(_UpperCamelCase )
if not self.reached:
return [self.start.pos]
return None
def __a ( self , _UpperCamelCase ) -> list[Node]:
lowerCAmelCase_ = []
for action in delta:
lowerCAmelCase_ = parent.pos_x + action[1]
lowerCAmelCase_ = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_UpperCamelCase ) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(
_UpperCamelCase , _UpperCamelCase , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , _UpperCamelCase , ) )
return successors
def __a ( self , _UpperCamelCase ) -> Path:
lowerCAmelCase_ = node
lowerCAmelCase_ = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x) )
lowerCAmelCase_ = current_node.parent
path.reverse()
return path
if __name__ == "__main__":
_A = (0, 0)
_A = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
print("------")
_A = GreedyBestFirst(init, goal)
_A = greedy_bf.search()
if path:
for pos_x, pos_y in path:
_A = 2
for elem in grid:
print(elem)
| 279 | 0 |
'''simple docstring'''
import numpy as np
def __UpperCAmelCase ( _UpperCAmelCase : np.array ) -> np.array:
return (2 / (1 + np.exp(-2 * vector ))) - 1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 |
'''simple docstring'''
import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError
from transformers import (
AlbertTokenizer,
AutoTokenizer,
BertTokenizer,
BertTokenizerFast,
GPTaTokenizerFast,
is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie
sys.path.append(str(Path(__file__).parent.parent / '''utils'''))
from test_module.custom_tokenization import CustomTokenizer # noqa E402
if is_tokenizers_available():
from test_module.custom_tokenization_fast import CustomTokenizerFast
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = mock.Mock()
__snake_case = 500
__snake_case = {}
__snake_case = HTTPError
__snake_case = {}
# Download this model to make sure it's in the cache.
__snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
# Under the mock environment we get a 500 error when trying to reach the tokenizer.
with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head:
__snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
# This check we did call the fake head request
mock_head.assert_called()
@require_tokenizers
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = mock.Mock()
__snake_case = 500
__snake_case = {}
__snake_case = HTTPError
__snake_case = {}
# Download this model to make sure it's in the cache.
__snake_case = GPTaTokenizerFast.from_pretrained("gpt2" )
# Under the mock environment we get a 500 error when trying to reach the tokenizer.
with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head:
__snake_case = GPTaTokenizerFast.from_pretrained("gpt2" )
# This check we did call the fake head request
mock_head.assert_called()
def A ( self : Optional[Any] ):
"""simple docstring"""
try:
__snake_case = tempfile.mktemp()
with open(a_ , "wb" ) as f:
http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" , a_ )
__snake_case = AlbertTokenizer.from_pretrained(a_ )
finally:
os.remove(a_ )
# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
# the current folder and have the right name.
if os.path.isfile("tokenizer.json" ):
# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
return
try:
with open("tokenizer.json" , "wb" ) as f:
http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json" , a_ )
__snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
self.assertEqual(tokenizer.vocab_size , 1_000 )
# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.
finally:
os.remove("tokenizer.json" )
def A ( self : str ):
"""simple docstring"""
__snake_case = AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" )
@is_staging_test
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
__SCREAMING_SNAKE_CASE = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]
@classmethod
def A ( cls : List[Any] ):
"""simple docstring"""
__snake_case = TOKEN
HfFolder.save_token(a_ )
@classmethod
def A ( cls : List[Any] ):
"""simple docstring"""
try:
delete_repo(token=cls._token , repo_id="test-tokenizer" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-tokenizer-org" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-tokenizer" )
except HTTPError:
pass
def A ( self : int ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizer(a_ )
tokenizer.push_to_hub("test-tokenizer" , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
# Reset repo
delete_repo(token=self._token , repo_id="test-tokenizer" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(a_ , repo_id="test-tokenizer" , push_to_hub=a_ , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
def A ( self : int ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizer(a_ )
tokenizer.push_to_hub("valid_org/test-tokenizer-org" , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-tokenizer-org" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(
a_ , repo_id="valid_org/test-tokenizer-org" , push_to_hub=a_ , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
@require_tokenizers
def A ( self : List[str] ):
"""simple docstring"""
CustomTokenizer.register_for_auto_class()
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = CustomTokenizer(a_ )
# No fast custom tokenizer
tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token )
__snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" )
# Fast and slow custom tokenizer
CustomTokenizerFast.register_for_auto_class()
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizerFast.from_pretrained(a_ )
bert_tokenizer.save_pretrained(a_ )
__snake_case = CustomTokenizerFast.from_pretrained(a_ )
tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token )
__snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizerFast" )
__snake_case = AutoTokenizer.from_pretrained(
f'''{USER}/test-dynamic-tokenizer''' , use_fast=a_ , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" )
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("Hello 友達" )
self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} )
trie.add("Hello" )
trie.data
self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} )
def A ( self : str ):
"""simple docstring"""
__snake_case = Trie()
self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS] This is a extra_id_100"] )
trie.add("[CLS]" )
trie.add("extra_id_1" )
trie.add("extra_id_100" )
self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS]", " This is a ", "extra_id_100"] )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("A" )
self.assertEqual(trie.split("ABC" ) , ["A", "BC"] )
self.assertEqual(trie.split("BCA" ) , ["BC", "A"] )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("TOKEN]" )
trie.add("[SPECIAL_TOKEN]" )
self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] )
def A ( self : str ):
"""simple docstring"""
__snake_case = Trie()
trie.add("A" )
trie.add("P" )
trie.add("[SPECIAL_TOKEN]" )
self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] )
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("AB" )
trie.add("B" )
trie.add("C" )
self.assertEqual(trie.split("ABC" ) , ["AB", "C"] )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = Trie()
trie.add("ABC" )
trie.add("B" )
trie.add("CD" )
self.assertEqual(trie.split("ABCD" ) , ["ABC", "D"] )
def A ( self : Any ):
"""simple docstring"""
__snake_case = Trie()
__snake_case = trie.cut_text("ABC" , [0, 0, 2, 1, 2, 3] )
self.assertEqual(a_ , ["AB", "C"] )
| 69 | 1 |
'''simple docstring'''
from typing import List, Optional, Tuple, Union
import torch
from ...models import UNetaDModel
from ...schedulers import ScoreSdeVeScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class A__ ( _UpperCAmelCase ):
"""simple docstring"""
UpperCamelCase_ : UNetaDModel
UpperCamelCase_ : ScoreSdeVeScheduler
def __init__( self : Tuple , lowerCAmelCase__ : UNetaDModel , lowerCAmelCase__ : ScoreSdeVeScheduler ) -> str:
"""simple docstring"""
super().__init__()
self.register_modules(unet=__UpperCamelCase , scheduler=__UpperCamelCase )
@torch.no_grad()
def __call__( self : Optional[int] , lowerCAmelCase__ : int = 1 , lowerCAmelCase__ : int = 2_0_0_0 , lowerCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCAmelCase__ : Optional[str] = "pil" , lowerCAmelCase__ : bool = True , **lowerCAmelCase__ : Union[str, Any] , ) -> Union[ImagePipelineOutput, Tuple]:
"""simple docstring"""
_UpperCAmelCase : Dict = self.unet.config.sample_size
_UpperCAmelCase : List[Any] = (batch_size, 3, img_size, img_size)
_UpperCAmelCase : str = self.unet
_UpperCAmelCase : Optional[Any] = randn_tensor(__UpperCamelCase , generator=__UpperCamelCase ) * self.scheduler.init_noise_sigma
_UpperCAmelCase : str = sample.to(self.device )
self.scheduler.set_timesteps(__UpperCamelCase )
self.scheduler.set_sigmas(__UpperCamelCase )
for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ):
_UpperCAmelCase : Union[str, Any] = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device )
# correction step
for _ in range(self.scheduler.config.correct_steps ):
_UpperCAmelCase : Optional[int] = self.unet(__UpperCamelCase , __UpperCamelCase ).sample
_UpperCAmelCase : str = self.scheduler.step_correct(__UpperCamelCase , __UpperCamelCase , generator=__UpperCamelCase ).prev_sample
# prediction step
_UpperCAmelCase : Optional[int] = model(__UpperCamelCase , __UpperCamelCase ).sample
_UpperCAmelCase : Optional[int] = self.scheduler.step_pred(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , generator=__UpperCamelCase )
_UpperCAmelCase , _UpperCAmelCase : List[str] = output.prev_sample, output.prev_sample_mean
_UpperCAmelCase : Union[str, Any] = sample_mean.clamp(0 , 1 )
_UpperCAmelCase : List[Any] = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
_UpperCAmelCase : Dict = self.numpy_to_pil(__UpperCamelCase )
if not return_dict:
return (sample,)
return ImagePipelineOutput(images=__UpperCamelCase ) | 719 | '''simple docstring'''
from __future__ import annotations
import sys
from collections import deque
from typing import Generic, TypeVar
__a = TypeVar('T')
class A__ ( Generic[T] ):
"""simple docstring"""
UpperCamelCase_ : deque[T] # Cache store of keys
UpperCamelCase_ : set[T] # References of the keys in cache
UpperCamelCase_ : int = 10 # Maximum capacity of cache
def __init__( self : Dict , lowerCAmelCase__ : int ) -> None:
"""simple docstring"""
_UpperCAmelCase : List[str] = deque()
_UpperCAmelCase : Any = set()
if not n:
_UpperCAmelCase : Dict = sys.maxsize
elif n < 0:
raise ValueError("n should be an integer greater than 0." )
else:
_UpperCAmelCase : List[Any] = n
def _lowerCAmelCase ( self : List[str] , lowerCAmelCase__ : T ) -> None:
"""simple docstring"""
if x not in self.key_reference:
if len(self.dq_store ) == LRUCache._MAX_CAPACITY:
_UpperCAmelCase : int = self.dq_store.pop()
self.key_reference.remove(lowerCAmelCase__ )
else:
self.dq_store.remove(lowerCAmelCase__ )
self.dq_store.appendleft(lowerCAmelCase__ )
self.key_reference.add(lowerCAmelCase__ )
def _lowerCAmelCase ( self : Tuple ) -> None:
"""simple docstring"""
for k in self.dq_store:
print(lowerCAmelCase__ )
def __repr__( self : Tuple ) -> str:
"""simple docstring"""
return F"""LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}"""
if __name__ == "__main__":
import doctest
doctest.testmod()
__a = LRUCache(4)
lru_cache.refer('A')
lru_cache.refer(2)
lru_cache.refer(3)
lru_cache.refer('A')
lru_cache.refer(4)
lru_cache.refer(5)
lru_cache.display()
print(lru_cache)
assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]" | 257 | 0 |
"""simple docstring"""
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
SCREAMING_SNAKE_CASE_ = {
'''configuration_xmod''': [
'''XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''XmodConfig''',
'''XmodOnnxConfig''',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = [
'''XMOD_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''XmodForCausalLM''',
'''XmodForMaskedLM''',
'''XmodForMultipleChoice''',
'''XmodForQuestionAnswering''',
'''XmodForSequenceClassification''',
'''XmodForTokenClassification''',
'''XmodModel''',
'''XmodPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_xmod import (
XMOD_PRETRAINED_MODEL_ARCHIVE_LIST,
XmodForCausalLM,
XmodForMaskedLM,
XmodForMultipleChoice,
XmodForQuestionAnswering,
XmodForSequenceClassification,
XmodForTokenClassification,
XmodModel,
XmodPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 426 |
def lowerCamelCase__ ( _lowercase , _lowercase ):
'''simple docstring'''
while a != 0:
UpperCAmelCase_, UpperCAmelCase_ : Optional[int] = b % a, a
return b
def lowerCamelCase__ ( _lowercase , _lowercase ):
'''simple docstring'''
if gcd(_lowercase , _lowercase ) != 1:
UpperCAmelCase_ : int = f'''mod inverse of {a!r} and {m!r} does not exist'''
raise ValueError(_lowercase )
UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_ : Union[str, Any] = 1, 0, a
UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_ : Dict = 0, 1, m
while va != 0:
UpperCAmelCase_ : List[Any] = ua // va
UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_ : Any = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va
return ua % m | 30 | 0 |
def UpperCAmelCase__ ( lowerCamelCase_ : int ):
if number < 0:
raise ValueError('number must not be negative' )
return number & (number - 1) == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| 577 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__)
SCREAMING_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 _UpperCamelCase( __lowerCamelCase ):
__SCREAMING_SNAKE_CASE : List[Any] = '''xmod'''
def __init__( self : str , SCREAMING_SNAKE_CASE__ : Tuple=3_0_5_2_2 , SCREAMING_SNAKE_CASE__ : int=7_6_8 , SCREAMING_SNAKE_CASE__ : List[str]=1_2 , SCREAMING_SNAKE_CASE__ : List[str]=1_2 , SCREAMING_SNAKE_CASE__ : str=3_0_7_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Any=5_1_2 , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.02 , SCREAMING_SNAKE_CASE__ : int=1e-12 , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : Dict=0 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : Tuple="absolute" , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Tuple=2 , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=("en_XX",) , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , **SCREAMING_SNAKE_CASE__ : Tuple , ):
'''simple docstring'''
super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
__a : Union[str, Any] = vocab_size
__a : int = hidden_size
__a : Optional[int] = num_hidden_layers
__a : List[Any] = num_attention_heads
__a : Optional[int] = hidden_act
__a : List[Any] = intermediate_size
__a : List[str] = hidden_dropout_prob
__a : Any = attention_probs_dropout_prob
__a : str = max_position_embeddings
__a : List[Any] = type_vocab_size
__a : str = initializer_range
__a : List[str] = layer_norm_eps
__a : Optional[int] = position_embedding_type
__a : Optional[Any] = use_cache
__a : List[Any] = classifier_dropout
__a : Tuple = pre_norm
__a : Union[str, Any] = adapter_reduction_factor
__a : int = adapter_layer_norm
__a : List[Any] = adapter_reuse_layer_norm
__a : int = ln_before_adapter
__a : List[str] = list(SCREAMING_SNAKE_CASE__ )
__a : str = default_language
class _UpperCamelCase( __lowerCamelCase ):
@property
def __lowerCAmelCase ( self : int ):
'''simple docstring'''
if self.task == "multiple-choice":
__a : int = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
__a : Any = {0: 'batch', 1: 'sequence'}
return OrderedDict(
[
('input_ids', dynamic_axis),
('attention_mask', dynamic_axis),
] )
| 577 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.