code stringlengths 82 53.2k | code_codestyle int64 0 721 | style_context stringlengths 91 41.9k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
'''simple docstring'''
import unittest
from transformers import BertGenerationTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
SCREAMING_SNAKE_CASE_ = "▁"
SCREAMING_SNAKE_CASE_ = get_tests_dir("fixtures/test_sentencepiece.model")
@require_sentencepiece
class lowerCAmelCase ( lowerCamelCase__ , unittest.TestCase ):
"""simple docstring"""
_A = BertGenerationTokenizer
_A = False
_A = True
def __magic_name__ ( self ) -> Dict:
super().setUp()
__a : Optional[int] = BertGenerationTokenizer(_A , keep_accents=_A )
tokenizer.save_pretrained(self.tmpdirname )
def __magic_name__ ( self ) -> Dict:
__a : Dict = '<s>'
__a : List[Any] = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A )
def __magic_name__ ( self ) -> Any:
__a : List[Any] = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '<unk>' )
self.assertEqual(vocab_keys[1] , '<s>' )
self.assertEqual(vocab_keys[-1] , '<pad>' )
self.assertEqual(len(_A ) , 1002 )
def __magic_name__ ( self ) -> Dict:
self.assertEqual(self.get_tokenizer().vocab_size , 1000 )
def __magic_name__ ( self ) -> List[str]:
__a : int = BertGenerationTokenizer(_A , keep_accents=_A )
__a : List[str] = tokenizer.tokenize('This is a test' )
self.assertListEqual(_A , ['▁This', '▁is', '▁a', '▁t', 'est'] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(_A ) , [285, 46, 10, 170, 382] , )
__a : Union[str, Any] = tokenizer.tokenize('I was born in 92000, and this is falsé.' )
self.assertListEqual(
_A , [
SPIECE_UNDERLINE + 'I',
SPIECE_UNDERLINE + 'was',
SPIECE_UNDERLINE + 'b',
'or',
'n',
SPIECE_UNDERLINE + 'in',
SPIECE_UNDERLINE + '',
'9',
'2',
'0',
'0',
'0',
',',
SPIECE_UNDERLINE + 'and',
SPIECE_UNDERLINE + 'this',
SPIECE_UNDERLINE + 'is',
SPIECE_UNDERLINE + 'f',
'al',
's',
'é',
'.',
] , )
__a : str = tokenizer.convert_tokens_to_ids(_A )
self.assertListEqual(
_A , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , )
__a : Tuple = tokenizer.convert_ids_to_tokens(_A )
self.assertListEqual(
_A , [
SPIECE_UNDERLINE + 'I',
SPIECE_UNDERLINE + 'was',
SPIECE_UNDERLINE + 'b',
'or',
'n',
SPIECE_UNDERLINE + 'in',
SPIECE_UNDERLINE + '',
'<unk>',
'2',
'0',
'0',
'0',
',',
SPIECE_UNDERLINE + 'and',
SPIECE_UNDERLINE + 'this',
SPIECE_UNDERLINE + 'is',
SPIECE_UNDERLINE + 'f',
'al',
's',
'<unk>',
'.',
] , )
@cached_property
def __magic_name__ ( self ) -> str:
return BertGenerationTokenizer.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' )
@slow
def __magic_name__ ( self ) -> Any:
__a : Tuple = 'Hello World!'
__a : Optional[Any] = [18536, 2260, 101]
self.assertListEqual(_A , self.big_tokenizer.encode(_A ) )
@slow
def __magic_name__ ( self ) -> Union[str, Any]:
__a : Union[str, Any] = (
'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will'
' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth'
)
__a : Optional[int] = [
871,
419,
358,
946,
991,
2521,
452,
358,
1357,
387,
7751,
3536,
112,
985,
456,
126,
865,
938,
5400,
5734,
458,
1368,
467,
786,
2462,
5246,
1159,
633,
865,
4519,
457,
582,
852,
2557,
427,
916,
508,
405,
34324,
497,
391,
408,
11342,
1244,
385,
100,
938,
985,
456,
574,
362,
12597,
3200,
3129,
1172,
]
self.assertListEqual(_A , self.big_tokenizer.encode(_A ) )
@require_torch
@slow
def __magic_name__ ( self ) -> List[Any]:
import torch
from transformers import BertGenerationConfig, BertGenerationEncoder
# Build sequence
__a : Union[str, Any] = list(self.big_tokenizer.get_vocab().keys() )[:10]
__a : Any = ' '.join(_A )
__a : Tuple = self.big_tokenizer.encode_plus(_A , return_tensors='pt' , return_token_type_ids=_A )
__a : List[Any] = self.big_tokenizer.batch_encode_plus(
[sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=_A )
__a : Optional[Any] = BertGenerationConfig()
__a : int = BertGenerationEncoder(_A )
assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size
with torch.no_grad():
model(**_A )
model(**_A )
@slow
def __magic_name__ ( self ) -> int:
# fmt: off
__a : Any = {'input_ids': [[39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114], [448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=_A , model_name='google/bert_for_seq_generation_L-24_bbc_encoder' , revision='c817d1fd1be2ffa69431227a1fe320544943d4db' , )
| 597 |
'''simple docstring'''
import argparse
import os
from pathlib import Path
import fairseq
import torch
from packaging import version
from torch import nn
from transformers import (
BartConfig,
BartForConditionalGeneration,
BartForSequenceClassification,
BartModel,
BartTokenizer,
)
from transformers.utils import logging
SCREAMING_SNAKE_CASE_ = ["bart.large", "bart.large.mnli", "bart.large.cnn", "bart_xsum/model.pt"]
SCREAMING_SNAKE_CASE_ = {"bart.large": BartModel, "bart.large.mnli": BartForSequenceClassification}
if version.parse(fairseq.__version__) < version.parse("0.9.0"):
raise Exception("requires fairseq >= 0.9.0")
logging.set_verbosity_info()
SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE_ = " Hello world! cécé herlolip"
SCREAMING_SNAKE_CASE_ = [
("model.classification_heads.mnli.dense.weight", "classification_head.dense.weight"),
("model.classification_heads.mnli.dense.bias", "classification_head.dense.bias"),
("model.classification_heads.mnli.out_proj.weight", "classification_head.out_proj.weight"),
("model.classification_heads.mnli.out_proj.bias", "classification_head.out_proj.bias"),
]
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE__ ):
__a : Dict = [
'encoder.version',
'decoder.version',
'model.encoder.version',
'model.decoder.version',
'_float_tensor',
]
for k in ignore_keys:
state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
__a : Dict = dct.pop(SCREAMING_SNAKE_CASE__ )
__a : Dict = val
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE__ ):
__a : Dict = torch.load(SCREAMING_SNAKE_CASE__ , map_location='cpu' )
__a : Dict = torch.hub.load('pytorch/fairseq' , 'bart.large.cnn' ).eval()
hub_interface.model.load_state_dict(sd['model'] )
return hub_interface
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE__ ):
__a , __a : Dict = emb.weight.shape
__a : Optional[Any] = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ )
__a : List[Any] = emb.weight.data
return lin_layer
@torch.no_grad()
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ):
if not os.path.exists(SCREAMING_SNAKE_CASE__ ):
__a : Tuple = torch.hub.load('pytorch/fairseq' , SCREAMING_SNAKE_CASE__ ).eval()
else:
__a : Optional[int] = load_xsum_checkpoint(SCREAMING_SNAKE_CASE__ )
bart.model.upgrade_state_dict(bart.model.state_dict() )
if hf_checkpoint_name is None:
__a : List[str] = checkpoint_path.replace('.' , '-' )
__a : Optional[Any] = BartConfig.from_pretrained(SCREAMING_SNAKE_CASE__ )
__a : Union[str, Any] = bart.encode(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 )
__a : List[str] = BartTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ).encode(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).unsqueeze(0 )
if not torch.eq(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).all():
raise ValueError(
f'''converted tokenizer and pretrained tokenizer returned different output: {tokens} != {tokensa}''' )
if checkpoint_path == "bart.large.mnli":
__a : List[Any] = bart.state_dict()
remove_ignore_keys_(SCREAMING_SNAKE_CASE__ )
__a : str = state_dict['model.decoder.embed_tokens.weight']
for src, dest in mnli_rename_keys:
rename_key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
__a : Dict = BartForSequenceClassification(SCREAMING_SNAKE_CASE__ ).eval()
model.load_state_dict(SCREAMING_SNAKE_CASE__ )
__a : Any = bart.predict('mnli' , SCREAMING_SNAKE_CASE__ , return_logits=SCREAMING_SNAKE_CASE__ )
__a : Optional[Any] = model(SCREAMING_SNAKE_CASE__ )[0] # logits
else: # no classification heads to worry about
__a : Dict = bart.model.state_dict()
remove_ignore_keys_(SCREAMING_SNAKE_CASE__ )
__a : Optional[Any] = state_dict['decoder.embed_tokens.weight']
__a : List[Any] = bart.extract_features(SCREAMING_SNAKE_CASE__ )
if hf_checkpoint_name == "facebook/bart-large":
__a : Dict = BartModel(SCREAMING_SNAKE_CASE__ ).eval()
model.load_state_dict(SCREAMING_SNAKE_CASE__ )
__a : str = model(SCREAMING_SNAKE_CASE__ ).model[0]
else:
__a : Optional[Any] = BartForConditionalGeneration(SCREAMING_SNAKE_CASE__ ).eval() # an existing summarization ckpt
model.model.load_state_dict(SCREAMING_SNAKE_CASE__ )
if hasattr(SCREAMING_SNAKE_CASE__ , 'lm_head' ):
__a : Optional[int] = make_linear_from_emb(model.model.shared )
__a : List[Any] = model.model(SCREAMING_SNAKE_CASE__ )[0]
# Check results
if fairseq_output.shape != new_model_outputs.shape:
raise ValueError(
f'''`fairseq_output` shape and `new_model_output` shape are different: {fairseq_output.shape=}, {new_model_outputs.shape}''' )
if (fairseq_output != new_model_outputs).any().item():
raise ValueError('Some values in `fairseq_output` are different from `new_model_outputs`' )
Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ )
model.save_pretrained(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"fairseq_path", type=str, help="bart.large, bart.large.cnn or a path to a model.pt on local filesystem."
)
parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
parser.add_argument(
"--hf_config", default=None, type=str, help="Which huggingface architecture to use: bart-large-xsum"
)
SCREAMING_SNAKE_CASE_ = parser.parse_args()
convert_bart_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, hf_checkpoint_name=args.hf_config)
| 597 | 1 |
'''simple docstring'''
import importlib
import shutil
import threading
import warnings
from typing import List
import fsspec
import fsspec.asyn
from . import compression
from .hffilesystem import HfFileSystem
A_ : Optional[int] =importlib.util.find_spec('''s3fs''') is not None
if _has_safs:
from .safilesystem import SaFileSystem # noqa: F401
A_ : List[compression.BaseCompressedFileFileSystem] =[
compression.BzaFileSystem,
compression.GzipFileSystem,
compression.LzaFileSystem,
compression.XzFileSystem,
compression.ZstdFileSystem,
]
# Register custom filesystems
for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]:
if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class:
warnings.warn(f'''A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.''')
fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True)
def snake_case_ ( __snake_case : str) -> str:
if "://" in dataset_path:
lowerCAmelCase_ = dataset_path.split('''://''')[1]
return dataset_path
def snake_case_ ( __snake_case : fsspec.AbstractFileSystem) -> bool:
if fs is not None and fs.protocol != "file":
return True
else:
return False
def snake_case_ ( __snake_case : fsspec.AbstractFileSystem , __snake_case : str , __snake_case : str) -> Union[str, Any]:
lowerCAmelCase_ = not is_remote_filesystem(__snake_case)
if is_local:
# LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory
shutil.move(fs._strip_protocol(__snake_case) , fs._strip_protocol(__snake_case))
else:
fs.mv(__snake_case , __snake_case , recursive=__snake_case)
def snake_case_ ( ) -> None:
if hasattr(fsspec.asyn , '''reset_lock'''):
# for future fsspec>2022.05.0
fsspec.asyn.reset_lock()
else:
lowerCAmelCase_ = None
lowerCAmelCase_ = None
lowerCAmelCase_ = threading.Lock()
| 606 | '''simple docstring'''
import os
import pytest
import yaml
from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
'''files''' , [
['''full:README.md''', '''dataset_infos.json'''],
['''empty:README.md''', '''dataset_infos.json'''],
['''dataset_infos.json'''],
['''full:README.md'''],
] , )
def snake_case_ ( __snake_case : Any , __snake_case : int) -> int:
lowerCAmelCase_ = tmp_path_factory.mktemp('''dset_infos_dir''')
if "full:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''') as f:
f.write('''---\ndataset_info:\n dataset_size: 42\n---''')
if "empty:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''') as f:
f.write('''''')
# we want to support dataset_infos.json for backward compatibility
if "dataset_infos.json" in files:
with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''') as f:
f.write('''{"default": {"dataset_size": 42}}''')
lowerCAmelCase_ = DatasetInfosDict.from_directory(__snake_case)
assert dataset_infos
assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
'''dataset_info''' , [
DatasetInfo(),
DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''')}) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ),
] , )
def snake_case_ ( __snake_case : List[str] , __snake_case : DatasetInfo) -> str:
lowerCAmelCase_ = str(__snake_case)
dataset_info.write_to_directory(__snake_case)
lowerCAmelCase_ = DatasetInfo.from_directory(__snake_case)
assert dataset_info == reloaded
assert os.path.exists(os.path.join(__snake_case , '''dataset_info.json'''))
def snake_case_ ( ) -> str:
lowerCAmelCase_ = DatasetInfo(
description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''')}) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , )
lowerCAmelCase_ = dataset_info._to_yaml_dict()
assert sorted(__snake_case) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML)
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
assert key in dataset_info_yaml_dict
assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str))
lowerCAmelCase_ = yaml.safe_dump(__snake_case)
lowerCAmelCase_ = yaml.safe_load(__snake_case)
assert dataset_info_yaml_dict == reloaded
def snake_case_ ( ) -> Optional[int]:
lowerCAmelCase_ = DatasetInfo()
lowerCAmelCase_ = dataset_info._to_yaml_dict()
assert dataset_info_yaml_dict == {}
@pytest.mark.parametrize(
'''dataset_infos_dict''' , [
DatasetInfosDict(),
DatasetInfosDict({'''default''': DatasetInfo()}),
DatasetInfosDict({'''my_config_name''': DatasetInfo()}),
DatasetInfosDict(
{
'''default''': DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''')}) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , )
}),
DatasetInfosDict(
{
'''v1''': DatasetInfo(dataset_size=42),
'''v2''': DatasetInfo(dataset_size=1337),
}),
] , )
def snake_case_ ( __snake_case : List[Any] , __snake_case : DatasetInfosDict) -> List[str]:
lowerCAmelCase_ = str(__snake_case)
dataset_infos_dict.write_to_directory(__snake_case)
lowerCAmelCase_ = DatasetInfosDict.from_directory(__snake_case)
# the config_name of the dataset_infos_dict take over the attribute
for config_name, dataset_info in dataset_infos_dict.items():
lowerCAmelCase_ = config_name
# the yaml representation doesn't include fields like description or citation
# so we just test that we can recover what we can from the yaml
lowerCAmelCase_ = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict())
assert dataset_infos_dict == reloaded
if dataset_infos_dict:
assert os.path.exists(os.path.join(__snake_case , '''README.md'''))
| 606 | 1 |
import baseaa
def lowercase ( __A : str ) -> bytes:
'''simple docstring'''
return baseaa.baaencode(string.encode("""utf-8""" ) )
def lowercase ( __A : bytes ) -> str:
'''simple docstring'''
return baseaa.baadecode(__A ).decode("""utf-8""" )
if __name__ == "__main__":
__lowercase : int = '''Hello World!'''
__lowercase : Union[str, Any] = baseaa_encode(test)
print(encoded)
__lowercase : Any = baseaa_decode(encoded)
print(decoded)
| 36 |
"""simple docstring"""
def __UpperCamelCase ( SCREAMING_SNAKE_CASE = 1_00_00_00 ) -> int:
"""simple docstring"""
__snake_case = 1
__snake_case = 1
__snake_case = {1: 1}
for inputa in range(2 , SCREAMING_SNAKE_CASE ):
__snake_case = 0
__snake_case = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
__snake_case = (3 * number) + 1
counter += 1
if inputa not in counters:
__snake_case = counter
if counter > pre_counter:
__snake_case = inputa
__snake_case = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 163 | 0 |
import collections
import json
import math
import os
import re
import time
from fnmatch import fnmatch
from typing import Dict
import requests
from slack_sdk import WebClient
_lowerCamelCase =WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"])
def snake_case__ ( lowerCAmelCase_ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE =test_results.split(' ' )
SCREAMING_SNAKE_CASE =0
SCREAMING_SNAKE_CASE =0
# When the output is short enough, the output is surrounded by = signs: "== OUTPUT =="
# When it is too long, those signs are not present.
SCREAMING_SNAKE_CASE =expressions[-2] if '=' in expressions[-1] else expressions[-1]
for i, expression in enumerate(lowerCAmelCase_ ):
if "failed" in expression:
failed += int(expressions[i - 1] )
if "passed" in expression:
success += int(expressions[i - 1] )
return failed, success, time_spent
def snake_case__ ( lowerCAmelCase_ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE ={}
SCREAMING_SNAKE_CASE =None
SCREAMING_SNAKE_CASE =False
for line in failures_short_lines.split('\n' ):
if re.search(r'_ \[doctest\]', lowerCAmelCase_ ):
SCREAMING_SNAKE_CASE =True
SCREAMING_SNAKE_CASE =line.split(' ' )[2]
elif in_error and not line.split(' ' )[0].isdigit():
SCREAMING_SNAKE_CASE =line
SCREAMING_SNAKE_CASE =False
return failures
class a_ :
"""simple docstring"""
def __init__( self : Dict ,snake_case : str ,snake_case : Dict ):
SCREAMING_SNAKE_CASE =title
SCREAMING_SNAKE_CASE =doc_test_results['time_spent'].split(',' )[0]
SCREAMING_SNAKE_CASE =doc_test_results['success']
SCREAMING_SNAKE_CASE =doc_test_results['failures']
SCREAMING_SNAKE_CASE =self.n_success + self.n_failures
# Failures and success of the modeling tests
SCREAMING_SNAKE_CASE =doc_test_results
@property
def _lowerCAmelCase ( self : List[str] ):
SCREAMING_SNAKE_CASE =[self._time_spent]
SCREAMING_SNAKE_CASE =0
for time in time_spent:
SCREAMING_SNAKE_CASE =time.split(':' )
# Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute.
if len(snake_case ) == 1:
SCREAMING_SNAKE_CASE =[0, 0, time_parts[0]]
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] )
total_secs += hours * 3600 + minutes * 60 + seconds
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60
return f'{int(snake_case )}h{int(snake_case )}m{int(snake_case )}s'
@property
def _lowerCAmelCase ( self : Union[str, Any] ):
return {"type": "header", "text": {"type": "plain_text", "text": self.title}}
@property
def _lowerCAmelCase ( self : List[Any] ):
return {
"type": "section",
"text": {
"type": "plain_text",
"text": f'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.',
"emoji": True,
},
"accessory": {
"type": "button",
"text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
"url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}',
},
}
@property
def _lowerCAmelCase ( self : List[Any] ):
return {
"type": "section",
"text": {
"type": "plain_text",
"text": (
f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in'
f' {self.time}.'
),
"emoji": True,
},
"accessory": {
"type": "button",
"text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
"url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}',
},
}
@property
def _lowerCAmelCase ( self : Tuple ):
SCREAMING_SNAKE_CASE =40
SCREAMING_SNAKE_CASE ={k: v['failed'] for k, v in doc_test_results.items() if isinstance(snake_case ,snake_case )}
SCREAMING_SNAKE_CASE =''
for category, failures in category_failures.items():
if len(snake_case ) == 0:
continue
if report != "":
report += "\n\n"
report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n"
report += "`"
report += "`\n`".join(snake_case )
report += "`"
return {
"type": "section",
"text": {
"type": "mrkdwn",
"text": f'The following examples had failures:\n\n\n{report}\n',
},
}
@property
def _lowerCAmelCase ( self : int ):
SCREAMING_SNAKE_CASE =[self.header]
if self.n_failures > 0:
blocks.append(self.failures )
if self.n_failures > 0:
blocks.extend([self.category_failures] )
if self.n_failures == 0:
blocks.append(self.no_failures )
return json.dumps(snake_case )
@staticmethod
def _lowerCAmelCase ( ):
SCREAMING_SNAKE_CASE =[
{
'type': 'section',
'text': {
'type': 'plain_text',
'text': 'There was an issue running the tests.',
},
'accessory': {
'type': 'button',
'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True},
'url': f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}',
},
}
]
print('Sending the following payload' )
print(json.dumps({'blocks': json.loads(snake_case )} ) )
client.chat_postMessage(
channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] ,text='There was an issue running the tests.' ,blocks=snake_case ,)
def _lowerCAmelCase ( self : Dict ):
print('Sending the following payload' )
print(json.dumps({'blocks': json.loads(self.payload )} ) )
SCREAMING_SNAKE_CASE =f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.'
SCREAMING_SNAKE_CASE =client.chat_postMessage(
channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] ,blocks=self.payload ,text=snake_case ,)
def _lowerCAmelCase ( self : Optional[int] ,snake_case : Optional[int] ,snake_case : List[str] ,snake_case : Tuple ,snake_case : List[str] ):
SCREAMING_SNAKE_CASE =''
for key, value in failures.items():
SCREAMING_SNAKE_CASE =value[:200] + ' [Truncated]' if len(snake_case ) > 250 else value
failures_text += f'*{key}*\n_{value}_\n\n'
SCREAMING_SNAKE_CASE =job_name
SCREAMING_SNAKE_CASE ={'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}}
if job_link is not None:
SCREAMING_SNAKE_CASE ={
'type': 'button',
'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True},
'url': job_link,
}
return [
{"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}},
content,
{"type": "section", "text": {"type": "mrkdwn", "text": failures_text}},
]
def _lowerCAmelCase ( self : Any ):
if self.thread_ts is None:
raise ValueError('Can only post reply if a post has been made.' )
SCREAMING_SNAKE_CASE =self.doc_test_results.pop('job_link' )
self.doc_test_results.pop('failures' )
self.doc_test_results.pop('success' )
self.doc_test_results.pop('time_spent' )
SCREAMING_SNAKE_CASE =sorted(self.doc_test_results.items() ,key=lambda snake_case : t[0] )
for job, job_result in sorted_dict:
if len(job_result['failures'] ):
SCREAMING_SNAKE_CASE =f'*Num failures* :{len(job_result["failed"] )} \n'
SCREAMING_SNAKE_CASE =job_result['failures']
SCREAMING_SNAKE_CASE =self.get_reply_blocks(snake_case ,snake_case ,snake_case ,text=snake_case )
print('Sending the following reply' )
print(json.dumps({'blocks': blocks} ) )
client.chat_postMessage(
channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] ,text=f'Results for {job}' ,blocks=snake_case ,thread_ts=self.thread_ts['ts'] ,)
time.sleep(1 )
def snake_case__ ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE =os.environ['GITHUB_RUN_ID']
SCREAMING_SNAKE_CASE =F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100'
SCREAMING_SNAKE_CASE =requests.get(lowerCAmelCase_ ).json()
SCREAMING_SNAKE_CASE ={}
try:
jobs.update({job['name']: job['html_url'] for job in result['jobs']} )
SCREAMING_SNAKE_CASE =math.ceil((result['total_count'] - 100) / 100 )
for i in range(lowerCAmelCase_ ):
SCREAMING_SNAKE_CASE =requests.get(url + F'&page={i + 2}' ).json()
jobs.update({job['name']: job['html_url'] for job in result['jobs']} )
return jobs
except Exception as e:
print('Unknown error, could not fetch links.', lowerCAmelCase_ )
return {}
def snake_case__ ( lowerCAmelCase_ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE ={}
if os.path.exists(lowerCAmelCase_ ):
SCREAMING_SNAKE_CASE =os.listdir(lowerCAmelCase_ )
for file in files:
try:
with open(os.path.join(lowerCAmelCase_, lowerCAmelCase_ ), encoding='utf-8' ) as f:
SCREAMING_SNAKE_CASE =f.read()
except UnicodeDecodeError as e:
raise ValueError(F'Could not open {os.path.join(lowerCAmelCase_, lowerCAmelCase_ )}.' ) from e
return _artifact
def snake_case__ ( ):
"""simple docstring"""
class a_ :
"""simple docstring"""
def __init__( self : Optional[int] ,snake_case : str ):
SCREAMING_SNAKE_CASE =name
SCREAMING_SNAKE_CASE =[]
def __str__( self : Optional[Any] ):
return self.name
def _lowerCAmelCase ( self : Tuple ,snake_case : str ):
self.paths.append({'name': self.name, 'path': path} )
SCREAMING_SNAKE_CASE ={}
SCREAMING_SNAKE_CASE =filter(os.path.isdir, os.listdir() )
for directory in directories:
SCREAMING_SNAKE_CASE =directory
if artifact_name not in _available_artifacts:
SCREAMING_SNAKE_CASE =Artifact(lowerCAmelCase_ )
_available_artifacts[artifact_name].add_path(lowerCAmelCase_ )
return _available_artifacts
if __name__ == "__main__":
_lowerCamelCase =get_job_links()
_lowerCamelCase =retrieve_available_artifacts()
_lowerCamelCase =collections.OrderedDict(
[
("*.py", "API Examples"),
("*.md", "MD Examples"),
]
)
# This dict will contain all the information relative to each doc test category:
# - failed: list of failed tests
# - failures: dict in the format 'test': 'error_message'
_lowerCamelCase ={
v: {
"failed": [],
"failures": {},
}
for v in docs.values()
}
# Link to the GitHub Action job
_lowerCamelCase =github_actions_job_links.get("run_doctests")
_lowerCamelCase =available_artifacts["doc_tests_gpu_test_reports"].paths[0]
_lowerCamelCase =retrieve_artifact(artifact_path["name"])
if "stats" in artifact:
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase =handle_test_results(artifact["stats"])
_lowerCamelCase =failed
_lowerCamelCase =success
_lowerCamelCase =time_spent[1:-1] + ", "
_lowerCamelCase =extract_first_line_failure(artifact["failures_short"])
for line in artifact["summary_short"].split("\n"):
if re.search("FAILED", line):
_lowerCamelCase =line.replace("FAILED ", "")
_lowerCamelCase =line.split()[0].replace("\n", "")
if "::" in line:
_lowerCamelCase , _lowerCamelCase =line.split("::")
else:
_lowerCamelCase , _lowerCamelCase =line, line
for file_regex in docs.keys():
if fnmatch(file_path, file_regex):
_lowerCamelCase =docs[file_regex]
doc_test_results[category]["failed"].append(test)
_lowerCamelCase =all_failures[test] if test in all_failures else "N/A"
_lowerCamelCase =failure
break
_lowerCamelCase =Message("🤗 Results of the doc tests.", doc_test_results)
message.post()
message.post_reply()
| 716 |
import argparse
from transformers import (
TapasConfig,
TapasForMaskedLM,
TapasForQuestionAnswering,
TapasForSequenceClassification,
TapasModel,
TapasTokenizer,
load_tf_weights_in_tapas,
)
from transformers.utils import logging
logging.set_verbosity_info()
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE =TapasConfig.from_json_file(lowerCAmelCase_ )
# set absolute/relative position embeddings parameter
SCREAMING_SNAKE_CASE =reset_position_index_per_cell
# set remaining parameters of TapasConfig as well as the model based on the task
if task == "SQA":
SCREAMING_SNAKE_CASE =TapasForQuestionAnswering(config=lowerCAmelCase_ )
elif task == "WTQ":
# run_task_main.py hparams
SCREAMING_SNAKE_CASE =4
SCREAMING_SNAKE_CASE =True
# hparam_utils.py hparams
SCREAMING_SNAKE_CASE =0.66_4694
SCREAMING_SNAKE_CASE =0.20_7951
SCREAMING_SNAKE_CASE =0.12_1194
SCREAMING_SNAKE_CASE =True
SCREAMING_SNAKE_CASE =True
SCREAMING_SNAKE_CASE =False
SCREAMING_SNAKE_CASE =0.035_2513
SCREAMING_SNAKE_CASE =TapasForQuestionAnswering(config=lowerCAmelCase_ )
elif task == "WIKISQL_SUPERVISED":
# run_task_main.py hparams
SCREAMING_SNAKE_CASE =4
SCREAMING_SNAKE_CASE =False
# hparam_utils.py hparams
SCREAMING_SNAKE_CASE =36.4519
SCREAMING_SNAKE_CASE =0.90_3421
SCREAMING_SNAKE_CASE =222.088
SCREAMING_SNAKE_CASE =True
SCREAMING_SNAKE_CASE =True
SCREAMING_SNAKE_CASE =True
SCREAMING_SNAKE_CASE =0.76_3141
SCREAMING_SNAKE_CASE =TapasForQuestionAnswering(config=lowerCAmelCase_ )
elif task == "TABFACT":
SCREAMING_SNAKE_CASE =TapasForSequenceClassification(config=lowerCAmelCase_ )
elif task == "MLM":
SCREAMING_SNAKE_CASE =TapasForMaskedLM(config=lowerCAmelCase_ )
elif task == "INTERMEDIATE_PRETRAINING":
SCREAMING_SNAKE_CASE =TapasModel(config=lowerCAmelCase_ )
else:
raise ValueError(F'Task {task} not supported.' )
print(F'Building PyTorch model from configuration: {config}' )
# Load weights from tf checkpoint
load_tf_weights_in_tapas(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ )
# Save pytorch-model (weights and configuration)
print(F'Save PyTorch model to {pytorch_dump_path}' )
model.save_pretrained(lowerCAmelCase_ )
# Save tokenizer files
print(F'Save tokenizer files to {pytorch_dump_path}' )
SCREAMING_SNAKE_CASE =TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + 'vocab.txt', model_max_length=512 )
tokenizer.save_pretrained(lowerCAmelCase_ )
print('Used relative position embeddings:', model.config.reset_position_index_per_cell )
if __name__ == "__main__":
_lowerCamelCase =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--task", default="SQA", type=str, help="Model task for which to convert a checkpoint. Defaults to SQA."
)
parser.add_argument(
"--reset_position_index_per_cell",
default=False,
action="store_true",
help="Whether to use relative position embeddings or not. Defaults to True.",
)
parser.add_argument(
"--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
)
parser.add_argument(
"--tapas_config_file",
default=None,
type=str,
required=True,
help=(
"The config json file corresponding to the pre-trained TAPAS model. \n"
"This specifies the model architecture."
),
)
parser.add_argument(
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
_lowerCamelCase =parser.parse_args()
convert_tf_checkpoint_to_pytorch(
args.task,
args.reset_position_index_per_cell,
args.tf_checkpoint_path,
args.tapas_config_file,
args.pytorch_dump_path,
)
| 252 | 0 |
"""simple docstring"""
def __A ( ) -> Union[str, Any]:
__a : Union[str, Any] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
__a : int = 6
__a : Tuple = 1
__a : List[str] = 19_01
__a : Tuple = 0
while year < 20_01:
day += 7
if (year % 4 == 0 and year % 1_00 != 0) or (year % 4_00 == 0):
if day > days_per_month[month - 1] and month != 2:
month += 1
__a : Tuple = day - days_per_month[month - 2]
elif day > 29 and month == 2:
month += 1
__a : Optional[Any] = day - 29
else:
if day > days_per_month[month - 1]:
month += 1
__a : Union[str, Any] = day - days_per_month[month - 2]
if month > 12:
year += 1
__a : Union[str, Any] = 1
if year < 20_01 and day == 1:
sundays += 1
return sundays
if __name__ == "__main__":
print(solution()) | 52 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
snake_case_ : str = logging.get_logger(__name__)
snake_case_ : Any = {
"""google/vivit-b-16x2-kinetics400""": (
"""https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json"""
),
# See all Vivit models at https://huggingface.co/models?filter=vivit
}
class snake_case__ ( lowerCAmelCase_ ):
SCREAMING_SNAKE_CASE__ = '''vivit'''
def __init__( self : Union[str, Any] , lowercase : int=2_24 , lowercase : Tuple=32 , lowercase : str=[2, 16, 16] , lowercase : str=3 , lowercase : Dict=7_68 , lowercase : Union[str, Any]=12 , lowercase : List[Any]=12 , lowercase : Dict=30_72 , lowercase : int="gelu_fast" , lowercase : Dict=0.0 , lowercase : Dict=0.0 , lowercase : List[str]=0.0_2 , lowercase : Tuple=1E-06 , lowercase : Any=True , **lowercase : Union[str, Any] , ):
'''simple docstring'''
UpperCAmelCase : List[str] = hidden_size
UpperCAmelCase : int = num_hidden_layers
UpperCAmelCase : int = num_attention_heads
UpperCAmelCase : List[str] = intermediate_size
UpperCAmelCase : List[str] = hidden_act
UpperCAmelCase : Dict = hidden_dropout_prob
UpperCAmelCase : Dict = attention_probs_dropout_prob
UpperCAmelCase : Dict = initializer_range
UpperCAmelCase : Any = layer_norm_eps
UpperCAmelCase : List[Any] = image_size
UpperCAmelCase : str = num_frames
UpperCAmelCase : str = tubelet_size
UpperCAmelCase : int = num_channels
UpperCAmelCase : Optional[int] = qkv_bias
super().__init__(**lowercase )
| 595 | 0 |
'''simple docstring'''
import collections
import inspect
import unittest
from typing import Dict, List, Tuple
from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available
from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import MaskFormerSwinBackbone
from transformers.models.maskformer import MaskFormerSwinModel
class UpperCAmelCase_ :
"""simple docstring"""
def __init__( self : Optional[int] , UpperCAmelCase : int , UpperCAmelCase : Optional[int]=13 , UpperCAmelCase : str=32 , UpperCAmelCase : Any=2 , UpperCAmelCase : Dict=3 , UpperCAmelCase : str=16 , UpperCAmelCase : Union[str, Any]=[1, 2, 1] , UpperCAmelCase : List[str]=[2, 2, 4] , UpperCAmelCase : Tuple=2 , UpperCAmelCase : Tuple=2.0 , UpperCAmelCase : Optional[Any]=True , UpperCAmelCase : Dict=0.0 , UpperCAmelCase : Tuple=0.0 , UpperCAmelCase : List[str]=0.1 , UpperCAmelCase : str="gelu" , UpperCAmelCase : Dict=False , UpperCAmelCase : Tuple=True , UpperCAmelCase : str=0.0_2 , UpperCAmelCase : List[str]=1e-5 , UpperCAmelCase : Any=True , UpperCAmelCase : Optional[Any]=None , UpperCAmelCase : Optional[Any]=True , UpperCAmelCase : Dict=10 , UpperCAmelCase : Dict=8 , UpperCAmelCase : str=["stage1", "stage2", "stage3"] , UpperCAmelCase : List[str]=[1, 2, 3] , ) -> Any:
'''simple docstring'''
lowercase : int =parent
lowercase : List[str] =batch_size
lowercase : List[str] =image_size
lowercase : Optional[int] =patch_size
lowercase : int =num_channels
lowercase : Union[str, Any] =embed_dim
lowercase : Tuple =depths
lowercase : List[Any] =num_heads
lowercase : int =window_size
lowercase : int =mlp_ratio
lowercase : Optional[Any] =qkv_bias
lowercase : List[Any] =hidden_dropout_prob
lowercase : Optional[int] =attention_probs_dropout_prob
lowercase : Any =drop_path_rate
lowercase : Optional[int] =hidden_act
lowercase : Tuple =use_absolute_embeddings
lowercase : Union[str, Any] =patch_norm
lowercase : str =layer_norm_eps
lowercase : List[str] =initializer_range
lowercase : Optional[int] =is_training
lowercase : str =scope
lowercase : Tuple =use_labels
lowercase : List[str] =type_sequence_label_size
lowercase : Optional[int] =encoder_stride
lowercase : str =out_features
lowercase : Optional[Any] =out_indices
def A__ ( self : str ) -> Union[str, Any]:
'''simple docstring'''
lowercase : str =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowercase : str =None
if self.use_labels:
lowercase : List[str] =ids_tensor([self.batch_size] , self.type_sequence_label_size )
lowercase : List[str] =self.get_config()
return config, pixel_values, labels
def A__ ( self : Any ) -> Optional[Any]:
'''simple docstring'''
return MaskFormerSwinConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , )
def A__ ( self : int , UpperCAmelCase : Optional[int] , UpperCAmelCase : str , UpperCAmelCase : Any ) -> Union[str, Any]:
'''simple docstring'''
lowercase : Any =MaskFormerSwinModel(config=UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
lowercase : Dict =model(UpperCAmelCase )
lowercase : Optional[Any] =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
lowercase : List[str] =int(config.embed_dim * 2 ** (len(config.depths ) - 1) )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) )
def A__ ( self : Optional[int] , UpperCAmelCase : Tuple , UpperCAmelCase : int , UpperCAmelCase : Optional[Any] ) -> List[str]:
'''simple docstring'''
lowercase : Any =MaskFormerSwinBackbone(config=UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
lowercase : str =model(UpperCAmelCase )
# verify feature maps
self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) )
self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] )
# verify channels
self.parent.assertEqual(len(model.channels ) , len(config.out_features ) )
self.parent.assertListEqual(model.channels , [16, 32, 64] )
# verify ValueError
with self.parent.assertRaises(UpperCAmelCase ):
lowercase : Dict =['''stem''']
lowercase : str =MaskFormerSwinBackbone(config=UpperCAmelCase )
def A__ ( self : Optional[int] ) -> Optional[int]:
'''simple docstring'''
lowercase : Tuple =self.prepare_config_and_inputs()
lowercase , lowercase , lowercase : List[Any] =config_and_inputs
lowercase : Any ={'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class UpperCAmelCase_ ( __A , __A , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = (
(
MaskFormerSwinModel,
MaskFormerSwinBackbone,
)
if is_torch_available()
else ()
)
UpperCamelCase_ = {'''feature-extraction''': MaskFormerSwinModel} if is_torch_available() else {}
UpperCamelCase_ = False
UpperCamelCase_ = False
UpperCamelCase_ = False
UpperCamelCase_ = False
UpperCamelCase_ = False
def A__ ( self : Any ) -> str:
'''simple docstring'''
lowercase : Optional[Any] =MaskFormerSwinModelTester(self )
lowercase : List[str] =ConfigTester(self , config_class=UpperCAmelCase , embed_dim=37 )
@require_torch_multi_gpu
@unittest.skip(
reason=(
'''`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with'''
''' `nn.DataParallel`'''
) )
def A__ ( self : Any ) -> str:
'''simple docstring'''
pass
def A__ ( self : str ) -> Optional[int]:
'''simple docstring'''
self.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def A__ ( self : List[Any] ) -> Optional[Any]:
'''simple docstring'''
return
def A__ ( self : Optional[int] ) -> Tuple:
'''simple docstring'''
lowercase : Optional[int] =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCAmelCase )
def A__ ( self : Optional[int] ) -> Dict:
'''simple docstring'''
lowercase : List[Any] =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_backbone(*UpperCAmelCase )
@unittest.skip('''Swin does not use inputs_embeds''' )
def A__ ( self : Optional[int] ) -> Dict:
'''simple docstring'''
pass
@unittest.skip('''Swin does not support feedforward chunking''' )
def A__ ( self : Tuple ) -> Dict:
'''simple docstring'''
pass
def A__ ( self : str ) -> str:
'''simple docstring'''
lowercase , lowercase : int =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase : Optional[Any] =model_class(UpperCAmelCase )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
lowercase : int =model.get_output_embeddings()
self.assertTrue(x is None or isinstance(UpperCAmelCase , nn.Linear ) )
def A__ ( self : Any ) -> str:
'''simple docstring'''
lowercase , lowercase : Any =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase : Optional[Any] =model_class(UpperCAmelCase )
lowercase : List[Any] =inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowercase : List[Any] =[*signature.parameters.keys()]
lowercase : Optional[Any] =['''pixel_values''']
self.assertListEqual(arg_names[:1] , UpperCAmelCase )
@unittest.skip(reason='''MaskFormerSwin is only used as backbone and doesn\'t support output_attentions''' )
def A__ ( self : str ) -> Any:
'''simple docstring'''
pass
@unittest.skip(reason='''MaskFormerSwin is only used as an internal backbone''' )
def A__ ( self : List[str] ) -> Optional[Any]:
'''simple docstring'''
pass
def A__ ( self : Optional[Any] , UpperCAmelCase : str , UpperCAmelCase : Tuple , UpperCAmelCase : List[str] , UpperCAmelCase : Dict ) -> Any:
'''simple docstring'''
lowercase : Tuple =model_class(UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
with torch.no_grad():
lowercase : Union[str, Any] =model(**self._prepare_for_class(UpperCAmelCase , UpperCAmelCase ) )
lowercase : Tuple =outputs.hidden_states
lowercase : Union[str, Any] =getattr(
self.model_tester , '''expected_num_hidden_layers''' , len(self.model_tester.depths ) + 1 )
self.assertEqual(len(UpperCAmelCase ) , UpperCAmelCase )
# Swin has a different seq_length
lowercase : int =(
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
lowercase : Dict =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , )
def A__ ( self : List[Any] ) -> Optional[int]:
'''simple docstring'''
lowercase , lowercase : List[str] =self.model_tester.prepare_config_and_inputs_for_common()
lowercase : Dict =(
self.model_tester.image_size
if isinstance(self.model_tester.image_size , collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
for model_class in self.all_model_classes:
lowercase : List[Any] =True
self.check_hidden_states_output(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowercase : Union[str, Any] =True
self.check_hidden_states_output(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase )
def A__ ( self : Union[str, Any] ) -> Optional[int]:
'''simple docstring'''
lowercase , lowercase : int =self.model_tester.prepare_config_and_inputs_for_common()
lowercase : List[str] =3
lowercase : List[Any] =(
self.model_tester.image_size
if isinstance(self.model_tester.image_size , collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
lowercase : List[str] =(
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
lowercase : Optional[Any] =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
lowercase : Optional[int] =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
for model_class in self.all_model_classes:
lowercase : Union[str, Any] =True
self.check_hidden_states_output(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , (padded_height, padded_width) )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowercase : Any =True
self.check_hidden_states_output(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , (padded_height, padded_width) )
@unittest.skip(reason='''MaskFormerSwin doesn\'t have pretrained checkpoints''' )
def A__ ( self : str ) -> List[str]:
'''simple docstring'''
pass
@unittest.skip(reason='''This will be fixed once MaskFormerSwin is replaced by native Swin''' )
def A__ ( self : int ) -> List[Any]:
'''simple docstring'''
pass
@unittest.skip(reason='''This will be fixed once MaskFormerSwin is replaced by native Swin''' )
def A__ ( self : Union[str, Any] ) -> str:
'''simple docstring'''
pass
def A__ ( self : Optional[Any] ) -> Any:
'''simple docstring'''
lowercase , lowercase : int =self.model_tester.prepare_config_and_inputs_for_common()
def set_nan_tensor_to_zero(UpperCAmelCase : List[str] ):
lowercase : Optional[int] =0
return t
def check_equivalence(UpperCAmelCase : Optional[int] , UpperCAmelCase : str , UpperCAmelCase : Dict , UpperCAmelCase : Optional[int]={} ):
with torch.no_grad():
lowercase : int =model(**UpperCAmelCase , return_dict=UpperCAmelCase , **UpperCAmelCase )
lowercase : Tuple =model(**UpperCAmelCase , return_dict=UpperCAmelCase , **UpperCAmelCase ).to_tuple()
def recursive_check(UpperCAmelCase : int , UpperCAmelCase : Tuple ):
if isinstance(UpperCAmelCase , (List, Tuple) ):
for tuple_iterable_value, dict_iterable_value in zip(UpperCAmelCase , UpperCAmelCase ):
recursive_check(UpperCAmelCase , UpperCAmelCase )
elif isinstance(UpperCAmelCase , UpperCAmelCase ):
for tuple_iterable_value, dict_iterable_value in zip(
tuple_object.values() , dict_object.values() ):
recursive_check(UpperCAmelCase , UpperCAmelCase )
elif tuple_object is None:
return
else:
self.assertTrue(
torch.allclose(
set_nan_tensor_to_zero(UpperCAmelCase ) , set_nan_tensor_to_zero(UpperCAmelCase ) , atol=1e-5 ) , msg=(
'''Tuple and dict output are not equal. Difference:'''
f' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:'
f' {torch.isnan(UpperCAmelCase ).any()} and `inf`: {torch.isinf(UpperCAmelCase )}. Dict has'
f' `nan`: {torch.isnan(UpperCAmelCase ).any()} and `inf`: {torch.isinf(UpperCAmelCase )}.'
) , )
recursive_check(UpperCAmelCase , UpperCAmelCase )
for model_class in self.all_model_classes:
lowercase : Any =model_class(UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
lowercase : List[Any] =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase )
lowercase : Union[str, Any] =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase )
check_equivalence(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase )
lowercase : Optional[int] =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase , return_labels=UpperCAmelCase )
lowercase : List[str] =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase , return_labels=UpperCAmelCase )
check_equivalence(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase )
lowercase : Union[str, Any] =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase )
lowercase : List[str] =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase )
check_equivalence(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , {'''output_hidden_states''': True} )
lowercase : int =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase , return_labels=UpperCAmelCase )
lowercase : List[Any] =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase , return_labels=UpperCAmelCase )
check_equivalence(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , {'''output_hidden_states''': True} )
@require_torch
class UpperCAmelCase_ ( unittest.TestCase , __A ):
"""simple docstring"""
UpperCamelCase_ = (MaskFormerSwinBackbone,) if is_torch_available() else ()
UpperCamelCase_ = MaskFormerSwinConfig
def A__ ( self : Optional[int] ) -> Dict:
'''simple docstring'''
lowercase : Optional[Any] =MaskFormerSwinModelTester(self )
def A__ ( self : List[str] ) -> Tuple:
'''simple docstring'''
lowercase , lowercase : Any =self.model_tester.prepare_config_and_inputs_for_common()
lowercase : Tuple =inputs_dict['''pixel_values'''].shape[0]
for backbone_class in self.all_model_classes:
lowercase : str =backbone_class(UpperCAmelCase )
backbone.to(UpperCAmelCase )
backbone.eval()
lowercase : Optional[int] =backbone(**UpperCAmelCase )
# Test default outputs and verify feature maps
self.assertIsInstance(outputs.feature_maps , UpperCAmelCase )
self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) )
for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ):
self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) )
self.assertIsNone(outputs.hidden_states )
self.assertIsNone(outputs.attentions )
# Test output_hidden_states=True
lowercase : List[Any] =backbone(**UpperCAmelCase , output_hidden_states=UpperCAmelCase )
self.assertIsNotNone(outputs.hidden_states )
self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) )
# We skip the stem layer
for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ):
for hidden_state in hidden_states:
# Hidden states are in the format (batch_size, (height * width), n_channels)
lowercase , lowercase , lowercase : str =hidden_state.shape
self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) )
# Test output_attentions=True
if self.has_attentions:
lowercase : str =backbone(**UpperCAmelCase , output_attentions=UpperCAmelCase )
self.assertIsNotNone(outputs.attentions )
| 8 |
'''simple docstring'''
SCREAMING_SNAKE_CASE = 'Alexander Joslin'
import operator as op
from .stack import Stack
def lowercase_ ( __A : str ) -> int:
"""simple docstring"""
lowercase : int ={'''*''': op.mul, '''/''': op.truediv, '''+''': op.add, '''-''': op.sub}
lowercase : Stack[int] =Stack()
lowercase : Stack[str] =Stack()
for i in equation:
if i.isdigit():
# RULE 1
operand_stack.push(int(__A ) )
elif i in operators:
# RULE 2
operator_stack.push(__A )
elif i == ")":
# RULE 4
lowercase : Optional[Any] =operator_stack.peek()
operator_stack.pop()
lowercase : Optional[Any] =operand_stack.peek()
operand_stack.pop()
lowercase : Optional[Any] =operand_stack.peek()
operand_stack.pop()
lowercase : List[str] =operators[opr](__A , __A )
operand_stack.push(__A )
# RULE 5
return operand_stack.peek()
if __name__ == "__main__":
SCREAMING_SNAKE_CASE = '(5 + ((4 * 2) * (2 + 3)))'
# answer = 45
print(f"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
| 8 | 1 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
_UpperCamelCase = logging.get_logger(__name__)
_UpperCamelCase = {
"roberta-base": "https://huggingface.co/roberta-base/resolve/main/config.json",
"roberta-large": "https://huggingface.co/roberta-large/resolve/main/config.json",
"roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/config.json",
"distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/config.json",
"roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json",
"roberta-large-openai-detector": "https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json",
}
class __lowercase (_UpperCAmelCase ):
_UpperCamelCase = """roberta"""
def __init__( self , A_=5_0265 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=2 , A_=0.02 , A_=1e-12 , A_=1 , A_=0 , A_=2 , A_="absolute" , A_=True , A_=None , **A_ , ) ->List[str]:
'''simple docstring'''
super().__init__(pad_token_id=__UpperCamelCase , bos_token_id=__UpperCamelCase , eos_token_id=__UpperCamelCase , **__UpperCamelCase )
__lowerCAmelCase : List[Any] = vocab_size
__lowerCAmelCase : str = hidden_size
__lowerCAmelCase : Optional[Any] = num_hidden_layers
__lowerCAmelCase : Optional[Any] = num_attention_heads
__lowerCAmelCase : Any = hidden_act
__lowerCAmelCase : Any = intermediate_size
__lowerCAmelCase : int = hidden_dropout_prob
__lowerCAmelCase : int = attention_probs_dropout_prob
__lowerCAmelCase : Union[str, Any] = max_position_embeddings
__lowerCAmelCase : Any = type_vocab_size
__lowerCAmelCase : Dict = initializer_range
__lowerCAmelCase : Union[str, Any] = layer_norm_eps
__lowerCAmelCase : Optional[int] = position_embedding_type
__lowerCAmelCase : List[Any] = use_cache
__lowerCAmelCase : Any = classifier_dropout
class __lowercase (_UpperCAmelCase ):
@property
def UpperCamelCase__ ( self ) ->Mapping[str, Mapping[int, str]]:
'''simple docstring'''
if self.task == "multiple-choice":
__lowerCAmelCase : int = {0: '''batch''', 1: '''choice''', 2: '''sequence'''}
else:
__lowerCAmelCase : Union[str, Any] = {0: '''batch''', 1: '''sequence'''}
return OrderedDict(
[
('''input_ids''', dynamic_axis),
('''attention_mask''', dynamic_axis),
] )
| 492 |
"""simple docstring"""
from argparse import ArgumentParser, Namespace
from typing import Any, List, Optional
from ..pipelines import Pipeline, get_supported_tasks, pipeline
from ..utils import logging
from . import BaseTransformersCLICommand
try:
from fastapi import Body, FastAPI, HTTPException
from fastapi.routing import APIRoute
from pydantic import BaseModel
from starlette.responses import JSONResponse
from uvicorn import run
__A : Any = True
except (ImportError, AttributeError):
__A : str = object
def lowercase ( *_SCREAMING_SNAKE_CASE : int , **_SCREAMING_SNAKE_CASE : List[str] ):
'''simple docstring'''
pass
__A : Any = False
__A : Optional[int] = logging.get_logger("transformers-cli/serving")
def lowercase ( _SCREAMING_SNAKE_CASE : Namespace ):
'''simple docstring'''
_UpperCAmelCase = pipeline(
task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , )
return ServeCommand(_SCREAMING_SNAKE_CASE , args.host , args.port , args.workers )
class _a ( lowerCAmelCase):
"""simple docstring"""
UpperCamelCase__ = 42
class _a ( lowerCAmelCase):
"""simple docstring"""
UpperCamelCase__ = 42
UpperCamelCase__ = 42
class _a ( lowerCAmelCase):
"""simple docstring"""
UpperCamelCase__ = 42
class _a ( lowerCAmelCase):
"""simple docstring"""
UpperCamelCase__ = 42
class _a ( lowerCAmelCase):
"""simple docstring"""
@staticmethod
def lowercase__ ( __UpperCamelCase : ArgumentParser )->List[str]:
_UpperCAmelCase = parser.add_parser(
'''serve''' , help='''CLI tool to run inference requests through REST and GraphQL endpoints.''' )
serve_parser.add_argument(
'''--task''' , type=__UpperCamelCase , choices=get_supported_tasks() , help='''The task to run the pipeline on''' , )
serve_parser.add_argument('''--host''' , type=__UpperCamelCase , default='''localhost''' , help='''Interface the server will listen on.''' )
serve_parser.add_argument('''--port''' , type=__UpperCamelCase , default=8_8_8_8 , help='''Port the serving will listen to.''' )
serve_parser.add_argument('''--workers''' , type=__UpperCamelCase , default=1 , help='''Number of http workers''' )
serve_parser.add_argument('''--model''' , type=__UpperCamelCase , help='''Model\'s name or path to stored model.''' )
serve_parser.add_argument('''--config''' , type=__UpperCamelCase , help='''Model\'s config name or path to stored model.''' )
serve_parser.add_argument('''--tokenizer''' , type=__UpperCamelCase , help='''Tokenizer name to use.''' )
serve_parser.add_argument(
'''--device''' , type=__UpperCamelCase , default=-1 , help='''Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)''' , )
serve_parser.set_defaults(func=__UpperCamelCase )
def __init__( self : int , __UpperCamelCase : Pipeline , __UpperCamelCase : str , __UpperCamelCase : int , __UpperCamelCase : int )->Any:
_UpperCAmelCase = pipeline
_UpperCAmelCase = host
_UpperCAmelCase = port
_UpperCAmelCase = workers
if not _serve_dependencies_installed:
raise RuntimeError(
'''Using serve command requires FastAPI and uvicorn. '''
'''Please install transformers with [serving]: pip install "transformers[serving]".'''
'''Or install FastAPI and uvicorn separately.''' )
else:
logger.info(F'Serving model over {host}:{port}' )
_UpperCAmelCase = FastAPI(
routes=[
APIRoute(
'''/''' , self.model_info , response_model=__UpperCamelCase , response_class=__UpperCamelCase , methods=['''GET'''] , ),
APIRoute(
'''/tokenize''' , self.tokenize , response_model=__UpperCamelCase , response_class=__UpperCamelCase , methods=['''POST'''] , ),
APIRoute(
'''/detokenize''' , self.detokenize , response_model=__UpperCamelCase , response_class=__UpperCamelCase , methods=['''POST'''] , ),
APIRoute(
'''/forward''' , self.forward , response_model=__UpperCamelCase , response_class=__UpperCamelCase , methods=['''POST'''] , ),
] , timeout=6_0_0 , )
def lowercase__ ( self : Optional[int] )->Union[str, Any]:
run(self._app , host=self.host , port=self.port , workers=self.workers )
def lowercase__ ( self : int )->int:
return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) )
def lowercase__ ( self : List[Any] , __UpperCamelCase : str = Body(__UpperCamelCase , embed=__UpperCamelCase ) , __UpperCamelCase : bool = Body(__UpperCamelCase , embed=__UpperCamelCase ) )->Any:
try:
_UpperCAmelCase = self._pipeline.tokenizer.tokenize(__UpperCamelCase )
if return_ids:
_UpperCAmelCase = self._pipeline.tokenizer.convert_tokens_to_ids(__UpperCamelCase )
return ServeTokenizeResult(tokens=__UpperCamelCase , tokens_ids=__UpperCamelCase )
else:
return ServeTokenizeResult(tokens=__UpperCamelCase )
except Exception as e:
raise HTTPException(status_code=5_0_0 , detail={'''model''': '''''', '''error''': str(__UpperCamelCase )} )
def lowercase__ ( self : Union[str, Any] , __UpperCamelCase : List[int] = Body(__UpperCamelCase , embed=__UpperCamelCase ) , __UpperCamelCase : bool = Body(__UpperCamelCase , embed=__UpperCamelCase ) , __UpperCamelCase : bool = Body(__UpperCamelCase , embed=__UpperCamelCase ) , )->List[str]:
try:
_UpperCAmelCase = self._pipeline.tokenizer.decode(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
return ServeDeTokenizeResult(model='''''' , text=__UpperCamelCase )
except Exception as e:
raise HTTPException(status_code=5_0_0 , detail={'''model''': '''''', '''error''': str(__UpperCamelCase )} )
async def lowercase__ ( self : int , __UpperCamelCase : List[Any]=Body(__UpperCamelCase , embed=__UpperCamelCase ) )->Tuple:
# Check we don't have empty string
if len(__UpperCamelCase ) == 0:
return ServeForwardResult(output=[] , attention=[] )
try:
# Forward through the model
_UpperCAmelCase = self._pipeline(__UpperCamelCase )
return ServeForwardResult(output=__UpperCamelCase )
except Exception as e:
raise HTTPException(5_0_0 , {'''error''': str(__UpperCamelCase )} )
| 602 | 0 |
'''simple docstring'''
from __future__ import annotations
import time
__lowercase = list[tuple[int, int]]
__lowercase = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
__lowercase = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right
class a__:
'''simple docstring'''
def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase):
"""simple docstring"""
lowerCAmelCase = pos_x
lowerCAmelCase = pos_y
lowerCAmelCase = (pos_y, pos_x)
lowerCAmelCase = goal_x
lowerCAmelCase = goal_y
lowerCAmelCase = parent
class a__:
'''simple docstring'''
def __init__( self , __lowerCAmelCase , __lowerCAmelCase):
"""simple docstring"""
lowerCAmelCase = Node(start[1] , start[0] , goal[1] , goal[0] , __lowerCAmelCase)
lowerCAmelCase = Node(goal[1] , goal[0] , goal[1] , goal[0] , __lowerCAmelCase)
lowerCAmelCase = [self.start]
lowerCAmelCase = False
def a_ ( self):
"""simple docstring"""
while self.node_queue:
lowerCAmelCase = self.node_queue.pop(0)
if current_node.pos == self.target.pos:
lowerCAmelCase = True
return self.retrace_path(__lowerCAmelCase)
lowerCAmelCase = self.get_successors(__lowerCAmelCase)
for node in successors:
self.node_queue.append(__lowerCAmelCase)
if not self.reached:
return [self.start.pos]
return None
def a_ ( self , __lowerCAmelCase):
"""simple docstring"""
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(__lowerCAmelCase) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(__lowerCAmelCase , __lowerCAmelCase , self.target.pos_y , self.target.pos_x , __lowerCAmelCase))
return successors
def a_ ( self , __lowerCAmelCase):
"""simple docstring"""
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
class a__:
'''simple docstring'''
def __init__( self , __lowerCAmelCase , __lowerCAmelCase):
"""simple docstring"""
lowerCAmelCase = BreadthFirstSearch(__lowerCAmelCase , __lowerCAmelCase)
lowerCAmelCase = BreadthFirstSearch(__lowerCAmelCase , __lowerCAmelCase)
lowerCAmelCase = False
def a_ ( self):
"""simple docstring"""
while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
lowerCAmelCase = self.fwd_bfs.node_queue.pop(0)
lowerCAmelCase = self.bwd_bfs.node_queue.pop(0)
if current_bwd_node.pos == current_fwd_node.pos:
lowerCAmelCase = True
return self.retrace_bidirectional_path(
__lowerCAmelCase , __lowerCAmelCase)
lowerCAmelCase = current_bwd_node
lowerCAmelCase = current_fwd_node
lowerCAmelCase = {
self.fwd_bfs: self.fwd_bfs.get_successors(__lowerCAmelCase),
self.bwd_bfs: self.bwd_bfs.get_successors(__lowerCAmelCase),
}
for bfs in [self.fwd_bfs, self.bwd_bfs]:
for node in successors[bfs]:
bfs.node_queue.append(__lowerCAmelCase)
if not self.reached:
return [self.fwd_bfs.start.pos]
return None
def a_ ( self , __lowerCAmelCase , __lowerCAmelCase):
"""simple docstring"""
lowerCAmelCase = self.fwd_bfs.retrace_path(__lowerCAmelCase)
lowerCAmelCase = self.bwd_bfs.retrace_path(__lowerCAmelCase)
bwd_path.pop()
bwd_path.reverse()
lowerCAmelCase = fwd_path + bwd_path
return path
if __name__ == "__main__":
# all coordinates are given in format [y,x]
import doctest
doctest.testmod()
__lowercase = (0, 0)
__lowercase = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
__lowercase = time.time()
__lowercase = BreadthFirstSearch(init, goal)
__lowercase = bfs.search()
__lowercase = time.time() - start_bfs_time
print('''Unidirectional BFS computation time : ''', bfs_time)
__lowercase = time.time()
__lowercase = BidirectionalBreadthFirstSearch(init, goal)
__lowercase = bd_bfs.search()
__lowercase = time.time() - start_bd_bfs_time
print('''Bidirectional BFS computation time : ''', bd_bfs_time)
| 711 | '''simple docstring'''
import operator as op
def snake_case__ ( _A: Optional[Any] ) -> Tuple:
'''simple docstring'''
lowerCAmelCase = []
lowerCAmelCase = lambda _A , _A : int(x / y ) # noqa: E731 integer division operation
lowerCAmelCase = {
"""^""": op.pow,
"""*""": op.mul,
"""/""": div,
"""+""": op.add,
"""-""": op.sub,
} # operators & their respective operation
# print table header
print("""Symbol""".center(8 ) , """Action""".center(12 ) , """Stack""" , sep=""" | """ )
print("""-""" * (30 + len(_A )) )
for x in post_fix:
if x.isdigit(): # if x in digit
stack.append(_A ) # append x to stack
# output in tabular format
print(x.rjust(8 ) , ("""push(""" + x + """)""").ljust(12 ) , """,""".join(_A ) , sep=""" | """ )
else:
lowerCAmelCase = stack.pop() # pop stack
# output in tabular format
print("""""".rjust(8 ) , ("""pop(""" + b + """)""").ljust(12 ) , """,""".join(_A ) , sep=""" | """ )
lowerCAmelCase = stack.pop() # pop stack
# output in tabular format
print("""""".rjust(8 ) , ("""pop(""" + a + """)""").ljust(12 ) , """,""".join(_A ) , sep=""" | """ )
stack.append(
str(opr[x](int(_A ) , int(_A ) ) ) ) # evaluate the 2 values popped from stack & push result to stack
# output in tabular format
print(
x.rjust(8 ) , ("""push(""" + a + x + b + """)""").ljust(12 ) , """,""".join(_A ) , sep=""" | """ , )
return int(stack[0] )
if __name__ == "__main__":
__lowercase = input('''\n\nEnter a Postfix Equation (space separated) = ''').split(''' ''')
print('''\n\tResult = ''', solve(Postfix))
| 605 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
UpperCAmelCase_ : Union[str, Any] = {
"configuration_maskformer": ["MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "MaskFormerConfig"],
"configuration_maskformer_swin": ["MaskFormerSwinConfig"],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : int = ["MaskFormerFeatureExtractor"]
UpperCAmelCase_ : List[Any] = ["MaskFormerImageProcessor"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : int = [
"MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
"MaskFormerForInstanceSegmentation",
"MaskFormerModel",
"MaskFormerPreTrainedModel",
]
UpperCAmelCase_ : Optional[Any] = [
"MaskFormerSwinBackbone",
"MaskFormerSwinModel",
"MaskFormerSwinPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig
from .configuration_maskformer_swin import MaskFormerSwinConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_maskformer import MaskFormerFeatureExtractor
from .image_processing_maskformer import MaskFormerImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_maskformer import (
MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
MaskFormerForInstanceSegmentation,
MaskFormerModel,
MaskFormerPreTrainedModel,
)
from .modeling_maskformer_swin import (
MaskFormerSwinBackbone,
MaskFormerSwinModel,
MaskFormerSwinPreTrainedModel,
)
else:
import sys
UpperCAmelCase_ : str = _LazyModule(__name__, globals()["__file__"], _import_structure)
| 491 |
from dataclasses import dataclass
from typing import Optional
import torch
from torch import nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .modeling_utils import ModelMixin
@dataclass
class UpperCamelCase ( _UpperCAmelCase ):
lowerCAmelCase : torch.FloatTensor
class UpperCamelCase ( _UpperCAmelCase , _UpperCAmelCase ):
@register_to_config
def __init__( self , UpperCAmelCase__ = 16 , UpperCAmelCase__ = 88 , UpperCAmelCase__ = None , UpperCAmelCase__ = None , UpperCAmelCase__ = 1 , UpperCAmelCase__ = 0.0 , UpperCAmelCase__ = 32 , UpperCAmelCase__ = None , UpperCAmelCase__ = False , UpperCAmelCase__ = None , UpperCAmelCase__ = "geglu" , UpperCAmelCase__ = True , UpperCAmelCase__ = True , ):
super().__init__()
A__ = num_attention_heads
A__ = attention_head_dim
A__ = num_attention_heads * attention_head_dim
A__ = in_channels
A__ = torch.nn.GroupNorm(num_groups=UpperCAmelCase__ , num_channels=UpperCAmelCase__ , eps=1e-6 , affine=UpperCAmelCase__ )
A__ = nn.Linear(UpperCAmelCase__ , UpperCAmelCase__ )
# 3. Define transformers blocks
A__ = nn.ModuleList(
[
BasicTransformerBlock(
UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , dropout=UpperCAmelCase__ , cross_attention_dim=UpperCAmelCase__ , activation_fn=UpperCAmelCase__ , attention_bias=UpperCAmelCase__ , double_self_attention=UpperCAmelCase__ , norm_elementwise_affine=UpperCAmelCase__ , )
for d in range(UpperCAmelCase__ )
] )
A__ = nn.Linear(UpperCAmelCase__ , UpperCAmelCase__ )
def __A ( self , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=1 , UpperCAmelCase__=None , UpperCAmelCase__ = True , ):
A__ , A__ , A__ , A__ = hidden_states.shape
A__ = batch_frames // num_frames
A__ = hidden_states
A__ = hidden_states[None, :].reshape(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
A__ = hidden_states.permute(0 , 2 , 1 , 3 , 4 )
A__ = self.norm(UpperCAmelCase__ )
A__ = hidden_states.permute(0 , 3 , 4 , 2 , 1 ).reshape(batch_size * height * width , UpperCAmelCase__ , UpperCAmelCase__ )
A__ = self.proj_in(UpperCAmelCase__ )
# 2. Blocks
for block in self.transformer_blocks:
A__ = block(
UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , timestep=UpperCAmelCase__ , cross_attention_kwargs=UpperCAmelCase__ , class_labels=UpperCAmelCase__ , )
# 3. Output
A__ = self.proj_out(UpperCAmelCase__ )
A__ = (
hidden_states[None, None, :]
.reshape(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
.permute(0 , 3 , 4 , 1 , 2 )
.contiguous()
)
A__ = hidden_states.reshape(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
A__ = hidden_states + residual
if not return_dict:
return (output,)
return TransformerTemporalModelOutput(sample=UpperCAmelCase__ )
| 491 | 1 |
import argparse
import json
from pathlib import Path
import requests
import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
_SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
def SCREAMING_SNAKE_CASE__ ( __a , __a=False ):
snake_case_ : List[Any] = []
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"""deit.encoder.layer.{i}.layernorm_before.weight""") )
rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""deit.encoder.layer.{i}.layernorm_before.bias""") )
rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""deit.encoder.layer.{i}.attention.output.dense.weight""") )
rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""deit.encoder.layer.{i}.attention.output.dense.bias""") )
rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""deit.encoder.layer.{i}.layernorm_after.weight""") )
rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""deit.encoder.layer.{i}.layernorm_after.bias""") )
rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""deit.encoder.layer.{i}.intermediate.dense.weight""") )
rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""deit.encoder.layer.{i}.intermediate.dense.bias""") )
rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""deit.encoder.layer.{i}.output.dense.weight""") )
rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""deit.encoder.layer.{i}.output.dense.bias""") )
# projection layer + position embeddings
rename_keys.extend(
[
('cls_token', 'deit.embeddings.cls_token'),
('dist_token', 'deit.embeddings.distillation_token'),
('patch_embed.proj.weight', 'deit.embeddings.patch_embeddings.projection.weight'),
('patch_embed.proj.bias', 'deit.embeddings.patch_embeddings.projection.bias'),
('pos_embed', 'deit.embeddings.position_embeddings'),
] )
if base_model:
# layernorm + pooler
rename_keys.extend(
[
('norm.weight', 'layernorm.weight'),
('norm.bias', 'layernorm.bias'),
('pre_logits.fc.weight', 'pooler.dense.weight'),
('pre_logits.fc.bias', 'pooler.dense.bias'),
] )
# if just the base model, we should remove "deit" from all keys that start with "deit"
snake_case_ : List[str] = [(pair[0], pair[1][4:]) if pair[1].startswith('deit' ) else pair for pair in rename_keys]
else:
# layernorm + classification heads
rename_keys.extend(
[
('norm.weight', 'deit.layernorm.weight'),
('norm.bias', 'deit.layernorm.bias'),
('head.weight', 'cls_classifier.weight'),
('head.bias', 'cls_classifier.bias'),
('head_dist.weight', 'distillation_classifier.weight'),
('head_dist.bias', 'distillation_classifier.bias'),
] )
return rename_keys
def SCREAMING_SNAKE_CASE__ ( __a , __a , __a=False ):
for i in range(config.num_hidden_layers ):
if base_model:
snake_case_ : str = ''
else:
snake_case_ : Any = 'deit.'
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
snake_case_ : Any = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" )
snake_case_ : List[str] = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" )
# next, add query, keys and values (in that order) to the state dict
snake_case_ : Optional[Any] = in_proj_weight[
: config.hidden_size, :
]
snake_case_ : List[Any] = in_proj_bias[: config.hidden_size]
snake_case_ : str = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
snake_case_ : List[Any] = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
snake_case_ : Union[str, Any] = in_proj_weight[
-config.hidden_size :, :
]
snake_case_ : Union[str, Any] = in_proj_bias[-config.hidden_size :]
def SCREAMING_SNAKE_CASE__ ( __a , __a , __a ):
snake_case_ : Any = dct.pop(__a )
snake_case_ : Optional[int] = val
def SCREAMING_SNAKE_CASE__ ( ):
snake_case_ : Tuple = 'http://images.cocodataset.org/val2017/000000039769.jpg'
snake_case_ : Dict = Image.open(requests.get(__a , stream=__a ).raw )
return im
@torch.no_grad()
def SCREAMING_SNAKE_CASE__ ( __a , __a ):
snake_case_ : List[str] = DeiTConfig()
# all deit models have fine-tuned heads
snake_case_ : List[str] = False
# dataset (fine-tuned on ImageNet 2012), patch_size and image_size
snake_case_ : List[str] = 10_00
snake_case_ : Dict = 'huggingface/label-files'
snake_case_ : Tuple = 'imagenet-1k-id2label.json'
snake_case_ : Union[str, Any] = json.load(open(hf_hub_download(__a , __a , repo_type='dataset' ) , 'r' ) )
snake_case_ : Optional[int] = {int(__a ): v for k, v in idalabel.items()}
snake_case_ : Union[str, Any] = idalabel
snake_case_ : Optional[Any] = {v: k for k, v in idalabel.items()}
snake_case_ : Tuple = int(deit_name[-6:-4] )
snake_case_ : List[Any] = int(deit_name[-3:] )
# size of the architecture
if deit_name[9:].startswith('tiny' ):
snake_case_ : Tuple = 1_92
snake_case_ : List[Any] = 7_68
snake_case_ : List[Any] = 12
snake_case_ : int = 3
elif deit_name[9:].startswith('small' ):
snake_case_ : Dict = 3_84
snake_case_ : List[Any] = 15_36
snake_case_ : List[str] = 12
snake_case_ : str = 6
if deit_name[9:].startswith('base' ):
pass
elif deit_name[4:].startswith('large' ):
snake_case_ : int = 10_24
snake_case_ : Tuple = 40_96
snake_case_ : int = 24
snake_case_ : Optional[Any] = 16
# load original model from timm
snake_case_ : Any = timm.create_model(__a , pretrained=__a )
timm_model.eval()
# load state_dict of original model, remove and rename some keys
snake_case_ : str = timm_model.state_dict()
snake_case_ : List[str] = create_rename_keys(__a , __a )
for src, dest in rename_keys:
rename_key(__a , __a , __a )
read_in_q_k_v(__a , __a , __a )
# load HuggingFace model
snake_case_ : Union[str, Any] = DeiTForImageClassificationWithTeacher(__a ).eval()
model.load_state_dict(__a )
# Check outputs on an image, prepared by DeiTImageProcessor
snake_case_ : List[str] = int(
(2_56 / 2_24) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103
snake_case_ : Any = DeiTImageProcessor(size=__a , crop_size=config.image_size )
snake_case_ : List[Any] = image_processor(images=prepare_img() , return_tensors='pt' )
snake_case_ : Union[str, Any] = encoding['pixel_values']
snake_case_ : str = model(__a )
snake_case_ : int = timm_model(__a )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(__a , outputs.logits , atol=1E-3 )
Path(__a ).mkdir(exist_ok=__a )
print(f"""Saving model {deit_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 __name__ == "__main__":
_SCREAMING_SNAKE_CASE = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--deit_name""",
default="""vit_deit_base_distilled_patch16_224""",
type=str,
help="""Name of the DeiT timm model you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
)
_SCREAMING_SNAKE_CASE = parser.parse_args()
convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
| 534 |
# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path
_SCREAMING_SNAKE_CASE = Path(__file__).resolve().parents[3] / """src"""
sys.path.insert(1, str(git_repo_path))
import dataclasses # noqa
import io # noqa
import itertools # noqa
import json # noqa
import os # noqa
import unittest # noqa
from copy import deepcopy # noqa
from parameterized import parameterized # noqa
from transformers import TrainingArguments, is_torch_available # noqa
from transformers.deepspeed import is_deepspeed_available # noqa
from transformers.file_utils import WEIGHTS_NAME # noqa
from transformers.testing_utils import ( # noqa
CaptureLogger,
ExtendSysPath,
TestCasePlus,
execute_subprocess_async,
get_gpu_count,
mockenv_context,
require_deepspeed,
require_torch_gpu,
require_torch_multi_gpu,
slow,
)
from transformers.trainer_utils import set_seed # noqa
set_seed(42)
_SCREAMING_SNAKE_CASE = {"""base""": """patrickvonplaten/wav2vec2_tiny_random""", """robust""": """patrickvonplaten/wav2vec2_tiny_random_robust"""}
_SCREAMING_SNAKE_CASE = """zero2"""
_SCREAMING_SNAKE_CASE = """zero3"""
_SCREAMING_SNAKE_CASE = [ZEROa, ZEROa]
def SCREAMING_SNAKE_CASE__ ( __a , __a , __a ):
# customize the test name generator function as we want both params to appear in the sub-test
# name, as by default it shows only the first param
snake_case_ : Tuple = parameterized.to_safe_name('_'.join(str(__a ) for x in param.args ) )
return f"""{func.__name__}_{param_based_name}"""
# Cartesian-product of zero stages with models to test
_SCREAMING_SNAKE_CASE = list(itertools.product(stages, models.keys()))
@slow
@require_deepspeed
@require_torch_gpu
class SCREAMING_SNAKE_CASE_ ( snake_case_ ):
@parameterized.expand(_A , name_func=_A )
def UpperCAmelCase_ ( self : Tuple , _A : Optional[Any] , _A : Optional[int] ) -> Dict:
"""simple docstring"""
self.run_and_check(
stage=_A , model=_A , distributed=_A , fpaa=_A , )
@require_torch_multi_gpu
@parameterized.expand(_A , name_func=_A )
def UpperCAmelCase_ ( self : int , _A : Any , _A : int ) -> Dict:
"""simple docstring"""
self.run_and_check(
stage=_A , model=_A , distributed=_A , fpaa=_A , )
@parameterized.expand(_A , name_func=_A )
def UpperCAmelCase_ ( self : str , _A : List[str] , _A : str ) -> Tuple:
"""simple docstring"""
self.run_and_check(
stage=_A , model=_A , distributed=_A , fpaa=_A , )
@require_torch_multi_gpu
@parameterized.expand(_A , name_func=_A )
def UpperCAmelCase_ ( self : Optional[int] , _A : int , _A : Union[str, Any] ) -> List[Any]:
"""simple docstring"""
self.run_and_check(
stage=_A , model=_A , distributed=_A , fpaa=_A , )
def UpperCAmelCase_ ( self : Any , _A : Union[str, Any] ) -> Any:
"""simple docstring"""
pass
def UpperCAmelCase_ ( self : List[str] , _A : str , _A : str , _A : int = 10 , _A : bool = True , _A : bool = True , _A : bool = True , ) -> Any:
"""simple docstring"""
snake_case_ : Dict = models[model]
snake_case_ : str = self.run_trainer(
stage=_A , model_name=_A , eval_steps=_A , num_train_epochs=1 , distributed=_A , fpaa=_A , )
self.do_checks(_A )
return output_dir
def UpperCAmelCase_ ( self : Any , _A : str , _A : str , _A : int = 10 , _A : int = 1 , _A : bool = True , _A : bool = True , ) -> Dict:
"""simple docstring"""
snake_case_ : str = self.get_auto_remove_tmp_dir('./xxx' , after=_A )
snake_case_ : Tuple = F"""
--model_name_or_path {model_name}
--dataset_name hf-internal-testing/librispeech_asr_dummy
--dataset_config_name clean
--train_split_name validation
--validation_split_name validation
--output_dir {output_dir}
--num_train_epochs {str(_A )}
--per_device_train_batch_size 2
--per_device_eval_batch_size 2
--evaluation_strategy steps
--learning_rate 5e-4
--warmup_steps 8
--orthography timit
--preprocessing_num_workers 1
--group_by_length
--freeze_feature_extractor
--report_to none
--save_steps 0
--eval_steps {eval_steps}
--report_to none
""".split()
if fpaa:
args.extend(['--fp16'] )
# currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
# hence the separate config files
snake_case_ : Any = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
snake_case_ : str = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
snake_case_ : int = self.get_launcher(_A )
snake_case_ : List[str] = launcher + script + args + ds_args
# keep for quick debug
# print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
execute_subprocess_async(_A , env=self.get_env() )
return output_dir
def UpperCAmelCase_ ( self : Optional[Any] , _A : Optional[Any]=False ) -> List[str]:
"""simple docstring"""
snake_case_ : str = min(2 , get_gpu_count() ) if distributed else 1
return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
| 534 | 1 |
from typing import Any, Callable, Dict, List, Optional, Union
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DiffusionPipeline,
LMSDiscreteScheduler,
PNDMScheduler,
StableDiffusionPipeline,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
snake_case = """CompVis/stable-diffusion-v1-1"""
snake_case = """CompVis/stable-diffusion-v1-2"""
snake_case = """CompVis/stable-diffusion-v1-3"""
snake_case = """CompVis/stable-diffusion-v1-4"""
class A_ ( UpperCAmelCase ):
"""simple docstring"""
def __init__( self : Union[str, Any] ,__A : AutoencoderKL ,__A : CLIPTextModel ,__A : CLIPTokenizer ,__A : UNetaDConditionModel ,__A : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] ,__A : StableDiffusionSafetyChecker ,__A : CLIPImageProcessor ,__A : bool = True ,) -> Any:
super()._init_()
_lowercase = StableDiffusionPipeline.from_pretrained(__A )
_lowercase = StableDiffusionPipeline.from_pretrained(__A )
_lowercase = StableDiffusionPipeline.from_pretrained(__A )
_lowercase = StableDiffusionPipeline(
vae=__A ,text_encoder=__A ,tokenizer=__A ,unet=__A ,scheduler=__A ,safety_checker=__A ,feature_extractor=__A ,requires_safety_checker=__A ,)
self.register_modules(pipelinea=self.pipea ,pipelinea=self.pipea ,pipelinea=self.pipea ,pipelinea=self.pipea )
@property
def __UpperCAmelCase ( self : Dict ) -> Dict[str, Any]:
return {k: getattr(self ,__A ) for k in self.config.keys() if not k.startswith('_' )}
def __UpperCAmelCase ( self : int ,__A : Optional[Union[str, int]] = "auto" ) -> Optional[Any]:
if slice_size == "auto":
# half the attention head size is usually a good trade-off between
# speed and memory
_lowercase = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(__A )
def __UpperCAmelCase ( self : Optional[Any] ) -> Optional[int]:
self.enable_attention_slicing(__A )
@torch.no_grad()
def __UpperCAmelCase ( self : int ,__A : Union[str, List[str]] ,__A : int = 512 ,__A : int = 512 ,__A : int = 50 ,__A : float = 7.5 ,__A : Optional[Union[str, List[str]]] = None ,__A : Optional[int] = 1 ,__A : float = 0.0 ,__A : Optional[torch.Generator] = None ,__A : Optional[torch.FloatTensor] = None ,__A : Optional[str] = "pil" ,__A : bool = True ,__A : Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,__A : int = 1 ,**__A : Dict ,) -> Tuple:
return self.pipea(
prompt=__A ,height=__A ,width=__A ,num_inference_steps=__A ,guidance_scale=__A ,negative_prompt=__A ,num_images_per_prompt=__A ,eta=__A ,generator=__A ,latents=__A ,output_type=__A ,return_dict=__A ,callback=__A ,callback_steps=__A ,**__A ,)
@torch.no_grad()
def __UpperCAmelCase ( self : int ,__A : Union[str, List[str]] ,__A : int = 512 ,__A : int = 512 ,__A : int = 50 ,__A : float = 7.5 ,__A : Optional[Union[str, List[str]]] = None ,__A : Optional[int] = 1 ,__A : float = 0.0 ,__A : Optional[torch.Generator] = None ,__A : Optional[torch.FloatTensor] = None ,__A : Optional[str] = "pil" ,__A : bool = True ,__A : Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,__A : int = 1 ,**__A : Union[str, Any] ,) -> Tuple:
return self.pipea(
prompt=__A ,height=__A ,width=__A ,num_inference_steps=__A ,guidance_scale=__A ,negative_prompt=__A ,num_images_per_prompt=__A ,eta=__A ,generator=__A ,latents=__A ,output_type=__A ,return_dict=__A ,callback=__A ,callback_steps=__A ,**__A ,)
@torch.no_grad()
def __UpperCAmelCase ( self : Optional[int] ,__A : Union[str, List[str]] ,__A : int = 512 ,__A : int = 512 ,__A : int = 50 ,__A : float = 7.5 ,__A : Optional[Union[str, List[str]]] = None ,__A : Optional[int] = 1 ,__A : float = 0.0 ,__A : Optional[torch.Generator] = None ,__A : Optional[torch.FloatTensor] = None ,__A : Optional[str] = "pil" ,__A : bool = True ,__A : Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,__A : int = 1 ,**__A : int ,) -> str:
return self.pipea(
prompt=__A ,height=__A ,width=__A ,num_inference_steps=__A ,guidance_scale=__A ,negative_prompt=__A ,num_images_per_prompt=__A ,eta=__A ,generator=__A ,latents=__A ,output_type=__A ,return_dict=__A ,callback=__A ,callback_steps=__A ,**__A ,)
@torch.no_grad()
def __UpperCAmelCase ( self : Any ,__A : Union[str, List[str]] ,__A : int = 512 ,__A : int = 512 ,__A : int = 50 ,__A : float = 7.5 ,__A : Optional[Union[str, List[str]]] = None ,__A : Optional[int] = 1 ,__A : float = 0.0 ,__A : Optional[torch.Generator] = None ,__A : Optional[torch.FloatTensor] = None ,__A : Optional[str] = "pil" ,__A : bool = True ,__A : Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,__A : int = 1 ,**__A : Union[str, Any] ,) -> List[Any]:
return self.pipea(
prompt=__A ,height=__A ,width=__A ,num_inference_steps=__A ,guidance_scale=__A ,negative_prompt=__A ,num_images_per_prompt=__A ,eta=__A ,generator=__A ,latents=__A ,output_type=__A ,return_dict=__A ,callback=__A ,callback_steps=__A ,**__A ,)
@torch.no_grad()
def __UpperCAmelCase ( self : List[str] ,__A : Union[str, List[str]] ,__A : int = 512 ,__A : int = 512 ,__A : int = 50 ,__A : float = 7.5 ,__A : Optional[Union[str, List[str]]] = None ,__A : Optional[int] = 1 ,__A : float = 0.0 ,__A : Optional[torch.Generator] = None ,__A : Optional[torch.FloatTensor] = None ,__A : Optional[str] = "pil" ,__A : bool = True ,__A : Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,__A : int = 1 ,**__A : Tuple ,) -> Optional[Any]:
_lowercase = 'cuda' if torch.cuda.is_available() else 'cpu'
self.to(__A )
# Checks if the height and width are divisible by 8 or not
if height % 8 != 0 or width % 8 != 0:
raise ValueError(F"""`height` and `width` must be divisible by 8 but are {height} and {width}.""" )
# Get first result from Stable Diffusion Checkpoint v1.1
_lowercase = self.textaimg_sda_a(
prompt=__A ,height=__A ,width=__A ,num_inference_steps=__A ,guidance_scale=__A ,negative_prompt=__A ,num_images_per_prompt=__A ,eta=__A ,generator=__A ,latents=__A ,output_type=__A ,return_dict=__A ,callback=__A ,callback_steps=__A ,**__A ,)
# Get first result from Stable Diffusion Checkpoint v1.2
_lowercase = self.textaimg_sda_a(
prompt=__A ,height=__A ,width=__A ,num_inference_steps=__A ,guidance_scale=__A ,negative_prompt=__A ,num_images_per_prompt=__A ,eta=__A ,generator=__A ,latents=__A ,output_type=__A ,return_dict=__A ,callback=__A ,callback_steps=__A ,**__A ,)
# Get first result from Stable Diffusion Checkpoint v1.3
_lowercase = self.textaimg_sda_a(
prompt=__A ,height=__A ,width=__A ,num_inference_steps=__A ,guidance_scale=__A ,negative_prompt=__A ,num_images_per_prompt=__A ,eta=__A ,generator=__A ,latents=__A ,output_type=__A ,return_dict=__A ,callback=__A ,callback_steps=__A ,**__A ,)
# Get first result from Stable Diffusion Checkpoint v1.4
_lowercase = self.textaimg_sda_a(
prompt=__A ,height=__A ,width=__A ,num_inference_steps=__A ,guidance_scale=__A ,negative_prompt=__A ,num_images_per_prompt=__A ,eta=__A ,generator=__A ,latents=__A ,output_type=__A ,return_dict=__A ,callback=__A ,callback_steps=__A ,**__A ,)
# Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] ) | 67 | from __future__ import annotations
def lowerCAmelCase_ ( lowercase: str , lowercase: list[str] | None = None , lowercase: dict[str, float] | None = None , lowercase: bool = False , ) -> tuple[int, float, str]:
'''simple docstring'''
_UpperCamelCase: Any = 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)
_UpperCamelCase: Any = {
'''a''': 0.08497,
'''b''': 0.01492,
'''c''': 0.02202,
'''d''': 0.04253,
'''e''': 0.11162,
'''f''': 0.02228,
'''g''': 0.02015,
'''h''': 0.06094,
'''i''': 0.07546,
'''j''': 0.00153,
'''k''': 0.01292,
'''l''': 0.04025,
'''m''': 0.02406,
'''n''': 0.06749,
'''o''': 0.07507,
'''p''': 0.01929,
'''q''': 0.00095,
'''r''': 0.07587,
'''s''': 0.06327,
'''t''': 0.09356,
'''u''': 0.02758,
'''v''': 0.00978,
'''w''': 0.02560,
'''x''': 0.00150,
'''y''': 0.01994,
'''z''': 0.00077,
}
else:
# Custom frequencies dictionary
_UpperCamelCase: str = frequencies_dict
if not case_sensitive:
_UpperCamelCase: Union[str, Any] = ciphertext.lower()
# Chi squared statistic values
_UpperCamelCase: dict[int, tuple[float, str]] = {}
# cycle through all of the shifts
for shift in range(len(lowercase ) ):
_UpperCamelCase: Tuple = ''''''
# decrypt the message with the shift
for letter in ciphertext:
try:
# Try to index the letter in the alphabet
_UpperCamelCase: Optional[int] = (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
_UpperCamelCase: Optional[int] = 0.0
# Loop through each letter in the decoded message with the shift
for letter in decrypted_with_shift:
if case_sensitive:
_UpperCamelCase: Optional[int] = letter.lower()
if letter in frequencies:
# Get the amount of times the letter occurs in the message
_UpperCamelCase: Any = decrypted_with_shift.lower().count(lowercase )
# Get the excepcted amount of times the letter should appear based
# on letter frequencies
_UpperCamelCase: int = frequencies[letter] * occurrences
# Complete the chi squared statistic formula
_UpperCamelCase: int = ((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
_UpperCamelCase: List[Any] = decrypted_with_shift.count(lowercase )
# Get the excepcted amount of times the letter should appear based
# on letter frequencies
_UpperCamelCase: Union[str, Any] = frequencies[letter] * occurrences
# Complete the chi squared statistic formula
_UpperCamelCase: List[str] = ((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
_UpperCamelCase: List[Any] = (
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]
_UpperCamelCase: int = min(
lowercase , key=lowercase , )
# Get all the data from the most likely cipher (key, decoded message)
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) ,
): str = 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,
) | 271 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCamelCase : Optional[int] = logging.get_logger(__name__)
__lowerCamelCase : Dict = {}
class lowerCamelCase ( _lowerCamelCase ):
'''simple docstring'''
UpperCamelCase__ ='''llama'''
UpperCamelCase__ =['''past_key_values''']
def __init__( self : Dict , lowerCamelCase_ : List[str]=32000 , lowerCamelCase_ : List[Any]=4096 , lowerCamelCase_ : Any=11008 , lowerCamelCase_ : Optional[Any]=32 , lowerCamelCase_ : Dict=32 , lowerCamelCase_ : Optional[Any]=None , lowerCamelCase_ : Dict="silu" , lowerCamelCase_ : Optional[int]=2048 , lowerCamelCase_ : int=0.0_2 , lowerCamelCase_ : Tuple=1E-6 , lowerCamelCase_ : Tuple=True , lowerCamelCase_ : List[str]=0 , lowerCamelCase_ : List[str]=1 , lowerCamelCase_ : Optional[int]=2 , lowerCamelCase_ : List[str]=1 , lowerCamelCase_ : Dict=False , lowerCamelCase_ : int=None , **lowerCamelCase_ : Tuple , ) -> Tuple:
__magic_name__ : Any = vocab_size
__magic_name__ : Optional[int] = max_position_embeddings
__magic_name__ : Union[str, Any] = hidden_size
__magic_name__ : Dict = intermediate_size
__magic_name__ : Union[str, Any] = num_hidden_layers
__magic_name__ : Tuple = num_attention_heads
# for backward compatibility
if num_key_value_heads is None:
__magic_name__ : Optional[int] = num_attention_heads
__magic_name__ : Optional[int] = num_key_value_heads
__magic_name__ : List[str] = hidden_act
__magic_name__ : List[str] = initializer_range
__magic_name__ : Tuple = rms_norm_eps
__magic_name__ : Optional[int] = pretraining_tp
__magic_name__ : Any = use_cache
__magic_name__ : int = rope_scaling
self._rope_scaling_validation()
super().__init__(
pad_token_id=lowerCamelCase_ , bos_token_id=lowerCamelCase_ , eos_token_id=lowerCamelCase_ , tie_word_embeddings=lowerCamelCase_ , **lowerCamelCase_ , )
def UpperCAmelCase__ ( self : str ) -> Tuple:
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , lowerCamelCase_ ) 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}''' )
__magic_name__ : List[str] = self.rope_scaling.get('''type''' , lowerCamelCase_ )
__magic_name__ : str = self.rope_scaling.get('''factor''' , lowerCamelCase_ )
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(lowerCamelCase_ , lowerCamelCase_ ) or rope_scaling_factor <= 1.0:
raise ValueError(F'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
| 501 |
import importlib.util
import json
import os
import warnings
from dataclasses import dataclass, field
import torch
from ..training_args import TrainingArguments
from ..utils import cached_property, is_sagemaker_dp_enabled, logging
__lowerCamelCase : List[Any] = logging.get_logger(__name__)
def lowercase__ ( ):
'''simple docstring'''
__magic_name__ : Any = os.getenv('''SM_HP_MP_PARAMETERS''' ,'''{}''' )
try:
# Parse it and check the field "partitions" is included, it is required for model parallel.
__magic_name__ : Tuple = json.loads(__A )
if "partitions" not in smp_options:
return False
except json.JSONDecodeError:
return False
# Get the sagemaker specific framework parameters from mpi_options variable.
__magic_name__ : int = os.getenv('''SM_FRAMEWORK_PARAMS''' ,'''{}''' )
try:
# Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
__magic_name__ : List[Any] = json.loads(__A )
if not mpi_options.get('''sagemaker_mpi_enabled''' ,__A ):
return False
except json.JSONDecodeError:
return False
# Lastly, check if the `smdistributed` module is present.
return importlib.util.find_spec('''smdistributed''' ) is not None
if is_sagemaker_model_parallel_available():
import smdistributed.modelparallel.torch as smp
smp.init()
@dataclass
class lowerCamelCase ( _lowerCamelCase ):
'''simple docstring'''
UpperCamelCase__ =field(
default='''''' ,metadata={'''help''': '''Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer'''} ,)
def UpperCAmelCase__ ( self : str ) -> List[str]:
super().__post_init__()
warnings.warn(
'''`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use '''
'''`TrainingArguments` instead.''' , lowerCamelCase_ , )
@cached_property
def UpperCAmelCase__ ( self : int ) -> "torch.device":
logger.info('''PyTorch: setting up devices''' )
if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1:
logger.warning(
'''torch.distributed process group is initialized, but local_rank == -1. '''
'''In order to use Torch DDP, launch your script with `python -m torch.distributed.launch''' )
if self.no_cuda:
__magic_name__ : Optional[int] = torch.device('''cpu''' )
__magic_name__ : int = 0
elif is_sagemaker_model_parallel_available():
__magic_name__ : Any = smp.local_rank()
__magic_name__ : int = torch.device('''cuda''' , lowerCamelCase_ )
__magic_name__ : Optional[int] = 1
elif is_sagemaker_dp_enabled():
import smdistributed.dataparallel.torch.torch_smddp # noqa: F401
torch.distributed.init_process_group(backend='''smddp''' , timeout=self.ddp_timeout_delta )
__magic_name__ : Optional[int] = int(os.getenv('''SMDATAPARALLEL_LOCAL_RANK''' ) )
__magic_name__ : Optional[int] = torch.device('''cuda''' , self.local_rank )
__magic_name__ : str = 1
elif self.local_rank == -1:
# if n_gpu is > 1 we'll use nn.DataParallel.
# If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
# Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will
# trigger an error that a device index is missing. Index 0 takes into account the
# GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0`
# will use the first GPU in that env, i.e. GPU#1
__magic_name__ : List[str] = torch.device('''cuda:0''' if torch.cuda.is_available() else '''cpu''' )
# Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at
# the default value.
__magic_name__ : Dict = torch.cuda.device_count()
else:
# Here, we'll use torch.distributed.
# Initializes the distributed backend which will take care of synchronizing nodes/GPUs
if not torch.distributed.is_initialized():
torch.distributed.init_process_group(backend='''nccl''' , timeout=self.ddp_timeout_delta )
__magic_name__ : str = torch.device('''cuda''' , self.local_rank )
__magic_name__ : Dict = 1
if device.type == "cuda":
torch.cuda.set_device(lowerCamelCase_ )
return device
@property
def UpperCAmelCase__ ( self : List[str] ) -> int:
if is_sagemaker_model_parallel_available():
return smp.dp_size()
return super().world_size
@property
def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]:
return not is_sagemaker_model_parallel_available()
@property
def UpperCAmelCase__ ( self : Optional[int] ) -> Tuple:
return False
| 501 | 1 |
'''simple docstring'''
from __future__ import annotations
from collections.abc import Callable
A__ : str = list[list[float | int]]
def UpperCAmelCase__ ( UpperCAmelCase_ : Matrix , UpperCAmelCase_ : Matrix ) -> Matrix:
__lowerCamelCase : int = len(UpperCAmelCase_ )
__lowerCamelCase : Matrix = [[0 for _ in range(size + 1 )] for _ in range(UpperCAmelCase_ )]
__lowerCamelCase : int
__lowerCamelCase : int
__lowerCamelCase : int
__lowerCamelCase : int
__lowerCamelCase : int
__lowerCamelCase : float
for row in range(UpperCAmelCase_ ):
for col in range(UpperCAmelCase_ ):
__lowerCamelCase : Union[str, Any] = matrix[row][col]
__lowerCamelCase : Optional[Any] = vector[row][0]
__lowerCamelCase : int = 0
__lowerCamelCase : Optional[Any] = 0
while row < size and col < size:
# pivoting
__lowerCamelCase : int = max((abs(augmented[rowa][col] ), rowa) for rowa in range(UpperCAmelCase_ , UpperCAmelCase_ ) )[
1
]
if augmented[pivot_row][col] == 0:
col += 1
continue
else:
__lowerCamelCase , __lowerCamelCase : Optional[int] = augmented[pivot_row], augmented[row]
for rowa in range(row + 1 , UpperCAmelCase_ ):
__lowerCamelCase : List[Any] = augmented[rowa][col] / augmented[row][col]
__lowerCamelCase : Dict = 0
for cola in range(col + 1 , size + 1 ):
augmented[rowa][cola] -= augmented[row][cola] * ratio
row += 1
col += 1
# back substitution
for col in range(1 , UpperCAmelCase_ ):
for row in range(UpperCAmelCase_ ):
__lowerCamelCase : Optional[int] = augmented[row][col] / augmented[col][col]
for cola in range(UpperCAmelCase_ , size + 1 ):
augmented[row][cola] -= augmented[col][cola] * ratio
# round to get rid of numbers like 2.000000000000004
return [
[round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(UpperCAmelCase_ )
]
def UpperCAmelCase__ ( UpperCAmelCase_ : list[int] ) -> Callable[[int], int]:
__lowerCamelCase : int = len(UpperCAmelCase_ )
__lowerCamelCase : Matrix = [[0 for _ in range(UpperCAmelCase_ )] for _ in range(UpperCAmelCase_ )]
__lowerCamelCase : Matrix = [[0] for _ in range(UpperCAmelCase_ )]
__lowerCamelCase : Matrix
__lowerCamelCase : int
__lowerCamelCase : int
__lowerCamelCase : int
for x_val, y_val in enumerate(UpperCAmelCase_ ):
for col in range(UpperCAmelCase_ ):
__lowerCamelCase : str = (x_val + 1) ** (size - col - 1)
__lowerCamelCase : str = y_val
__lowerCamelCase : Dict = solve(UpperCAmelCase_ , UpperCAmelCase_ )
def interpolated_func(UpperCAmelCase_ : int ) -> int:
return sum(
round(coeffs[x_val][0] ) * (var ** (size - x_val - 1))
for x_val in range(UpperCAmelCase_ ) )
return interpolated_func
def UpperCAmelCase__ ( UpperCAmelCase_ : int ) -> int:
return (
1
- variable
+ variable**2
- variable**3
+ variable**4
- variable**5
+ variable**6
- variable**7
+ variable**8
- variable**9
+ variable**10
)
def UpperCAmelCase__ ( UpperCAmelCase_ : Callable[[int], int] = question_function , UpperCAmelCase_ : int = 10 ) -> int:
__lowerCamelCase : list[int] = [func(UpperCAmelCase_ ) for x_val in range(1 , order + 1 )]
__lowerCamelCase : list[Callable[[int], int]] = [
interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 )
]
__lowerCamelCase : int = 0
__lowerCamelCase : Callable[[int], int]
__lowerCamelCase : int
for poly in polynomials:
__lowerCamelCase : Optional[Any] = 1
while func(UpperCAmelCase_ ) == poly(UpperCAmelCase_ ):
x_val += 1
ret += poly(UpperCAmelCase_ )
return ret
if __name__ == "__main__":
print(f'''{solution() = }''')
| 13 |
'''simple docstring'''
from __future__ import annotations
import unittest
from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers.models.xglm.modeling_tf_xglm import (
TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
TFXGLMForCausalLM,
TFXGLMModel,
)
@require_tf
class UpperCAmelCase_ :
"""simple docstring"""
lowerCamelCase : Dict = XGLMConfig
lowerCamelCase : List[str] = {}
lowerCamelCase : Union[str, Any] = 'gelu'
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=14 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=0.0_2 , ) -> Any:
__lowerCamelCase : int = parent
__lowerCamelCase : Optional[int] = batch_size
__lowerCamelCase : Optional[Any] = seq_length
__lowerCamelCase : Optional[int] = is_training
__lowerCamelCase : str = use_input_mask
__lowerCamelCase : Dict = use_labels
__lowerCamelCase : Union[str, Any] = vocab_size
__lowerCamelCase : List[Any] = d_model
__lowerCamelCase : List[Any] = num_hidden_layers
__lowerCamelCase : List[Any] = num_attention_heads
__lowerCamelCase : Optional[Any] = ffn_dim
__lowerCamelCase : List[Any] = activation_function
__lowerCamelCase : List[Any] = activation_dropout
__lowerCamelCase : List[Any] = attention_dropout
__lowerCamelCase : Union[str, Any] = max_position_embeddings
__lowerCamelCase : Tuple = initializer_range
__lowerCamelCase : int = None
__lowerCamelCase : int = 0
__lowerCamelCase : Tuple = 2
__lowerCamelCase : Tuple = 1
def lowercase_ ( self ) -> Any:
return XGLMConfig.from_pretrained('facebook/xglm-564M' )
def lowercase_ ( self ) -> Tuple:
__lowerCamelCase : Optional[Any] = tf.clip_by_value(
ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 )
__lowerCamelCase : Optional[int] = None
if self.use_input_mask:
__lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length] )
__lowerCamelCase : str = self.get_config()
__lowerCamelCase : List[Any] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 )
return (
config,
input_ids,
input_mask,
head_mask,
)
def lowercase_ ( self ) -> Optional[int]:
return XGLMConfig(
vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=SCREAMING_SNAKE_CASE_ , )
def lowercase_ ( self ) -> str:
__lowerCamelCase : List[Any] = self.prepare_config_and_inputs()
(
(
__lowerCamelCase
) , (
__lowerCamelCase
) , (
__lowerCamelCase
) , (
__lowerCamelCase
) ,
) : str = config_and_inputs
__lowerCamelCase : Union[str, Any] = {
'input_ids': input_ids,
'head_mask': head_mask,
}
return config, inputs_dict
@require_tf
class UpperCAmelCase_ (_UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ):
"""simple docstring"""
lowerCamelCase : Optional[Any] = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
lowerCamelCase : List[Any] = (TFXGLMForCausalLM,) if is_tf_available() else ()
lowerCamelCase : Any = (
{'feature-extraction': TFXGLMModel, 'text-generation': TFXGLMForCausalLM} if is_tf_available() else {}
)
lowerCamelCase : List[Any] = False
lowerCamelCase : Dict = False
lowerCamelCase : Union[str, Any] = False
def lowercase_ ( self ) -> List[Any]:
__lowerCamelCase : str = TFXGLMModelTester(self )
__lowerCamelCase : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , n_embd=37 )
def lowercase_ ( self ) -> Dict:
self.config_tester.run_common_tests()
@slow
def lowercase_ ( self ) -> Optional[int]:
for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__lowerCamelCase : Optional[Any] = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
@unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.' )
def lowercase_ ( self ) -> Any:
super().test_resize_token_embeddings()
@require_tf
class UpperCAmelCase_ (unittest.TestCase ):
"""simple docstring"""
@slow
def lowercase_ ( self , SCREAMING_SNAKE_CASE_=True ) -> List[str]:
__lowerCamelCase : Optional[Any] = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' )
__lowerCamelCase : int = tf.convert_to_tensor([[2, 2_68, 98_65]] , dtype=tf.intaa ) # The dog
# </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
# fmt: off
__lowerCamelCase : Optional[int] = [2, 2_68, 98_65, 67, 11, 19_88, 5_72_52, 98_65, 5, 9_84, 67, 19_88, 21_38_38, 16_58, 53, 7_04_46, 33, 66_57, 2_78, 15_81]
# fmt: on
__lowerCamelCase : Any = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ , num_beams=1 )
if verify_outputs:
self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE_ )
@slow
def lowercase_ ( self ) -> int:
__lowerCamelCase : Any = XGLMTokenizer.from_pretrained('facebook/xglm-564M' )
__lowerCamelCase : Tuple = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' )
tf.random.set_seed(0 )
__lowerCamelCase : List[Any] = tokenizer('Today is a nice day and' , return_tensors='tf' )
__lowerCamelCase : int = tokenized.input_ids
# forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
with tf.device(':/CPU:0' ):
__lowerCamelCase : Tuple = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ , seed=[7, 0] )
__lowerCamelCase : Optional[Any] = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
__lowerCamelCase : Union[str, Any] = (
'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due'
)
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
@slow
def lowercase_ ( self ) -> int:
__lowerCamelCase : Tuple = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' )
__lowerCamelCase : Any = XGLMTokenizer.from_pretrained('facebook/xglm-564M' )
__lowerCamelCase : Any = 'left'
# use different length sentences to test batching
__lowerCamelCase : Any = [
'This is an extremelly long sentence that only exists to test the ability of the model to cope with '
'left-padding, such as in batched generation. The output for the sequence below should be the same '
'regardless of whether left padding is applied or not. When',
'Hello, my dog is a little',
]
__lowerCamelCase : Any = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors='tf' , padding=SCREAMING_SNAKE_CASE_ )
__lowerCamelCase : Optional[int] = inputs['input_ids']
__lowerCamelCase : str = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=inputs['attention_mask'] , max_new_tokens=12 )
__lowerCamelCase : Optional[int] = tokenizer(sentences[0] , return_tensors='tf' ).input_ids
__lowerCamelCase : int = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , max_new_tokens=12 )
__lowerCamelCase : Optional[Any] = tokenizer(sentences[1] , return_tensors='tf' ).input_ids
__lowerCamelCase : Optional[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , max_new_tokens=12 )
__lowerCamelCase : Union[str, Any] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
__lowerCamelCase : Union[str, Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
__lowerCamelCase : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
__lowerCamelCase : Optional[int] = [
'This is an extremelly long sentence that only exists to test the ability of the model to cope with '
'left-padding, such as in batched generation. The output for the sequence below should be the same '
'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be '
'a single',
'Hello, my dog is a little bit of a shy one, but he is very friendly',
]
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , [non_padded_sentence, padded_sentence] )
| 13 | 1 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_torch_available,
)
lowerCamelCase = {
'''configuration_speecht5''': [
'''SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP''',
'''SpeechT5Config''',
'''SpeechT5HifiGanConfig''',
],
'''feature_extraction_speecht5''': ['''SpeechT5FeatureExtractor'''],
'''processing_speecht5''': ['''SpeechT5Processor'''],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase = ['''SpeechT5Tokenizer''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase = [
'''SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''SpeechT5ForSpeechToText''',
'''SpeechT5ForSpeechToSpeech''',
'''SpeechT5ForTextToSpeech''',
'''SpeechT5Model''',
'''SpeechT5PreTrainedModel''',
'''SpeechT5HifiGan''',
]
if TYPE_CHECKING:
from .configuration_speechta import (
SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP,
SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP,
SpeechTaConfig,
SpeechTaHifiGanConfig,
)
from .feature_extraction_speechta import SpeechTaFeatureExtractor
from .processing_speechta import SpeechTaProcessor
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_speechta import SpeechTaTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_speechta import (
SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST,
SpeechTaForSpeechToSpeech,
SpeechTaForSpeechToText,
SpeechTaForTextToSpeech,
SpeechTaHifiGan,
SpeechTaModel,
SpeechTaPreTrainedModel,
)
else:
import sys
lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 710 |
import os
import posixpath
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union
import numpy as np
import pyarrow as pa
import datasets
from datasets.arrow_writer import ArrowWriter, ParquetWriter
from datasets.config import MAX_SHARD_SIZE
from datasets.filesystems import (
is_remote_filesystem,
rename,
)
from datasets.iterable_dataset import _BaseExamplesIterable
from datasets.utils.py_utils import convert_file_size_to_int
lowerCamelCase = datasets.utils.logging.get_logger(__name__)
if TYPE_CHECKING:
import pyspark
@dataclass
class snake_case_ ( datasets.BuilderConfig ):
"""simple docstring"""
__UpperCAmelCase =None
def __lowercase ( UpperCAmelCase__ , UpperCAmelCase__ , ):
"""simple docstring"""
import pyspark
def generate_fn():
__lowerCAmelCase = df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id' ) )
for partition_id in partition_order:
__lowerCAmelCase = df_with_partition_id.select('*' ).where(F"""part_id = {partition_id}""" ).drop('part_id' )
__lowerCAmelCase = partition_df.collect()
__lowerCAmelCase = 0
for row in rows:
yield F"""{partition_id}_{row_id}""", row.asDict()
row_id += 1
return generate_fn
class snake_case_ ( _BaseExamplesIterable ):
"""simple docstring"""
def __init__( self , _A , _A=None , ):
__lowerCAmelCase = df
__lowerCAmelCase = partition_order or range(self.df.rdd.getNumPartitions() )
__lowerCAmelCase = _generate_iterable_examples(self.df , self.partition_order )
def __iter__( self ):
yield from self.generate_examples_fn()
def A__ ( self , _A ):
__lowerCAmelCase = list(range(self.df.rdd.getNumPartitions() ) )
generator.shuffle(_A )
return SparkExamplesIterable(self.df , partition_order=_A )
def A__ ( self , _A , _A ):
__lowerCAmelCase = self.split_shard_indices_by_worker(_A , _A )
return SparkExamplesIterable(self.df , partition_order=_A )
@property
def A__ ( self ):
return len(self.partition_order )
class snake_case_ ( datasets.DatasetBuilder ):
"""simple docstring"""
__UpperCAmelCase =SparkConfig
def __init__( self , _A , _A = None , _A = None , **_A , ):
import pyspark
__lowerCAmelCase = pyspark.sql.SparkSession.builder.getOrCreate()
__lowerCAmelCase = df
__lowerCAmelCase = working_dir
super().__init__(
cache_dir=_A , config_name=str(self.df.semanticHash() ) , **_A , )
def A__ ( self ):
# Returns the path of the created file.
def create_cache_and_write_probe(_A ):
# makedirs with exist_ok will recursively create the directory. It will not throw an error if directories
# already exist.
os.makedirs(self._cache_dir , exist_ok=_A )
__lowerCAmelCase = os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex )
# Opening the file in append mode will create a new file unless it already exists, in which case it will not
# change the file contents.
open(_A , 'a' )
return [probe_file]
if self._spark.conf.get('spark.master' , '' ).startswith('local' ):
return
# If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS
# accessible to the driver.
# TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error.
if self._cache_dir:
__lowerCAmelCase = (
self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(_A ).collect()
)
if os.path.isfile(probe[0] ):
return
raise ValueError(
'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' )
def A__ ( self ):
return datasets.DatasetInfo(features=self.config.features )
def A__ ( self , _A ):
return [datasets.SplitGenerator(name=datasets.Split.TRAIN )]
def A__ ( self , _A ):
import pyspark
def get_arrow_batch_size(_A ):
for batch in it:
yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} )
__lowerCAmelCase = self.df.count()
__lowerCAmelCase = df_num_rows if df_num_rows <= 1_0_0 else 1_0_0
# Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample.
__lowerCAmelCase = (
self.df.limit(_A )
.repartition(1 )
.mapInArrow(_A , 'batch_bytes: long' )
.agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) )
.collect()[0]
.sample_bytes
/ sample_num_rows
)
__lowerCAmelCase = approx_bytes_per_row * df_num_rows
if approx_total_size > max_shard_size:
# Make sure there is at least one row per partition.
__lowerCAmelCase = min(_A , int(approx_total_size / max_shard_size ) )
__lowerCAmelCase = self.df.repartition(_A )
def A__ ( self , _A , _A , _A , ):
import pyspark
__lowerCAmelCase = ParquetWriter if file_format == 'parquet' else ArrowWriter
__lowerCAmelCase = os.path.join(self._working_dir , os.path.basename(_A ) ) if self._working_dir else fpath
__lowerCAmelCase = file_format == 'parquet'
# Define these so that we don't reference self in write_arrow, which will result in a pickling error due to
# pickling the SparkContext.
__lowerCAmelCase = self.config.features
__lowerCAmelCase = self._writer_batch_size
__lowerCAmelCase = self._fs.storage_options
def write_arrow(_A ):
# Within the same SparkContext, no two task attempts will share the same attempt ID.
__lowerCAmelCase = pyspark.TaskContext().taskAttemptId()
__lowerCAmelCase = next(_A , _A )
if first_batch is None:
# Some partitions might not receive any data.
return pa.RecordBatch.from_arrays(
[[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , )
__lowerCAmelCase = 0
__lowerCAmelCase = writer_class(
features=_A , path=working_fpath.replace('SSSSS' , F"""{shard_id:05d}""" ).replace('TTTTT' , F"""{task_id:05d}""" ) , writer_batch_size=_A , storage_options=_A , embed_local_files=_A , )
__lowerCAmelCase = pa.Table.from_batches([first_batch] )
writer.write_table(_A )
for batch in it:
if max_shard_size is not None and writer._num_bytes >= max_shard_size:
__lowerCAmelCase, __lowerCAmelCase = writer.finalize()
writer.close()
yield pa.RecordBatch.from_arrays(
[[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , )
shard_id += 1
__lowerCAmelCase = writer_class(
features=writer._features , path=working_fpath.replace('SSSSS' , F"""{shard_id:05d}""" ).replace('TTTTT' , F"""{task_id:05d}""" ) , writer_batch_size=_A , storage_options=_A , embed_local_files=_A , )
__lowerCAmelCase = pa.Table.from_batches([batch] )
writer.write_table(_A )
if writer._num_bytes > 0:
__lowerCAmelCase, __lowerCAmelCase = writer.finalize()
writer.close()
yield pa.RecordBatch.from_arrays(
[[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , )
if working_fpath != fpath:
for file in os.listdir(os.path.dirname(_A ) ):
__lowerCAmelCase = os.path.join(os.path.dirname(_A ) , os.path.basename(_A ) )
shutil.move(_A , _A )
__lowerCAmelCase = (
self.df.mapInArrow(_A , 'task_id: long, num_examples: long, num_bytes: long' )
.groupBy('task_id' )
.agg(
pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) , pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) , pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) , pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) , )
.collect()
)
for row in stats:
yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths)
def A__ ( self , _A , _A = "arrow" , _A = None , _A = None , **_A , ):
self._validate_cache_dir()
__lowerCAmelCase = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE )
self._repartition_df_if_needed(_A )
__lowerCAmelCase = not is_remote_filesystem(self._fs )
__lowerCAmelCase = os.path.join if is_local else posixpath.join
__lowerCAmelCase = '-TTTTT-SSSSS-of-NNNNN'
__lowerCAmelCase = F"""{self.name}-{split_generator.name}{SUFFIX}.{file_format}"""
__lowerCAmelCase = path_join(self._output_dir , _A )
__lowerCAmelCase = 0
__lowerCAmelCase = 0
__lowerCAmelCase = 0
__lowerCAmelCase = []
__lowerCAmelCase = []
for task_id, content in self._prepare_split_single(_A , _A , _A ):
(
(
__lowerCAmelCase
), (
__lowerCAmelCase
), (
__lowerCAmelCase
), (
__lowerCAmelCase
),
) = content
if num_bytes > 0:
total_num_examples += num_examples
total_num_bytes += num_bytes
total_shards += num_shards
task_id_and_num_shards.append((task_id, num_shards) )
all_shard_lengths.extend(_A )
__lowerCAmelCase = total_num_examples
__lowerCAmelCase = total_num_bytes
# should rename everything at the end
logger.debug(F"""Renaming {total_shards} shards.""" )
if total_shards > 1:
__lowerCAmelCase = all_shard_lengths
# Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a
# pickling error due to pickling the SparkContext.
__lowerCAmelCase = self._fs
# use the -SSSSS-of-NNNNN pattern
def _rename_shard(
_A , _A , _A , ):
rename(
_A , fpath.replace('SSSSS' , F"""{shard_id:05d}""" ).replace('TTTTT' , F"""{task_id:05d}""" ) , fpath.replace('TTTTT-SSSSS' , F"""{global_shard_id:05d}""" ).replace('NNNNN' , F"""{total_shards:05d}""" ) , )
__lowerCAmelCase = []
__lowerCAmelCase = 0
for i in range(len(_A ) ):
__lowerCAmelCase, __lowerCAmelCase = task_id_and_num_shards[i]
for shard_id in range(_A ):
args.append([task_id, shard_id, global_shard_id] )
global_shard_id += 1
self._spark.sparkContext.parallelize(_A , len(_A ) ).map(lambda _A : _rename_shard(*_A ) ).collect()
else:
# don't use any pattern
__lowerCAmelCase = 0
__lowerCAmelCase = task_id_and_num_shards[0][0]
self._rename(
fpath.replace('SSSSS' , F"""{shard_id:05d}""" ).replace('TTTTT' , F"""{task_id:05d}""" ) , fpath.replace(_A , '' ) , )
def A__ ( self , _A , ):
return SparkExamplesIterable(self.df )
| 102 | 0 |
"""simple docstring"""
import logging
import os
from .state import PartialState
class lowerCamelCase ( logging.LoggerAdapter ):
@staticmethod
def a_ ( SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : Any = PartialState()
return not main_process_only or (main_process_only and state.is_main_process)
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ):
if PartialState._shared_state == {}:
raise RuntimeError(
"""You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.""" )
UpperCamelCase : Dict = kwargs.pop("""main_process_only""" , SCREAMING_SNAKE_CASE_ )
UpperCamelCase : Union[str, Any] = kwargs.pop("""in_order""" , SCREAMING_SNAKE_CASE_ )
if self.isEnabledFor(SCREAMING_SNAKE_CASE_ ):
if self._should_log(SCREAMING_SNAKE_CASE_ ):
UpperCamelCase , UpperCamelCase : Dict = self.process(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.logger.log(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
elif in_order:
UpperCamelCase : Tuple = PartialState()
for i in range(state.num_processes ):
if i == state.process_index:
UpperCamelCase , UpperCamelCase : Optional[int] = self.process(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.logger.log(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
state.wait_for_everyone()
def A_ ( snake_case_ : str ,snake_case_ : str = None ):
'''simple docstring'''
if log_level is None:
UpperCamelCase : Tuple = os.environ.get("""ACCELERATE_LOG_LEVEL""" ,snake_case_ )
UpperCamelCase : Tuple = logging.getLogger(snake_case_ )
if log_level is not None:
logger.setLevel(log_level.upper() )
logger.root.setLevel(log_level.upper() )
return MultiProcessAdapter(snake_case_ ,{} )
| 499 |
"""simple docstring"""
import time
import warnings
from abc import ABC
from copy import deepcopy
from typing import Optional
import torch
from ..utils import add_start_docstrings, logging
__A : int = logging.get_logger(__name__)
__A : Optional[Any] = R'''
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
or scores for each vocabulary token after SoftMax.
kwargs (`Dict[str, Any]`, *optional*):
Additional stopping criteria specific kwargs.
Return:
`bool`. `False` indicates we should continue, `True` indicates we should stop.
'''
class lowerCamelCase ( _UpperCAmelCase ):
@add_start_docstrings(SCREAMING_SNAKE_CASE_ )
def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ):
raise NotImplementedError("""StoppingCriteria needs to be subclassed""" )
class lowerCamelCase ( _UpperCAmelCase ):
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ):
UpperCamelCase : str = max_length
UpperCamelCase : List[Any] = max_position_embeddings
@add_start_docstrings(SCREAMING_SNAKE_CASE_ )
def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : Dict = input_ids.shape[-1]
UpperCamelCase : List[Any] = cur_len >= self.max_length
if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
logger.warning_once(
"""This is a friendly reminder - the current text generation call will exceed the model's predefined """
f'maximum length ({self.max_position_embeddings}). Depending on the model, you may observe '
"""exceptions, performance degradation, or nothing at all.""" )
return is_done
class lowerCamelCase ( _UpperCAmelCase ):
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
warnings.warn(
"""The class `MaxNewTokensCriteria` is deprecated. """
f'Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` '
"""with `max_length = start_length + max_new_tokens` instead.""" , SCREAMING_SNAKE_CASE_ , )
UpperCamelCase : Dict = start_length
UpperCamelCase : List[Any] = max_new_tokens
UpperCamelCase : int = start_length + max_new_tokens
@add_start_docstrings(SCREAMING_SNAKE_CASE_ )
def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ):
return input_ids.shape[-1] >= self.max_length
class lowerCamelCase ( _UpperCAmelCase ):
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ):
UpperCamelCase : List[str] = max_time
UpperCamelCase : Optional[int] = time.time() if initial_timestamp is None else initial_timestamp
@add_start_docstrings(SCREAMING_SNAKE_CASE_ )
def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ):
return time.time() - self.initial_timestamp > self.max_time
class lowerCamelCase ( _UpperCAmelCase ):
@add_start_docstrings(SCREAMING_SNAKE_CASE_ )
def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ):
return any(criteria(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for criteria in self )
@property
def a_ ( self ):
for stopping_criterium in self:
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
return stopping_criterium.max_length
elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
return stopping_criterium.max_length
return None
def A_ ( snake_case_ : StoppingCriteriaList ,snake_case_ : int ):
'''simple docstring'''
UpperCamelCase : Optional[Any] = stopping_criteria.max_length
UpperCamelCase : Tuple = deepcopy(snake_case_ )
if stopping_max_length is not None and stopping_max_length != max_length:
warnings.warn("""You set different `max_length` for stopping criteria and `max_length` parameter""" ,snake_case_ )
elif stopping_max_length is None:
new_stopping_criteria.append(MaxLengthCriteria(max_length=snake_case_ ) )
return new_stopping_criteria
| 499 | 1 |
def _UpperCAmelCase (UpperCamelCase_ : list ):
'''simple docstring'''
def merge(UpperCamelCase_ : list , UpperCamelCase_ : list ) -> list:
def _merge():
while left and right:
yield (left if left[0] <= right[0] else right).pop(0 )
yield from left
yield from right
return list(_merge() )
if len(UpperCamelCase_ ) <= 1:
return collection
_lowerCAmelCase : str = len(UpperCamelCase_ ) // 2
return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
_lowerCamelCase : int = input("Enter numbers separated by a comma:\n").strip()
_lowerCamelCase : List[Any] = [int(item) for item in user_input.split(",")]
print(*merge_sort(unsorted), sep=",")
| 196 |
import numpy as np
def _UpperCAmelCase (UpperCamelCase_ : np.array ):
'''simple docstring'''
return (2 / (1 + np.exp(-2 * vector ))) - 1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 196 | 1 |
'''simple docstring'''
from typing import Any, Dict, List, Union
from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from ..image_utils import load_image
if is_torch_available():
import torch
from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
lowercase : Optional[Any] = logging.get_logger(__name__)
lowercase : Any = Dict[str, Any]
lowercase : List[str] = List[Prediction]
@add_end_docstrings(lowerCamelCase_ )
class _lowerCAmelCase ( lowerCamelCase_ ):
"""simple docstring"""
def __init__( self : int , *SCREAMING_SNAKE_CASE : List[str] , **SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]:
"""simple docstring"""
super().__init__(*__snake_case , **__snake_case )
if self.framework == "tf":
raise ValueError(f"The {self.__class__} is only available in PyTorch." )
requires_backends(self , "vision" )
self.check_model_type(
dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) )
def __A ( self : str , **SCREAMING_SNAKE_CASE : Any ) -> List[str]:
"""simple docstring"""
lowerCAmelCase = {}
if "threshold" in kwargs:
lowerCAmelCase = kwargs["threshold"]
return {}, {}, postprocess_kwargs
def __call__( self : Dict , *SCREAMING_SNAKE_CASE : Tuple , **SCREAMING_SNAKE_CASE : Dict ) -> Union[Predictions, List[Prediction]]:
"""simple docstring"""
return super().__call__(*__snake_case , **__snake_case )
def __A ( self : List[Any] , SCREAMING_SNAKE_CASE : Optional[int] ) -> int:
"""simple docstring"""
lowerCAmelCase = load_image(__snake_case )
lowerCAmelCase = torch.IntTensor([[image.height, image.width]] )
lowerCAmelCase = self.image_processor(images=[image] , return_tensors="pt" )
if self.tokenizer is not None:
lowerCAmelCase = self.tokenizer(text=inputs["words"] , boxes=inputs["boxes"] , return_tensors="pt" )
lowerCAmelCase = target_size
return inputs
def __A ( self : Tuple , SCREAMING_SNAKE_CASE : Optional[int] ) -> str:
"""simple docstring"""
lowerCAmelCase = model_inputs.pop("target_size" )
lowerCAmelCase = self.model(**__snake_case )
lowerCAmelCase = outputs.__class__({"target_size": target_size, **outputs} )
if self.tokenizer is not None:
lowerCAmelCase = model_inputs["bbox"]
return model_outputs
def __A ( self : Any , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Optional[int]=0.9 ) -> Optional[Any]:
"""simple docstring"""
lowerCAmelCase = model_outputs["target_size"]
if self.tokenizer is not None:
# This is a LayoutLMForTokenClassification variant.
# The OCR got the boxes and the model classified the words.
lowerCAmelCase , lowerCAmelCase = target_size[0].tolist()
def unnormalize(SCREAMING_SNAKE_CASE : Any ):
return self._get_bounding_box(
torch.Tensor(
[
(width * bbox[0] / 1_0_0_0),
(height * bbox[1] / 1_0_0_0),
(width * bbox[2] / 1_0_0_0),
(height * bbox[3] / 1_0_0_0),
] ) )
lowerCAmelCase , lowerCAmelCase = model_outputs["logits"].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 )
lowerCAmelCase = [self.model.config.idalabel[prediction] for prediction in classes.tolist()]
lowerCAmelCase = [unnormalize(__snake_case ) for bbox in model_outputs["bbox"].squeeze(0 )]
lowerCAmelCase = ["score", "label", "box"]
lowerCAmelCase = [dict(zip(__snake_case , __snake_case ) ) for vals in zip(scores.tolist() , __snake_case , __snake_case ) if vals[0] > threshold]
else:
# This is a regular ForObjectDetectionModel
lowerCAmelCase = self.image_processor.post_process_object_detection(__snake_case , __snake_case , __snake_case )
lowerCAmelCase = raw_annotations[0]
lowerCAmelCase = raw_annotation["scores"]
lowerCAmelCase = raw_annotation["labels"]
lowerCAmelCase = raw_annotation["boxes"]
lowerCAmelCase = scores.tolist()
lowerCAmelCase = [self.model.config.idalabel[label.item()] for label in labels]
lowerCAmelCase = [self._get_bounding_box(__snake_case ) for box in boxes]
# {"scores": [...], ...} --> [{"score":x, ...}, ...]
lowerCAmelCase = ["score", "label", "box"]
lowerCAmelCase = [
dict(zip(__snake_case , __snake_case ) )
for vals in zip(raw_annotation["scores"] , raw_annotation["labels"] , raw_annotation["boxes"] )
]
return annotation
def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE : "torch.Tensor" ) -> Dict[str, int]:
"""simple docstring"""
if self.framework != "pt":
raise ValueError("The ObjectDetectionPipeline is only available in PyTorch." )
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = box.int().tolist()
lowerCAmelCase = {
"xmin": xmin,
"ymin": ymin,
"xmax": xmax,
"ymax": ymax,
}
return bbox
| 649 |
import flax.linen as nn
import jax.numpy as jnp
from .attention_flax import FlaxTransformeraDModel
from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD
class snake_case_ (nn.Module ):
UpperCAmelCase__ : int
UpperCAmelCase__ : int
UpperCAmelCase__ : float = 0.0
UpperCAmelCase__ : int = 1
UpperCAmelCase__ : int = 1
UpperCAmelCase__ : bool = True
UpperCAmelCase__ : bool = False
UpperCAmelCase__ : bool = False
UpperCAmelCase__ : bool = False
UpperCAmelCase__ : jnp.dtype = jnp.floataa
def lowerCamelCase__( self :int ) -> Dict:
a__ = []
a__ = []
for i in range(self.num_layers ):
a__ = self.in_channels if i == 0 else self.out_channels
a__ = FlaxResnetBlockaD(
in_channels=__snake_case ,out_channels=self.out_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,)
resnets.append(__snake_case )
a__ = FlaxTransformeraDModel(
in_channels=self.out_channels ,n_heads=self.num_attention_heads ,d_head=self.out_channels // self.num_attention_heads ,depth=1 ,use_linear_projection=self.use_linear_projection ,only_cross_attention=self.only_cross_attention ,use_memory_efficient_attention=self.use_memory_efficient_attention ,dtype=self.dtype ,)
attentions.append(__snake_case )
a__ = resnets
a__ = attentions
if self.add_downsample:
a__ = FlaxDownsampleaD(self.out_channels ,dtype=self.dtype )
def __call__( self :Dict ,__snake_case :str ,__snake_case :Optional[Any] ,__snake_case :Optional[int] ,__snake_case :Tuple=True ) -> Tuple:
a__ = ()
for resnet, attn in zip(self.resnets ,self.attentions ):
a__ = resnet(__snake_case ,__snake_case ,deterministic=__snake_case )
a__ = attn(__snake_case ,__snake_case ,deterministic=__snake_case )
output_states += (hidden_states,)
if self.add_downsample:
a__ = self.downsamplers_a(__snake_case )
output_states += (hidden_states,)
return hidden_states, output_states
class snake_case_ (nn.Module ):
UpperCAmelCase__ : int
UpperCAmelCase__ : int
UpperCAmelCase__ : float = 0.0
UpperCAmelCase__ : int = 1
UpperCAmelCase__ : bool = True
UpperCAmelCase__ : jnp.dtype = jnp.floataa
def lowerCamelCase__( self :Optional[Any] ) -> Dict:
a__ = []
for i in range(self.num_layers ):
a__ = self.in_channels if i == 0 else self.out_channels
a__ = FlaxResnetBlockaD(
in_channels=__snake_case ,out_channels=self.out_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,)
resnets.append(__snake_case )
a__ = resnets
if self.add_downsample:
a__ = FlaxDownsampleaD(self.out_channels ,dtype=self.dtype )
def __call__( self :Optional[Any] ,__snake_case :str ,__snake_case :Dict ,__snake_case :Any=True ) -> List[Any]:
a__ = ()
for resnet in self.resnets:
a__ = resnet(__snake_case ,__snake_case ,deterministic=__snake_case )
output_states += (hidden_states,)
if self.add_downsample:
a__ = self.downsamplers_a(__snake_case )
output_states += (hidden_states,)
return hidden_states, output_states
class snake_case_ (nn.Module ):
UpperCAmelCase__ : int
UpperCAmelCase__ : int
UpperCAmelCase__ : int
UpperCAmelCase__ : float = 0.0
UpperCAmelCase__ : int = 1
UpperCAmelCase__ : int = 1
UpperCAmelCase__ : bool = True
UpperCAmelCase__ : bool = False
UpperCAmelCase__ : bool = False
UpperCAmelCase__ : bool = False
UpperCAmelCase__ : jnp.dtype = jnp.floataa
def lowerCamelCase__( self :Tuple ) -> List[str]:
a__ = []
a__ = []
for i in range(self.num_layers ):
a__ = self.in_channels if (i == self.num_layers - 1) else self.out_channels
a__ = self.prev_output_channel if i == 0 else self.out_channels
a__ = FlaxResnetBlockaD(
in_channels=resnet_in_channels + res_skip_channels ,out_channels=self.out_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,)
resnets.append(__snake_case )
a__ = FlaxTransformeraDModel(
in_channels=self.out_channels ,n_heads=self.num_attention_heads ,d_head=self.out_channels // self.num_attention_heads ,depth=1 ,use_linear_projection=self.use_linear_projection ,only_cross_attention=self.only_cross_attention ,use_memory_efficient_attention=self.use_memory_efficient_attention ,dtype=self.dtype ,)
attentions.append(__snake_case )
a__ = resnets
a__ = attentions
if self.add_upsample:
a__ = FlaxUpsampleaD(self.out_channels ,dtype=self.dtype )
def __call__( self :List[str] ,__snake_case :int ,__snake_case :List[Any] ,__snake_case :Union[str, Any] ,__snake_case :Union[str, Any] ,__snake_case :Dict=True ) -> int:
for resnet, attn in zip(self.resnets ,self.attentions ):
# pop res hidden states
a__ = res_hidden_states_tuple[-1]
a__ = res_hidden_states_tuple[:-1]
a__ = jnp.concatenate((hidden_states, res_hidden_states) ,axis=-1 )
a__ = resnet(__snake_case ,__snake_case ,deterministic=__snake_case )
a__ = attn(__snake_case ,__snake_case ,deterministic=__snake_case )
if self.add_upsample:
a__ = self.upsamplers_a(__snake_case )
return hidden_states
class snake_case_ (nn.Module ):
UpperCAmelCase__ : int
UpperCAmelCase__ : int
UpperCAmelCase__ : int
UpperCAmelCase__ : float = 0.0
UpperCAmelCase__ : int = 1
UpperCAmelCase__ : bool = True
UpperCAmelCase__ : jnp.dtype = jnp.floataa
def lowerCamelCase__( self :Union[str, Any] ) -> Any:
a__ = []
for i in range(self.num_layers ):
a__ = self.in_channels if (i == self.num_layers - 1) else self.out_channels
a__ = self.prev_output_channel if i == 0 else self.out_channels
a__ = FlaxResnetBlockaD(
in_channels=resnet_in_channels + res_skip_channels ,out_channels=self.out_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,)
resnets.append(__snake_case )
a__ = resnets
if self.add_upsample:
a__ = FlaxUpsampleaD(self.out_channels ,dtype=self.dtype )
def __call__( self :Optional[int] ,__snake_case :List[Any] ,__snake_case :int ,__snake_case :Optional[Any] ,__snake_case :Optional[Any]=True ) -> List[str]:
for resnet in self.resnets:
# pop res hidden states
a__ = res_hidden_states_tuple[-1]
a__ = res_hidden_states_tuple[:-1]
a__ = jnp.concatenate((hidden_states, res_hidden_states) ,axis=-1 )
a__ = resnet(__snake_case ,__snake_case ,deterministic=__snake_case )
if self.add_upsample:
a__ = self.upsamplers_a(__snake_case )
return hidden_states
class snake_case_ (nn.Module ):
UpperCAmelCase__ : int
UpperCAmelCase__ : float = 0.0
UpperCAmelCase__ : int = 1
UpperCAmelCase__ : int = 1
UpperCAmelCase__ : bool = False
UpperCAmelCase__ : bool = False
UpperCAmelCase__ : jnp.dtype = jnp.floataa
def lowerCamelCase__( self :Tuple ) -> List[Any]:
# there is always at least one resnet
a__ = [
FlaxResnetBlockaD(
in_channels=self.in_channels ,out_channels=self.in_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,)
]
a__ = []
for _ in range(self.num_layers ):
a__ = FlaxTransformeraDModel(
in_channels=self.in_channels ,n_heads=self.num_attention_heads ,d_head=self.in_channels // self.num_attention_heads ,depth=1 ,use_linear_projection=self.use_linear_projection ,use_memory_efficient_attention=self.use_memory_efficient_attention ,dtype=self.dtype ,)
attentions.append(__snake_case )
a__ = FlaxResnetBlockaD(
in_channels=self.in_channels ,out_channels=self.in_channels ,dropout_prob=self.dropout ,dtype=self.dtype ,)
resnets.append(__snake_case )
a__ = resnets
a__ = attentions
def __call__( self :Optional[Any] ,__snake_case :Union[str, Any] ,__snake_case :List[str] ,__snake_case :int ,__snake_case :int=True ) -> str:
a__ = self.resnets[0](__snake_case ,__snake_case )
for attn, resnet in zip(self.attentions ,self.resnets[1:] ):
a__ = attn(__snake_case ,__snake_case ,deterministic=__snake_case )
a__ = resnet(__snake_case ,__snake_case ,deterministic=__snake_case )
return hidden_states
| 335 | 0 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
UpperCamelCase =logging.get_logger(__name__)
UpperCamelCase ={
"""google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""",
"""google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""",
# See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
}
class A ( __snake_case ):
"""simple docstring"""
__a : List[Any] = 'mobilenet_v1'
def __init__( self , __lowerCAmelCase=3 , __lowerCAmelCase=2_24 , __lowerCAmelCase=1.0 , __lowerCAmelCase=8 , __lowerCAmelCase="relu6" , __lowerCAmelCase=True , __lowerCAmelCase=0.9_99 , __lowerCAmelCase=0.02 , __lowerCAmelCase=0.0_01 , **__lowerCAmelCase , ):
super().__init__(**A_ )
if depth_multiplier <= 0:
raise ValueError("""depth_multiplier must be greater than zero.""" )
UpperCamelCase_ : List[str] = num_channels
UpperCamelCase_ : Any = image_size
UpperCamelCase_ : Optional[Any] = depth_multiplier
UpperCamelCase_ : Union[str, Any] = min_depth
UpperCamelCase_ : int = hidden_act
UpperCamelCase_ : Union[str, Any] = tf_padding
UpperCamelCase_ : Optional[Any] = classifier_dropout_prob
UpperCamelCase_ : int = initializer_range
UpperCamelCase_ : Tuple = layer_norm_eps
class A ( __snake_case ):
"""simple docstring"""
__a : Any = version.parse('''1.11''' )
@property
def _UpperCAmelCase ( self ):
return OrderedDict([("""pixel_values""", {0: """batch"""})] )
@property
def _UpperCAmelCase ( self ):
if self.task == "image-classification":
return OrderedDict([("""logits""", {0: """batch"""})] )
else:
return OrderedDict([("""last_hidden_state""", {0: """batch"""}), ("""pooler_output""", {0: """batch"""})] )
@property
def _UpperCAmelCase ( self ):
return 1E-4
| 716 |
'''simple docstring'''
def snake_case ( a_ : int ) -> int:
"""simple docstring"""
assert (
isinstance(a_ , a_ ) and number_of_steps > 0
), f"number_of_steps needs to be positive integer, your input {number_of_steps}"
if number_of_steps == 1:
return 1
UpperCamelCase_ , UpperCamelCase_ : str = 1, 1
for _ in range(number_of_steps - 1 ):
UpperCamelCase_ , UpperCamelCase_ : Tuple = current + previous, current
return current
if __name__ == "__main__":
import doctest
doctest.testmod()
| 543 | 0 |
"""simple docstring"""
import os
from typing import Dict, List, Union
import tensorflow as tf
from keras_nlp.tokenizers import BytePairTokenizer
from tensorflow_text import pad_model_inputs
from .tokenization_gpta import GPTaTokenizer
class lowercase__( tf.keras.layers.Layer ):
'''simple docstring'''
def __init__( self :str , lowerCamelCase_ :Dict[str, int] , lowerCamelCase_ :List[str] , lowerCamelCase_ :int = None , lowerCamelCase_ :int = None ) -> Union[str, Any]:
'''simple docstring'''
super().__init__()
SCREAMING_SNAKE_CASE : str = pad_token_id
SCREAMING_SNAKE_CASE : List[str] = max_length
SCREAMING_SNAKE_CASE : Union[str, Any] = vocab
SCREAMING_SNAKE_CASE : Optional[int] = merges
SCREAMING_SNAKE_CASE : Tuple = BytePairTokenizer(lowerCamelCase_ , lowerCamelCase_ , sequence_length=lowerCamelCase_ )
@classmethod
def __lowerCAmelCase ( cls :str , lowerCamelCase_ :GPTaTokenizer , *lowerCamelCase_ :Any , **lowerCamelCase_ :str ) -> Dict:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Tuple = [''' '''.join(lowerCamelCase_ ) for m in tokenizer.bpe_ranks.keys()]
SCREAMING_SNAKE_CASE : List[Any] = tokenizer.get_vocab()
return cls(lowerCamelCase_ , lowerCamelCase_ , *lowerCamelCase_ , **lowerCamelCase_ )
@classmethod
def __lowerCAmelCase ( cls :Union[str, Any] , lowerCamelCase_ :Union[str, os.PathLike] , *lowerCamelCase_ :Dict , **lowerCamelCase_ :Tuple ) -> Optional[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE : int = GPTaTokenizer.from_pretrained(lowerCamelCase_ , *lowerCamelCase_ , **lowerCamelCase_ )
return cls.from_tokenizer(lowerCamelCase_ , *lowerCamelCase_ , **lowerCamelCase_ )
@classmethod
def __lowerCAmelCase ( cls :str , lowerCamelCase_ :Dict ) -> Tuple:
'''simple docstring'''
return cls(**lowerCamelCase_ )
def __lowerCAmelCase ( self :Any ) -> Any:
'''simple docstring'''
return {
"vocab": self.vocab,
"merges": self.merges,
"max_length": self.max_length,
"pad_token_id": self.pad_token_id,
}
def __lowerCAmelCase ( self :Dict , lowerCamelCase_ :List[str] , lowerCamelCase_ :int = None ) -> str:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[int] = self.tf_tokenizer(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Optional[int] = tf.ones_like(lowerCamelCase_ )
if self.pad_token_id is not None:
# pad the tokens up to max length
SCREAMING_SNAKE_CASE : Optional[int] = max_length if max_length is not None else self.max_length
if max_length is not None:
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = pad_model_inputs(
lowerCamelCase_ , max_seq_length=lowerCamelCase_ , pad_value=self.pad_token_id )
return {"attention_mask": attention_mask, "input_ids": input_ids}
| 698 |
"""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 lowercase__( _UpperCAmelCase ):
'''simple docstring'''
UpperCamelCase = 42
UpperCamelCase = 42
def __init__( self :List[str] , lowerCamelCase_ :UNetaDModel , lowerCamelCase_ :ScoreSdeVeScheduler ) -> int:
'''simple docstring'''
super().__init__()
self.register_modules(unet=lowerCamelCase_ , scheduler=lowerCamelCase_ )
@torch.no_grad()
def __call__( self :int , lowerCamelCase_ :int = 1 , lowerCamelCase_ :int = 20_00 , 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'''
SCREAMING_SNAKE_CASE : Optional[int] = self.unet.config.sample_size
SCREAMING_SNAKE_CASE : List[str] = (batch_size, 3, img_size, img_size)
SCREAMING_SNAKE_CASE : Any = self.unet
SCREAMING_SNAKE_CASE : Dict = randn_tensor(lowerCamelCase_ , generator=lowerCamelCase_ ) * self.scheduler.init_noise_sigma
SCREAMING_SNAKE_CASE : Union[str, Any] = sample.to(self.device )
self.scheduler.set_timesteps(lowerCamelCase_ )
self.scheduler.set_sigmas(lowerCamelCase_ )
for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ):
SCREAMING_SNAKE_CASE : Tuple = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device )
# correction step
for _ in range(self.scheduler.config.correct_steps ):
SCREAMING_SNAKE_CASE : Optional[Any] = self.unet(lowerCamelCase_ , lowerCamelCase_ ).sample
SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.step_correct(lowerCamelCase_ , lowerCamelCase_ , generator=lowerCamelCase_ ).prev_sample
# prediction step
SCREAMING_SNAKE_CASE : Any = model(lowerCamelCase_ , lowerCamelCase_ ).sample
SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.step_pred(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , generator=lowerCamelCase_ )
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = output.prev_sample, output.prev_sample_mean
SCREAMING_SNAKE_CASE : List[str] = sample_mean.clamp(0 , 1 )
SCREAMING_SNAKE_CASE : Any = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
SCREAMING_SNAKE_CASE : Any = self.numpy_to_pil(lowerCamelCase_ )
if not return_dict:
return (sample,)
return ImagePipelineOutput(images=lowerCamelCase_ )
| 698 | 1 |
'''simple docstring'''
import logging
import torch
from accelerate import Accelerator
from arguments import EvaluationArguments
from datasets import load_dataset
from torch.utils.data import IterableDataset
from torch.utils.data.dataloader import DataLoader
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed
class a ( snake_case__ ):
'''simple docstring'''
def __init__( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=1_0_2_4 , lowerCamelCase_=1_0_2_4 , lowerCamelCase_=3.6 ) -> str:
_a : Any = tokenizer
_a : Union[str, Any] = tokenizer.bos_token_id
_a : int = dataset
_a : Tuple = seq_length
_a : Union[str, Any] = seq_length * chars_per_token * num_of_sequences
def __iter__( self ) -> Union[str, Any]:
_a : Dict = iter(self.dataset )
_a : Dict = True
while more_examples:
_a : int = [], 0
while True:
if buffer_len >= self.input_characters:
break
try:
buffer.append(next(lowerCamelCase_ )['content'] )
buffer_len += len(buffer[-1] )
except StopIteration:
_a : Optional[int] = False
break
_a : List[Any] = tokenizer(lowerCamelCase_ , truncation=lowerCamelCase_ )['input_ids']
_a : Union[str, Any] = []
for tokenized_input in tokenized_inputs:
all_token_ids.extend(tokenized_input + [self.concat_token_id] )
for i in range(0 , len(lowerCamelCase_ ) , self.seq_length ):
_a : Union[str, Any] = all_token_ids[i : i + self.seq_length]
if len(lowerCamelCase_ ) == self.seq_length:
yield torch.tensor(lowerCamelCase_ )
def UpperCAmelCase_ ( A ):
'''simple docstring'''
_a : str = {'streaming': True}
_a : List[Any] = load_dataset(args.dataset_name , split='train' , **A )
_a : List[str] = ConstantLengthDataset(A , A , seq_length=args.seq_length )
_a : Dict = DataLoader(A , batch_size=args.batch_size )
return eval_dataloader
def UpperCAmelCase_ ( A ):
'''simple docstring'''
model.eval()
_a : List[Any] = []
for step, batch in enumerate(A ):
with torch.no_grad():
_a : Optional[Any] = model(A , labels=A )
_a : Dict = outputs.loss.repeat(args.batch_size )
losses.append(accelerator.gather(A ) )
if args.max_eval_steps > 0 and step >= args.max_eval_steps:
break
_a : Any = torch.mean(torch.cat(A ) )
try:
_a : str = torch.exp(A )
except OverflowError:
_a : Union[str, Any] = float('inf' )
return loss.item(), perplexity.item()
# Setup Accelerator
UpperCAmelCase_ : Any = Accelerator()
# Parse configuration
UpperCAmelCase_ : Union[str, Any] = HfArgumentParser(EvaluationArguments)
UpperCAmelCase_ : int = parser.parse_args()
set_seed(args.seed)
# Logging
UpperCAmelCase_ : Any = logging.getLogger(__name__)
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO
)
# Load model and tokenizer
UpperCAmelCase_ : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt)
UpperCAmelCase_ : Optional[int] = AutoTokenizer.from_pretrained(args.model_ckpt)
# Load dataset and dataloader
UpperCAmelCase_ : str = create_dataloader(args)
# Prepare everything with our `accelerator`.
UpperCAmelCase_ : List[str] = accelerator.prepare(model, eval_dataloader)
# Evaluate and save the last checkpoint
logger.info("Evaluating and saving model after training")
UpperCAmelCase_ : Union[str, Any] = evaluate(args)
logger.info(f'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
| 701 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCAmelCase_ : List[str] = logging.get_logger(__name__)
UpperCAmelCase_ : Optional[int] = {
# See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert
}
class a ( snake_case__ ):
'''simple docstring'''
__lowerCAmelCase : Union[str, Any] = """megatron-bert"""
def __init__( self , lowerCamelCase_=2_9_0_5_6 , lowerCamelCase_=1_0_2_4 , lowerCamelCase_=2_4 , lowerCamelCase_=1_6 , lowerCamelCase_=4_0_9_6 , lowerCamelCase_="gelu" , lowerCamelCase_=0.1 , lowerCamelCase_=0.1 , lowerCamelCase_=5_1_2 , lowerCamelCase_=2 , lowerCamelCase_=0.02 , lowerCamelCase_=1e-12 , lowerCamelCase_=0 , lowerCamelCase_="absolute" , lowerCamelCase_=True , **lowerCamelCase_ , ) -> List[str]:
super().__init__(pad_token_id=lowerCamelCase_ , **lowerCamelCase_ )
_a : Union[str, Any] = vocab_size
_a : Any = hidden_size
_a : Tuple = num_hidden_layers
_a : Dict = num_attention_heads
_a : str = hidden_act
_a : Dict = intermediate_size
_a : Any = hidden_dropout_prob
_a : int = attention_probs_dropout_prob
_a : str = max_position_embeddings
_a : int = type_vocab_size
_a : Tuple = initializer_range
_a : Optional[Any] = layer_norm_eps
_a : str = position_embedding_type
_a : str = use_cache
| 424 | 0 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.testing_utils import is_flaky, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DonutImageProcessor
class lowercase_ ( unittest.TestCase ):
def __init__( self : Optional[int] , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[Any]=7 , __lowerCamelCase : Tuple=3 , __lowerCamelCase : int=18 , __lowerCamelCase : Union[str, Any]=30 , __lowerCamelCase : Tuple=400 , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : Tuple=None , __lowerCamelCase : int=True , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Tuple=True , __lowerCamelCase : Dict=[0.5, 0.5, 0.5] , __lowerCamelCase : Dict=[0.5, 0.5, 0.5] , ):
snake_case__ : Optional[int] = parent
snake_case__ : str = batch_size
snake_case__ : Any = num_channels
snake_case__ : Dict = image_size
snake_case__ : Union[str, Any] = min_resolution
snake_case__ : Dict = max_resolution
snake_case__ : Tuple = do_resize
snake_case__ : str = size if size is not None else {'height': 18, 'width': 20}
snake_case__ : Any = do_thumbnail
snake_case__ : List[str] = do_align_axis
snake_case__ : Any = do_pad
snake_case__ : int = do_normalize
snake_case__ : List[str] = image_mean
snake_case__ : str = image_std
def _lowerCAmelCase ( self : Dict ):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_thumbnail": self.do_thumbnail,
"do_align_long_axis": self.do_align_axis,
"do_pad": self.do_pad,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
}
@require_torch
@require_vision
class lowercase_ ( lowerCAmelCase_ , unittest.TestCase ):
A_ = DonutImageProcessor if is_vision_available() else None
def _lowerCAmelCase ( self : Optional[Any] ):
snake_case__ : List[str] = DonutImageProcessingTester(self )
@property
def _lowerCAmelCase ( self : List[str] ):
return self.image_processor_tester.prepare_image_processor_dict()
def _lowerCAmelCase ( self : List[Any] ):
snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(UpperCamelCase__ , 'do_resize' ) )
self.assertTrue(hasattr(UpperCamelCase__ , 'size' ) )
self.assertTrue(hasattr(UpperCamelCase__ , 'do_thumbnail' ) )
self.assertTrue(hasattr(UpperCamelCase__ , 'do_align_long_axis' ) )
self.assertTrue(hasattr(UpperCamelCase__ , 'do_pad' ) )
self.assertTrue(hasattr(UpperCamelCase__ , 'do_normalize' ) )
self.assertTrue(hasattr(UpperCamelCase__ , 'image_mean' ) )
self.assertTrue(hasattr(UpperCamelCase__ , 'image_std' ) )
def _lowerCAmelCase ( self : Dict ):
snake_case__ : Any = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'height': 18, 'width': 20} )
snake_case__ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {'height': 42, 'width': 42} )
# Previous config had dimensions in (width, height) order
snake_case__ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) )
self.assertEqual(image_processor.size , {'height': 84, 'width': 42} )
def _lowerCAmelCase ( self : Dict ):
pass
@is_flaky()
def _lowerCAmelCase ( self : Optional[Any] ):
snake_case__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
snake_case__ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase__ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase__ , Image.Image )
# Test not batched input
snake_case__ : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
# Test batched
snake_case__ : str = image_processing(UpperCamelCase__ , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
@is_flaky()
def _lowerCAmelCase ( self : List[str] ):
snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
snake_case__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase__ , numpify=UpperCamelCase__ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase__ , np.ndarray )
# Test not batched input
snake_case__ : Union[str, 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.size['height'],
self.image_processor_tester.size['width'],
) , )
# Test batched
snake_case__ : Optional[Any] = image_processing(UpperCamelCase__ , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
@is_flaky()
def _lowerCAmelCase ( self : Dict ):
snake_case__ : List[Any] = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
snake_case__ : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase__ , torchify=UpperCamelCase__ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase__ , torch.Tensor )
# Test not batched input
snake_case__ : 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.size['height'],
self.image_processor_tester.size['width'],
) , )
# Test batched
snake_case__ : Optional[int] = image_processing(UpperCamelCase__ , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
| 270 |
import argparse
from pathlib import Path
from typing import Dict, OrderedDict, Tuple
import torch
from audiocraft.models import MusicGen
from transformers import (
AutoFeatureExtractor,
AutoTokenizer,
EncodecModel,
MusicgenDecoderConfig,
MusicgenForConditionalGeneration,
MusicgenProcessor,
TaEncoderModel,
)
from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM
from transformers.utils import logging
logging.set_verbosity_info()
a = logging.get_logger(__name__)
a = ['model.decoder.embed_positions.weights']
def UpperCAmelCase_ ( UpperCAmelCase__ ):
if "emb" in name:
lowercase_ = name.replace("""emb""" , """model.decoder.embed_tokens""" )
if "transformer" in name:
lowercase_ = name.replace("""transformer""" , """model.decoder""" )
if "cross_attention" in name:
lowercase_ = name.replace("""cross_attention""" , """encoder_attn""" )
if "linear1" in name:
lowercase_ = name.replace("""linear1""" , """fc1""" )
if "linear2" in name:
lowercase_ = name.replace("""linear2""" , """fc2""" )
if "norm1" in name:
lowercase_ = name.replace("""norm1""" , """self_attn_layer_norm""" )
if "norm_cross" in name:
lowercase_ = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" )
if "norm2" in name:
lowercase_ = name.replace("""norm2""" , """final_layer_norm""" )
if "out_norm" in name:
lowercase_ = name.replace("""out_norm""" , """model.decoder.layer_norm""" )
if "linears" in name:
lowercase_ = name.replace("""linears""" , """lm_heads""" )
if "condition_provider.conditioners.description.output_proj" in name:
lowercase_ = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" )
return name
def UpperCAmelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ ):
lowercase_ = list(state_dict.keys() )
lowercase_ = {}
for key in keys:
lowercase_ = state_dict.pop(UpperCAmelCase__ )
lowercase_ = rename_keys(UpperCAmelCase__ )
if "in_proj_weight" in key:
# split fused qkv proj
lowercase_ = val[:hidden_size, :]
lowercase_ = val[hidden_size : 2 * hidden_size, :]
lowercase_ = val[-hidden_size:, :]
elif "enc_to_dec_proj" in key:
lowercase_ = val
else:
lowercase_ = val
return state_dict, enc_dec_proj_state_dict
def UpperCAmelCase_ ( UpperCAmelCase__ ):
if checkpoint == "small":
# default config values
lowercase_ = 1_0_2_4
lowercase_ = 2_4
lowercase_ = 1_6
elif checkpoint == "medium":
lowercase_ = 1_5_3_6
lowercase_ = 4_8
lowercase_ = 2_4
elif checkpoint == "large":
lowercase_ = 2_0_4_8
lowercase_ = 4_8
lowercase_ = 3_2
else:
raise ValueError(F'''Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.''' )
lowercase_ = MusicgenDecoderConfig(
hidden_size=UpperCAmelCase__ , ffn_dim=hidden_size * 4 , num_hidden_layers=UpperCAmelCase__ , num_attention_heads=UpperCAmelCase__ , )
return config
@torch.no_grad()
def UpperCAmelCase_ ( UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__="cpu" ):
lowercase_ = MusicGen.get_pretrained(UpperCAmelCase__ , device=UpperCAmelCase__ )
lowercase_ = decoder_config_from_checkpoint(UpperCAmelCase__ )
lowercase_ = fairseq_model.lm.state_dict()
lowercase_ , lowercase_ = rename_state_dict(
UpperCAmelCase__ , hidden_size=decoder_config.hidden_size )
lowercase_ = TaEncoderModel.from_pretrained("""t5-base""" )
lowercase_ = EncodecModel.from_pretrained("""facebook/encodec_32khz""" )
lowercase_ = MusicgenForCausalLM(UpperCAmelCase__ ).eval()
# load all decoder weights - expect that we'll be missing embeddings and enc-dec projection
lowercase_ , lowercase_ = decoder.load_state_dict(UpperCAmelCase__ , strict=UpperCAmelCase__ )
for key in missing_keys.copy():
if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS:
missing_keys.remove(UpperCAmelCase__ )
if len(UpperCAmelCase__ ) > 0:
raise ValueError(F'''Missing key(s) in state_dict: {missing_keys}''' )
if len(UpperCAmelCase__ ) > 0:
raise ValueError(F'''Unexpected key(s) in state_dict: {unexpected_keys}''' )
# init the composite model
lowercase_ = MusicgenForConditionalGeneration(text_encoder=UpperCAmelCase__ , audio_encoder=UpperCAmelCase__ , decoder=UpperCAmelCase__ )
# load the pre-trained enc-dec projection (from the decoder state dict)
model.enc_to_dec_proj.load_state_dict(UpperCAmelCase__ )
# check we can do a forward pass
lowercase_ = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 )
lowercase_ = input_ids.reshape(2 * 4 , -1 )
with torch.no_grad():
lowercase_ = model(input_ids=UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ ).logits
if logits.shape != (8, 1, 2_0_4_8):
raise ValueError("""Incorrect shape for logits""" )
# now construct the processor
lowercase_ = AutoTokenizer.from_pretrained("""t5-base""" )
lowercase_ = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" )
lowercase_ = MusicgenProcessor(feature_extractor=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ )
# set the appropriate bos/pad token ids
lowercase_ = 2_0_4_8
lowercase_ = 2_0_4_8
# set other default generation config params
lowercase_ = int(3_0 * audio_encoder.config.frame_rate )
lowercase_ = True
lowercase_ = 3.0
if pytorch_dump_folder is not None:
Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ )
logger.info(F'''Saving model {checkpoint} to {pytorch_dump_folder}''' )
model.save_pretrained(UpperCAmelCase__ )
processor.save_pretrained(UpperCAmelCase__ )
if repo_id:
logger.info(F'''Pushing model {checkpoint} to {repo_id}''' )
model.push_to_hub(UpperCAmelCase__ )
processor.push_to_hub(UpperCAmelCase__ )
if __name__ == "__main__":
a = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--checkpoint',
default='small',
type=str,
help='Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.',
)
parser.add_argument(
'--pytorch_dump_folder',
required=True,
default=None,
type=str,
help='Path to the output PyTorch model directory.',
)
parser.add_argument(
'--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.'
)
parser.add_argument(
'--device', default='cpu', type=str, help='Torch device to run the conversion, either cpu or cuda.'
)
a = parser.parse_args()
convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
| 412 | 0 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
A_ = logging.get_logger(__name__)
A_ = {
"tanreinama/GPTSAN-2.8B-spout_is_uniform": (
"https://huggingface.co/tanreinama/GPTSAN-2.8B-spout_is_uniform/resolve/main/config.json"
),
}
class UpperCAmelCase ( UpperCAmelCase__ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ = 'gptsan-japanese'
SCREAMING_SNAKE_CASE_ = [
'past_key_values',
]
SCREAMING_SNAKE_CASE_ = {
'hidden_size': 'd_model',
'num_attention_heads': 'num_heads',
'num_hidden_layers': 'num_layers',
}
def __init__( self , SCREAMING_SNAKE_CASE_=36000 , SCREAMING_SNAKE_CASE_=1280 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=8192 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=128 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=128 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=1E-5 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_="float32" , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=0.002 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=35998 , SCREAMING_SNAKE_CASE_=35995 , SCREAMING_SNAKE_CASE_=35999 , **SCREAMING_SNAKE_CASE_ , ) -> List[str]:
'''simple docstring'''
lowerCamelCase_ = vocab_size
lowerCamelCase_ = max_position_embeddings
lowerCamelCase_ = d_model
lowerCamelCase_ = d_ff
lowerCamelCase_ = d_ext
lowerCamelCase_ = d_spout
lowerCamelCase_ = num_switch_layers
lowerCamelCase_ = num_ext_layers
lowerCamelCase_ = num_switch_layers + num_ext_layers
lowerCamelCase_ = num_heads
lowerCamelCase_ = num_experts
lowerCamelCase_ = expert_capacity
lowerCamelCase_ = dropout_rate
lowerCamelCase_ = layer_norm_epsilon
lowerCamelCase_ = router_bias
lowerCamelCase_ = router_jitter_noise
lowerCamelCase_ = router_dtype
lowerCamelCase_ = router_ignore_padding_tokens
lowerCamelCase_ = output_hidden_states
lowerCamelCase_ = output_attentions
lowerCamelCase_ = initializer_factor
lowerCamelCase_ = output_router_logits
lowerCamelCase_ = use_cache
super().__init__(
separator_token_id=SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
| 384 |
'''simple docstring'''
A_ = {
"a": "AAAAA",
"b": "AAAAB",
"c": "AAABA",
"d": "AAABB",
"e": "AABAA",
"f": "AABAB",
"g": "AABBA",
"h": "AABBB",
"i": "ABAAA",
"j": "BBBAA",
"k": "ABAAB",
"l": "ABABA",
"m": "ABABB",
"n": "ABBAA",
"o": "ABBAB",
"p": "ABBBA",
"q": "ABBBB",
"r": "BAAAA",
"s": "BAAAB",
"t": "BAABA",
"u": "BAABB",
"v": "BBBAB",
"w": "BABAA",
"x": "BABAB",
"y": "BABBA",
"z": "BABBB",
" ": " ",
}
A_ = {value: key for key, value in encode_dict.items()}
def _UpperCamelCase ( __UpperCamelCase ) -> str:
lowerCamelCase_ = ''
for letter in word.lower():
if letter.isalpha() or letter == " ":
encoded += encode_dict[letter]
else:
raise Exception('encode() accepts only letters of the alphabet and spaces' )
return encoded
def _UpperCamelCase ( __UpperCamelCase ) -> str:
if set(__UpperCamelCase ) - {"A", "B", " "} != set():
raise Exception('decode() accepts only \'A\', \'B\' and spaces' )
lowerCamelCase_ = ''
for word in coded.split():
while len(__UpperCamelCase ) != 0:
decoded += decode_dict[word[:5]]
lowerCamelCase_ = word[5:]
decoded += " "
return decoded.strip()
if __name__ == "__main__":
from doctest import testmod
testmod()
| 384 | 1 |
from __future__ import annotations
def __a ( lowerCAmelCase_ : list ,lowerCAmelCase_ : int ) -> Union[str, Any]:
'''simple docstring'''
if len(lowerCAmelCase_ ) <= 1 or n <= 1:
return
insert_next(lowerCAmelCase_ ,n - 1 )
rec_insertion_sort(lowerCAmelCase_ ,n - 1 )
def __a ( lowerCAmelCase_ : list ,lowerCAmelCase_ : int ) -> int:
'''simple docstring'''
if index >= len(lowerCAmelCase_ ) or collection[index - 1] <= collection[index]:
return
# Swaps adjacent elements since they are not in ascending order
UpperCAmelCase_, UpperCAmelCase_= (
collection[index],
collection[index - 1],
)
insert_next(lowerCAmelCase_ ,index + 1 )
if __name__ == "__main__":
__A = input('''Enter integers separated by spaces: ''')
__A = [int(num) for num in numbers.split()]
rec_insertion_sort(number_list, len(number_list))
print(number_list)
| 593 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__A = {'''configuration_yolos''': ['''YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''YolosConfig''', '''YolosOnnxConfig''']}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ['''YolosFeatureExtractor''']
__A = ['''YolosImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'''YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''YolosForObjectDetection''',
'''YolosModel''',
'''YolosPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_yolos import YolosFeatureExtractor
from .image_processing_yolos import YolosImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_yolos import (
YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST,
YolosForObjectDetection,
YolosModel,
YolosPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 593 | 1 |
'''simple docstring'''
from pathlib import PurePosixPath
from typing import Optional
import fsspec
from fsspec import AbstractFileSystem
from huggingface_hub.hf_api import DatasetInfo
from ..utils.file_utils import get_authentication_headers_for_url
from ..utils.hub import hf_hub_url
class SCREAMING_SNAKE_CASE__ ( __UpperCamelCase ):
lowercase__ = ""
lowercase__ = "hf-legacy" # "hf://"" is reserved for hffs
def __init__( self , __UpperCamelCase = None , __UpperCamelCase = None , **__UpperCamelCase , ):
'''simple docstring'''
super().__init__(self , **__UpperCamelCase )
__a : int = repo_info
__a : int = token
__a : Any = None
def __lowerCamelCase ( self ):
'''simple docstring'''
if self.dir_cache is None:
__a : Union[str, Any] = {}
for hf_file in self.repo_info.siblings:
# TODO(QL): add sizes
__a : List[str] = {
"""name""": hf_file.rfilename,
"""size""": None,
"""type""": """file""",
}
self.dir_cache.update(
{
str(__UpperCamelCase ): {"""name""": str(__UpperCamelCase ), """size""": None, """type""": """directory"""}
for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1]
} )
def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase = "rb" , **__UpperCamelCase , ):
'''simple docstring'''
if not isinstance(self.repo_info , __UpperCamelCase ):
raise NotImplementedError(f"""Open is only implemented for dataset repositories, but got {self.repo_info}""" )
__a : Any = hf_hub_url(self.repo_info.id , __UpperCamelCase , revision=self.repo_info.sha )
return fsspec.open(
__UpperCamelCase , mode=__UpperCamelCase , headers=get_authentication_headers_for_url(__UpperCamelCase , use_auth_token=self.token ) , client_kwargs={"""trust_env""": True} , ).open()
def __lowerCamelCase ( self , __UpperCamelCase , **__UpperCamelCase ):
'''simple docstring'''
self._get_dirs()
__a : str = self._strip_protocol(__UpperCamelCase )
if path in self.dir_cache:
return self.dir_cache[path]
else:
raise FileNotFoundError(__UpperCamelCase )
def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase=False , **__UpperCamelCase ):
'''simple docstring'''
self._get_dirs()
__a : int = PurePosixPath(path.strip("""/""" ) )
__a : List[str] = {}
for p, f in self.dir_cache.items():
__a : str = PurePosixPath(p.strip("""/""" ) )
__a : Optional[int] = p.parent
if root == path:
__a : List[str] = f
__a : str = list(paths.values() )
if detail:
return out
else:
return sorted(f["""name"""] for f in out ) | 703 |
'''simple docstring'''
import unittest
from transformers import (
MODEL_FOR_OBJECT_DETECTION_MAPPING,
AutoFeatureExtractor,
AutoModelForObjectDetection,
ObjectDetectionPipeline,
is_vision_available,
pipeline,
)
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_pytesseract,
require_tf,
require_timm,
require_torch,
require_vision,
slow,
)
from .test_pipelines_common import ANY
if is_vision_available():
from PIL import Image
else:
class SCREAMING_SNAKE_CASE__ :
@staticmethod
def __lowerCamelCase ( *__UpperCamelCase , **__UpperCamelCase ):
'''simple docstring'''
pass
@is_pipeline_test
@require_vision
@require_timm
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
lowercase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING
def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
'''simple docstring'''
__a : Optional[Any] = ObjectDetectionPipeline(model=__UpperCamelCase , image_processor=__UpperCamelCase )
return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"]
def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase ):
'''simple docstring'''
__a : List[str] = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 )
self.assertGreater(len(__UpperCamelCase ) , 0 )
for detected_object in outputs:
self.assertEqual(
__UpperCamelCase , {
"""score""": ANY(__UpperCamelCase ),
"""label""": ANY(__UpperCamelCase ),
"""box""": {"""xmin""": ANY(__UpperCamelCase ), """ymin""": ANY(__UpperCamelCase ), """xmax""": ANY(__UpperCamelCase ), """ymax""": ANY(__UpperCamelCase )},
} , )
import datasets
__a : Optional[int] = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" )
__a : Tuple = [
Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ),
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
# RGBA
dataset[0]["""file"""],
# LA
dataset[1]["""file"""],
# L
dataset[2]["""file"""],
]
__a : Any = object_detector(__UpperCamelCase , threshold=0.0 )
self.assertEqual(len(__UpperCamelCase ) , len(__UpperCamelCase ) )
for outputs in batch_outputs:
self.assertGreater(len(__UpperCamelCase ) , 0 )
for detected_object in outputs:
self.assertEqual(
__UpperCamelCase , {
"""score""": ANY(__UpperCamelCase ),
"""label""": ANY(__UpperCamelCase ),
"""box""": {"""xmin""": ANY(__UpperCamelCase ), """ymin""": ANY(__UpperCamelCase ), """xmax""": ANY(__UpperCamelCase ), """ymax""": ANY(__UpperCamelCase )},
} , )
@require_tf
@unittest.skip("""Object detection not implemented in TF""" )
def __lowerCamelCase ( self ):
'''simple docstring'''
pass
@require_torch
def __lowerCamelCase ( self ):
'''simple docstring'''
__a : Optional[Any] = """hf-internal-testing/tiny-detr-mobilenetsv3"""
__a : Dict = AutoModelForObjectDetection.from_pretrained(__UpperCamelCase )
__a : Optional[Any] = AutoFeatureExtractor.from_pretrained(__UpperCamelCase )
__a : str = ObjectDetectionPipeline(model=__UpperCamelCase , feature_extractor=__UpperCamelCase )
__a : Optional[int] = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 )
self.assertEqual(
nested_simplify(__UpperCamelCase , decimals=4 ) , [
{"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}},
{"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}},
] , )
__a : Union[str, Any] = object_detector(
[
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
] , threshold=0.0 , )
self.assertEqual(
nested_simplify(__UpperCamelCase , decimals=4 ) , [
[
{"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}},
{"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}},
],
[
{"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}},
{"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}},
],
] , )
@require_torch
@slow
def __lowerCamelCase ( self ):
'''simple docstring'''
__a : str = """facebook/detr-resnet-50"""
__a : Dict = AutoModelForObjectDetection.from_pretrained(__UpperCamelCase )
__a : int = AutoFeatureExtractor.from_pretrained(__UpperCamelCase )
__a : int = ObjectDetectionPipeline(model=__UpperCamelCase , feature_extractor=__UpperCamelCase )
__a : Any = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" )
self.assertEqual(
nested_simplify(__UpperCamelCase , decimals=4 ) , [
{"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}},
{"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}},
{"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}},
{"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
{"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
] , )
__a : Optional[Any] = object_detector(
[
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
] )
self.assertEqual(
nested_simplify(__UpperCamelCase , decimals=4 ) , [
[
{"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}},
{"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}},
{"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}},
{"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
{"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
],
[
{"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}},
{"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}},
{"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}},
{"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
{"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
],
] , )
@require_torch
@slow
def __lowerCamelCase ( self ):
'''simple docstring'''
__a : int = """facebook/detr-resnet-50"""
__a : Optional[int] = pipeline("""object-detection""" , model=__UpperCamelCase )
__a : Optional[int] = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" )
self.assertEqual(
nested_simplify(__UpperCamelCase , decimals=4 ) , [
{"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}},
{"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}},
{"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}},
{"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
{"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
] , )
__a : List[str] = object_detector(
[
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
] )
self.assertEqual(
nested_simplify(__UpperCamelCase , decimals=4 ) , [
[
{"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}},
{"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}},
{"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}},
{"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
{"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
],
[
{"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}},
{"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}},
{"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}},
{"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
{"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
],
] , )
@require_torch
@slow
def __lowerCamelCase ( self ):
'''simple docstring'''
__a : Union[str, Any] = 0.9_9_8_5
__a : Union[str, Any] = """facebook/detr-resnet-50"""
__a : Optional[int] = pipeline("""object-detection""" , model=__UpperCamelCase )
__a : Union[str, Any] = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__UpperCamelCase )
self.assertEqual(
nested_simplify(__UpperCamelCase , decimals=4 ) , [
{"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}},
{"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}},
] , )
@require_torch
@require_pytesseract
@slow
def __lowerCamelCase ( self ):
'''simple docstring'''
__a : str = """Narsil/layoutlmv3-finetuned-funsd"""
__a : List[Any] = 0.9_9_9_3
__a : Dict = pipeline("""object-detection""" , model=__UpperCamelCase , threshold=__UpperCamelCase )
__a : List[str] = object_detector(
"""https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" )
self.assertEqual(
nested_simplify(__UpperCamelCase , decimals=4 ) , [
{"""score""": 0.9_9_9_3, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}},
{"""score""": 0.9_9_9_3, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}},
] , ) | 697 | 0 |
'''simple docstring'''
import argparse
import gdown
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from transformers import (
CLIPTokenizer,
CLIPTokenizerFast,
VideoMAEImageProcessor,
XCLIPConfig,
XCLIPModel,
XCLIPProcessor,
XCLIPTextConfig,
XCLIPVisionConfig,
)
def _lowerCAmelCase ( __snake_case : int , __snake_case : Tuple ) -> List[str]:
__A : Tuple = XCLIPTextConfig()
# derive patch size from model name
__A : Dict = model_name.find('patch' )
__A : Dict = int(model_name[start_idx + len('patch' ) : start_idx + len('patch' ) + 2] )
__A : List[str] = XCLIPVisionConfig(patch_size=__snake_case , num_frames=__snake_case )
if "large" in model_name:
__A : Dict = 7_68
__A : List[Any] = 30_72
__A : int = 12
__A : Tuple = 10_24
__A : str = 40_96
__A : Any = 16
__A : str = 24
__A : Dict = 7_68
__A : Any = 30_72
if model_name == "xclip-large-patch14-16-frames":
__A : List[str] = 3_36
__A : List[str] = XCLIPConfig.from_text_vision_configs(__snake_case , __snake_case )
if "large" in model_name:
__A : List[str] = 7_68
return config
def _lowerCAmelCase ( __snake_case : Optional[Any] ) -> Dict:
# text encoder
if name == "token_embedding.weight":
__A : str = name.replace('token_embedding.weight' , 'text_model.embeddings.token_embedding.weight' )
if name == "positional_embedding":
__A : Any = name.replace('positional_embedding' , 'text_model.embeddings.position_embedding.weight' )
if "ln_1" in name:
__A : List[Any] = name.replace('ln_1' , 'layer_norm1' )
if "ln_2" in name:
__A : Union[str, Any] = name.replace('ln_2' , 'layer_norm2' )
if "c_fc" in name:
__A : Any = name.replace('c_fc' , 'fc1' )
if "c_proj" in name:
__A : Optional[Any] = name.replace('c_proj' , 'fc2' )
if name.startswith('transformer.resblocks' ):
__A : Optional[Any] = name.replace('transformer.resblocks' , 'text_model.encoder.layers' )
if "attn.out_proj" in name and "message" not in name:
__A : Union[str, Any] = name.replace('attn.out_proj' , 'self_attn.out_proj' )
if "ln_final" in name:
__A : str = name.replace('ln_final' , 'text_model.final_layer_norm' )
# visual encoder
if name == "visual.class_embedding":
__A : Optional[int] = name.replace('visual.class_embedding' , 'vision_model.embeddings.class_embedding' )
if name == "visual.positional_embedding":
__A : Optional[Any] = name.replace('visual.positional_embedding' , 'vision_model.embeddings.position_embedding.weight' )
if name.startswith('visual.transformer.resblocks' ):
__A : Tuple = name.replace('visual.transformer.resblocks' , 'vision_model.encoder.layers' )
if "visual.conv1" in name:
__A : int = name.replace('visual.conv1' , 'vision_model.embeddings.patch_embedding' )
if "visual.ln_pre" in name:
__A : List[Any] = name.replace('visual.ln_pre' , 'vision_model.pre_layernorm' )
if "visual.ln_post" in name:
__A : List[Any] = name.replace('visual.ln_post' , 'vision_model.post_layernorm' )
if "visual.proj" in name:
__A : Optional[int] = name.replace('visual.proj' , 'visual_projection.weight' )
if "text_projection" in name:
__A : Any = name.replace('text_projection' , 'text_projection.weight' )
# things on top
if "prompts_visual_proj" in name:
__A : List[Any] = name.replace('prompts_visual_proj' , 'prompts_visual_projection' )
if "prompts_visual_ln" in name:
__A : int = name.replace('prompts_visual_ln' , 'prompts_visual_layernorm' )
# mit
if name == "mit.positional_embedding":
__A : Union[str, Any] = name.replace('positional' , 'position' )
if name.startswith('mit.resblocks' ):
__A : Optional[int] = name.replace('mit.resblocks' , 'mit.encoder.layers' )
# prompts generator
if name.startswith('prompts_generator.norm' ):
__A : Any = name.replace('prompts_generator.norm' , 'prompts_generator.layernorm' )
return name
def _lowerCAmelCase ( __snake_case : Optional[int] , __snake_case : Optional[int] ) -> Tuple:
for key in orig_state_dict.copy().keys():
__A : Dict = orig_state_dict.pop(__snake_case )
if "attn.in_proj" in key:
__A : Dict = key.split('.' )
if key.startswith('visual' ):
__A : Dict = key_split[3]
__A : Tuple = config.vision_config.hidden_size
if "message_attn" in key:
if "weight" in key:
__A : Dict = val[
:dim, :
]
__A : Tuple = val[
dim : dim * 2, :
]
__A : Optional[Any] = val[
-dim:, :
]
else:
__A : Optional[Any] = val[
:dim
]
__A : Optional[int] = val[
dim : dim * 2
]
__A : Tuple = val[
-dim:
]
else:
if "weight" in key:
__A : Dict = val[
:dim, :
]
__A : Optional[Any] = val[
dim : dim * 2, :
]
__A : Any = val[
-dim:, :
]
else:
__A : Union[str, Any] = val[:dim]
__A : Union[str, Any] = val[
dim : dim * 2
]
__A : Optional[int] = val[-dim:]
elif key.startswith('mit' ):
__A : List[str] = key_split[2]
__A : Optional[Any] = config.vision_config.mit_hidden_size
if "weight" in key:
__A : Optional[Any] = val[:dim, :]
__A : Optional[Any] = val[dim : dim * 2, :]
__A : List[Any] = val[-dim:, :]
else:
__A : str = val[:dim]
__A : Dict = val[dim : dim * 2]
__A : Tuple = val[-dim:]
else:
__A : Union[str, Any] = key_split[2]
__A : Optional[Any] = config.text_config.hidden_size
if "weight" in key:
__A : List[str] = val[:dim, :]
__A : int = val[
dim : dim * 2, :
]
__A : Optional[Any] = val[-dim:, :]
else:
__A : Union[str, Any] = val[:dim]
__A : Tuple = val[
dim : dim * 2
]
__A : str = val[-dim:]
else:
__A : Dict = rename_key(__snake_case )
if new_key_name in ["visual_projection.weight", "text_projection.weight"]:
__A : List[Any] = val.T
__A : Any = val
return orig_state_dict
def _lowerCAmelCase ( __snake_case : Union[str, Any] ) -> Optional[int]:
if num_frames == 8:
__A : Any = 'eating_spaghetti_8_frames.npy'
elif num_frames == 16:
__A : List[str] = 'eating_spaghetti.npy'
elif num_frames == 32:
__A : int = 'eating_spaghetti_32_frames.npy'
__A : Any = hf_hub_download(
repo_id='hf-internal-testing/spaghetti-video' , filename=__snake_case , repo_type='dataset' , )
__A : Any = np.load(__snake_case )
return list(__snake_case )
def _lowerCAmelCase ( __snake_case : Union[str, Any] , __snake_case : Tuple=None , __snake_case : List[Any]=False ) -> Union[str, Any]:
__A : List[Any] = {
# fully supervised kinetics-400 checkpoints
'xclip-base-patch32': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth',
'xclip-base-patch32-16-frames': (
'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth'
),
'xclip-base-patch16': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth',
'xclip-base-patch16-16-frames': (
'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth'
),
'xclip-large-patch14': 'https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&export=download&confirm=t&uuid=b26caedc-88e2-473e-830a-9d158b653cdb',
'xclip-large-patch14-16-frames': 'https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&export=download&confirm=t&uuid=538fa810-e671-4050-b385-9a623f89804f',
# fully supervised kinetics-600 checkpoints
'xclip-base-patch16-kinetics-600': (
'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth'
),
'xclip-base-patch16-kinetics-600-16-frames': (
'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth'
),
'xclip-large-patch14-kinetics-600': 'https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&export=download&confirm=t&uuid=141d4977-4a65-44ae-864f-4b0c19f838be',
# few shot
'xclip-base-patch16-hmdb-2-shot': (
'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth'
),
'xclip-base-patch16-hmdb-4-shot': (
'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth'
),
'xclip-base-patch16-hmdb-8-shot': (
'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth'
),
'xclip-base-patch16-hmdb-16-shot': (
'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth'
),
'xclip-base-patch16-ucf-2-shot': (
'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth'
),
'xclip-base-patch16-ucf-4-shot': (
'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth'
),
'xclip-base-patch16-ucf-8-shot': (
'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth'
),
'xclip-base-patch16-ucf-16-shot': (
'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth'
),
# zero shot
'xclip-base-patch16-zero-shot': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth',
}
__A : List[Any] = model_to_url[model_name]
__A : List[Any] = 8
if "16-frames" in model_name:
__A : int = 16
elif "shot" in model_name:
__A : Optional[int] = 32
__A : List[str] = get_xclip_config(__snake_case , __snake_case )
__A : str = XCLIPModel(__snake_case )
model.eval()
if "drive" in checkpoint_url:
__A : List[str] = 'pytorch_model.bin'
gdown.cached_download(__snake_case , __snake_case , quiet=__snake_case )
__A : int = torch.load(__snake_case , map_location='cpu' )['model']
else:
__A : Optional[Any] = torch.hub.load_state_dict_from_url(__snake_case )['model']
__A : Dict = convert_state_dict(__snake_case , __snake_case )
__A : Union[str, Any] = XCLIPModel(__snake_case )
__A ,__A : List[str] = model.load_state_dict(__snake_case , strict=__snake_case )
assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"]
model.eval()
__A : List[str] = 3_36 if model_name == 'xclip-large-patch14-16-frames' else 2_24
__A : Optional[Any] = VideoMAEImageProcessor(size=__snake_case )
__A : Dict = CLIPTokenizer.from_pretrained('openai/clip-vit-base-patch32' )
__A : Optional[Any] = CLIPTokenizerFast.from_pretrained('openai/clip-vit-base-patch32' )
__A : str = XCLIPProcessor(image_processor=__snake_case , tokenizer=__snake_case )
__A : List[Any] = prepare_video(__snake_case )
__A : List[Any] = processor(
text=['playing sports', 'eating spaghetti', 'go shopping'] , videos=__snake_case , return_tensors='pt' , padding=__snake_case )
print('Shape of pixel values:' , inputs.pixel_values.shape )
with torch.no_grad():
__A : Optional[int] = model(**__snake_case )
# Verify outputs
__A : List[str] = outputs.logits_per_video
__A : Tuple = logits_per_video.softmax(dim=1 )
print('Probs:' , __snake_case )
# kinetics-400
if model_name == "xclip-base-patch32":
__A : List[Any] = torch.tensor([[0.0_019, 0.9_951, 0.0_030]] )
elif model_name == "xclip-base-patch32-16-frames":
__A : str = torch.tensor([[7.0_9_9_9e-0_4, 9.9_8_8_3e-0_1, 4.5_5_8_0e-0_4]] )
elif model_name == "xclip-base-patch16":
__A : List[Any] = torch.tensor([[0.0_083, 0.9_681, 0.0_236]] )
elif model_name == "xclip-base-patch16-16-frames":
__A : int = torch.tensor([[7.6_9_3_7e-0_4, 9.9_7_2_8e-0_1, 1.9_4_7_3e-0_3]] )
elif model_name == "xclip-large-patch14":
__A : Any = torch.tensor([[0.0_062, 0.9_864, 0.0_075]] )
elif model_name == "xclip-large-patch14-16-frames":
__A : Any = torch.tensor([[3.3_8_7_7e-0_4, 9.9_9_3_7e-0_1, 2.8_8_8_8e-0_4]] )
# kinetics-600
elif model_name == "xclip-base-patch16-kinetics-600":
__A : Optional[int] = torch.tensor([[0.0_555, 0.8_914, 0.0_531]] )
elif model_name == "xclip-base-patch16-kinetics-600-16-frames":
__A : int = torch.tensor([[3.8_5_5_4e-0_4, 9.9_9_2_9e-0_1, 3.2_7_5_4e-0_4]] )
elif model_name == "xclip-large-patch14-kinetics-600":
__A : List[Any] = torch.tensor([[0.0_036, 0.9_920, 0.0_045]] )
# few shot
elif model_name == "xclip-base-patch16-hmdb-2-shot":
__A : Optional[int] = torch.tensor([[7.1_8_9_0e-0_6, 9.9_9_9_4e-0_1, 5.6_5_5_9e-0_5]] )
elif model_name == "xclip-base-patch16-hmdb-4-shot":
__A : int = torch.tensor([[1.0_3_2_0e-0_5, 9.9_9_9_3e-0_1, 6.2_4_3_5e-0_5]] )
elif model_name == "xclip-base-patch16-hmdb-8-shot":
__A : Dict = torch.tensor([[4.1_3_7_7e-0_6, 9.9_9_9_0e-0_1, 9.8_3_8_6e-0_5]] )
elif model_name == "xclip-base-patch16-hmdb-16-shot":
__A : Optional[Any] = torch.tensor([[4.1_3_4_7e-0_5, 9.9_9_6_2e-0_1, 3.3_4_1_1e-0_4]] )
elif model_name == "xclip-base-patch16-ucf-2-shot":
__A : List[Any] = torch.tensor([[8.5_8_5_7e-0_5, 9.9_9_2_8e-0_1, 6.3_2_9_1e-0_4]] )
elif model_name == "xclip-base-patch16-ucf-4-shot":
__A : str = torch.tensor([[8.5_8_5_7e-0_5, 9.9_9_2_8e-0_1, 6.3_2_9_1e-0_4]] )
elif model_name == "xclip-base-patch16-ucf-8-shot":
__A : str = torch.tensor([[0.0_027, 0.9_904, 0.0_070]] )
elif model_name == "xclip-base-patch16-ucf-16-shot":
__A : List[Any] = torch.tensor([[9.8_2_1_9e-0_4, 9.9_5_9_3e-0_1, 3.0_8_6_3e-0_3]] )
# zero shot
elif model_name == "xclip-base-patch16-zero-shot":
__A : Optional[Any] = torch.tensor([[3.5_0_8_2e-0_4, 9.9_7_8_5e-0_1, 1.7_9_6_6e-0_3]] )
else:
raise ValueError(f'Model name {model_name} not supported' )
assert torch.allclose(__snake_case , __snake_case , atol=1e-3 )
print('Looks ok!' )
if pytorch_dump_folder_path is not None:
print(f'Saving model {model_name} to {pytorch_dump_folder_path}' )
model.save_pretrained(__snake_case )
if push_to_hub:
print('Pushing model, processor and slow tokenizer files to the hub...' )
model.push_to_hub(__snake_case , organization='nielsr' )
processor.push_to_hub(__snake_case , organization='nielsr' )
slow_tokenizer.push_to_hub(__snake_case , organization='nielsr' )
if __name__ == "__main__":
lowercase__ : str = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--model_name''',
default='''xclip-base-patch32''',
type=str,
help='''Name of the model.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
)
parser.add_argument(
'''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
)
lowercase__ : Tuple = parser.parse_args()
convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub) | 8 |
'''simple docstring'''
from __future__ import annotations
import os
import tempfile
import unittest
from transformers import ConvBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFConvBertForMaskedLM,
TFConvBertForMultipleChoice,
TFConvBertForQuestionAnswering,
TFConvBertForSequenceClassification,
TFConvBertForTokenClassification,
TFConvBertModel,
)
class SCREAMING_SNAKE_CASE :
def __init__( self , _UpperCAmelCase , _UpperCAmelCase=13 , _UpperCAmelCase=7 , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=99 , _UpperCAmelCase=32 , _UpperCAmelCase=2 , _UpperCAmelCase=4 , _UpperCAmelCase=37 , _UpperCAmelCase="gelu" , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.1 , _UpperCAmelCase=512 , _UpperCAmelCase=16 , _UpperCAmelCase=2 , _UpperCAmelCase=0.02 , _UpperCAmelCase=3 , _UpperCAmelCase=4 , _UpperCAmelCase=None , ):
'''simple docstring'''
__A : Optional[int] = parent
__A : str = 13
__A : List[Any] = 7
__A : List[str] = True
__A : str = True
__A : Optional[Any] = True
__A : int = True
__A : Dict = 99
__A : Dict = 384
__A : Any = 2
__A : int = 4
__A : Optional[Any] = 37
__A : Optional[int] = 'gelu'
__A : Dict = 0.1
__A : Optional[int] = 0.1
__A : Any = 512
__A : int = 16
__A : List[str] = 2
__A : str = 0.02
__A : Any = 3
__A : str = 4
__A : Union[str, Any] = 128
__A : int = 2
__A : List[Any] = 9
__A : List[Any] = 1
__A : List[Any] = None
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
__A : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
__A : str = None
if self.use_input_mask:
__A : List[Any] = random_attention_mask([self.batch_size, self.seq_length])
__A : Optional[Any] = None
if self.use_token_type_ids:
__A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size)
__A : Optional[int] = None
__A : List[str] = None
__A : Dict = None
if self.use_labels:
__A : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size)
__A : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels)
__A : str = ids_tensor([self.batch_size] , self.num_choices)
__A : List[Any] = ConvBertConfig(
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 , return_dict=_UpperCAmelCase , )
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase):
'''simple docstring'''
__A : int = TFConvBertModel(config=_UpperCAmelCase)
__A : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
__A : Tuple = [input_ids, input_mask]
__A : Any = model(_UpperCAmelCase)
__A : Dict = model(_UpperCAmelCase)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase):
'''simple docstring'''
__A : str = TFConvBertForMaskedLM(config=_UpperCAmelCase)
__A : str = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
__A : str = model(_UpperCAmelCase)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size))
def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase):
'''simple docstring'''
__A : Optional[int] = self.num_labels
__A : Any = TFConvBertForSequenceClassification(config=_UpperCAmelCase)
__A : Optional[Any] = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
__A : Dict = model(_UpperCAmelCase)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase):
'''simple docstring'''
__A : Tuple = self.num_choices
__A : List[str] = TFConvBertForMultipleChoice(config=_UpperCAmelCase)
__A : int = tf.tile(tf.expand_dims(_UpperCAmelCase , 1) , (1, self.num_choices, 1))
__A : Optional[Any] = tf.tile(tf.expand_dims(_UpperCAmelCase , 1) , (1, self.num_choices, 1))
__A : List[Any] = tf.tile(tf.expand_dims(_UpperCAmelCase , 1) , (1, self.num_choices, 1))
__A : int = {
'input_ids': multiple_choice_inputs_ids,
'attention_mask': multiple_choice_input_mask,
'token_type_ids': multiple_choice_token_type_ids,
}
__A : Optional[Any] = model(_UpperCAmelCase)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices))
def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase):
'''simple docstring'''
__A : List[Any] = self.num_labels
__A : List[Any] = TFConvBertForTokenClassification(config=_UpperCAmelCase)
__A : str = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
__A : int = model(_UpperCAmelCase)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels))
def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase):
'''simple docstring'''
__A : Optional[Any] = TFConvBertForQuestionAnswering(config=_UpperCAmelCase)
__A : Any = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
__A : Union[str, Any] = model(_UpperCAmelCase)
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length))
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
__A : Optional[int] = self.prepare_config_and_inputs()
(
(
__A
) ,(
__A
) ,(
__A
) ,(
__A
) ,(
__A
) ,(
__A
) ,(
__A
) ,
) : Union[str, Any] = config_and_inputs
__A : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
return config, inputs_dict
@require_tf
class SCREAMING_SNAKE_CASE (a__ , a__ , unittest.TestCase ):
lowerCAmelCase = (
(
TFConvBertModel,
TFConvBertForMaskedLM,
TFConvBertForQuestionAnswering,
TFConvBertForSequenceClassification,
TFConvBertForTokenClassification,
TFConvBertForMultipleChoice,
)
if is_tf_available()
else ()
)
lowerCAmelCase = (
{
'''feature-extraction''': TFConvBertModel,
'''fill-mask''': TFConvBertForMaskedLM,
'''question-answering''': TFConvBertForQuestionAnswering,
'''text-classification''': TFConvBertForSequenceClassification,
'''token-classification''': TFConvBertForTokenClassification,
'''zero-shot''': TFConvBertForSequenceClassification,
}
if is_tf_available()
else {}
)
lowerCAmelCase = False
lowerCAmelCase = False
lowerCAmelCase = False
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
__A : int = TFConvBertModelTester(self)
__A : str = ConfigTester(self , config_class=_UpperCAmelCase , hidden_size=37)
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
__A : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_UpperCAmelCase)
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
__A : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*_UpperCAmelCase)
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
__A : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*_UpperCAmelCase)
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
__A : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*_UpperCAmelCase)
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
__A : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*_UpperCAmelCase)
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
__A : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*_UpperCAmelCase)
@slow
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
__A ,__A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
__A : List[str] = True
__A : List[str] = True
if hasattr(_UpperCAmelCase , 'use_cache'):
__A : List[Any] = True
__A : str = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length)
__A : Union[str, Any] = getattr(self.model_tester , 'key_length' , _UpperCAmelCase)
for model_class in self.all_model_classes:
__A : List[str] = self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase)
__A : Optional[int] = model_class(_UpperCAmelCase)
__A : Optional[Any] = len(model(_UpperCAmelCase))
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(_UpperCAmelCase , saved_model=_UpperCAmelCase)
__A : Union[str, Any] = os.path.join(_UpperCAmelCase , 'saved_model' , '1')
__A : Tuple = tf.keras.models.load_model(_UpperCAmelCase)
__A : str = model(_UpperCAmelCase)
if self.is_encoder_decoder:
__A : Optional[int] = outputs['encoder_hidden_states']
__A : str = outputs['encoder_attentions']
else:
__A : List[Any] = outputs['hidden_states']
__A : Optional[Any] = outputs['attentions']
self.assertEqual(len(_UpperCAmelCase) , _UpperCAmelCase)
__A : str = getattr(
self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1)
self.assertEqual(len(_UpperCAmelCase) , _UpperCAmelCase)
self.assertListEqual(
list(output_hidden_states[0].shape[-2:]) , [self.model_tester.seq_length, self.model_tester.hidden_size] , )
self.assertEqual(len(_UpperCAmelCase) , self.model_tester.num_hidden_layers)
self.assertListEqual(
list(output_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , )
@slow
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
__A : Dict = TFConvBertModel.from_pretrained('YituTech/conv-bert-base')
self.assertIsNotNone(_UpperCAmelCase)
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
__A ,__A : Dict = self.model_tester.prepare_config_and_inputs_for_common()
__A : Any = True
__A : str = getattr(self.model_tester , 'decoder_seq_length' , self.model_tester.seq_length)
__A : Any = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length)
__A : int = getattr(self.model_tester , 'key_length' , _UpperCAmelCase)
__A : Tuple = getattr(self.model_tester , 'key_length' , _UpperCAmelCase)
def check_decoder_attentions_output(_UpperCAmelCase):
__A : List[str] = len(_UpperCAmelCase)
self.assertEqual(out_len % 2 , 0)
__A : Any = outputs.decoder_attentions
self.assertEqual(len(_UpperCAmelCase) , self.model_tester.num_hidden_layers)
self.assertListEqual(
list(decoder_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , )
def check_encoder_attentions_output(_UpperCAmelCase):
__A : str = [
t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions)
]
self.assertEqual(len(_UpperCAmelCase) , self.model_tester.num_hidden_layers)
self.assertListEqual(
list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , )
for model_class in self.all_model_classes:
__A : Dict = True
__A : Any = False
__A : str = model_class(_UpperCAmelCase)
__A : List[str] = model(self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase))
__A : List[str] = len(_UpperCAmelCase)
self.assertEqual(config.output_hidden_states , _UpperCAmelCase)
check_encoder_attentions_output(_UpperCAmelCase)
if self.is_encoder_decoder:
__A : Union[str, Any] = model_class(_UpperCAmelCase)
__A : int = model(self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase))
self.assertEqual(config.output_hidden_states , _UpperCAmelCase)
check_decoder_attentions_output(_UpperCAmelCase)
# Check that output attentions can also be changed via the config
del inputs_dict["output_attentions"]
__A : int = True
__A : Tuple = model_class(_UpperCAmelCase)
__A : Dict = model(self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase))
self.assertEqual(config.output_hidden_states , _UpperCAmelCase)
check_encoder_attentions_output(_UpperCAmelCase)
# Check attention is always last and order is fine
__A : Any = True
__A : str = True
__A : Union[str, Any] = model_class(_UpperCAmelCase)
__A : Union[str, Any] = model(self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase))
self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_UpperCAmelCase))
self.assertEqual(model.config.output_hidden_states , _UpperCAmelCase)
check_encoder_attentions_output(_UpperCAmelCase)
@require_tf
class SCREAMING_SNAKE_CASE (unittest.TestCase ):
@slow
def SCREAMING_SNAKE_CASE ( self):
'''simple docstring'''
__A : Tuple = TFConvBertModel.from_pretrained('YituTech/conv-bert-base')
__A : str = tf.constant([[0, 1, 2, 3, 4, 5]])
__A : Optional[int] = model(_UpperCAmelCase)[0]
__A : List[Any] = [1, 6, 768]
self.assertEqual(output.shape , _UpperCAmelCase)
__A : Tuple = tf.constant(
[
[
[-0.03475493, -0.4686034, -0.30638832],
[0.22637248, -0.26988646, -0.7423424],
[0.10324868, -0.45013508, -0.58280784],
]
])
tf.debugging.assert_near(output[:, :3, :3] , _UpperCAmelCase , atol=1e-4) | 8 | 1 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_squeezebert import SqueezeBertTokenizer
__UpperCAmelCase = logging.get_logger(__name__)
__UpperCAmelCase = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
__UpperCAmelCase = {
"vocab_file": {
"squeezebert/squeezebert-uncased": (
"https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt"
),
"squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt",
"squeezebert/squeezebert-mnli-headless": (
"https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"squeezebert/squeezebert-uncased": (
"https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json"
),
"squeezebert/squeezebert-mnli": (
"https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json"
),
"squeezebert/squeezebert-mnli-headless": (
"https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json"
),
},
}
__UpperCAmelCase = {
"squeezebert/squeezebert-uncased": 5_12,
"squeezebert/squeezebert-mnli": 5_12,
"squeezebert/squeezebert-mnli-headless": 5_12,
}
__UpperCAmelCase = {
"squeezebert/squeezebert-uncased": {"do_lower_case": True},
"squeezebert/squeezebert-mnli": {"do_lower_case": True},
"squeezebert/squeezebert-mnli-headless": {"do_lower_case": True},
}
class UpperCamelCase__ ( __SCREAMING_SNAKE_CASE ):
"""simple docstring"""
UpperCAmelCase_ =VOCAB_FILES_NAMES
UpperCAmelCase_ =PRETRAINED_VOCAB_FILES_MAP
UpperCAmelCase_ =PRETRAINED_INIT_CONFIGURATION
UpperCAmelCase_ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCAmelCase_ =SqueezeBertTokenizer
def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ) -> int:
super().__init__(
_A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , )
SCREAMING_SNAKE_CASE_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get('''lowercase''' , _A ) != do_lower_case
or normalizer_state.get('''strip_accents''' , _A ) != strip_accents
or normalizer_state.get('''handle_chinese_chars''' , _A ) != tokenize_chinese_chars
):
SCREAMING_SNAKE_CASE_ = getattr(_A , normalizer_state.pop('''type''' ) )
SCREAMING_SNAKE_CASE_ = do_lower_case
SCREAMING_SNAKE_CASE_ = strip_accents
SCREAMING_SNAKE_CASE_ = tokenize_chinese_chars
SCREAMING_SNAKE_CASE_ = normalizer_class(**_A )
SCREAMING_SNAKE_CASE_ = do_lower_case
def _UpperCamelCase ( self , _A , _A=None ) -> Optional[Any]:
SCREAMING_SNAKE_CASE_ = [self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def _UpperCamelCase ( self , _A , _A = None ) -> List[int]:
SCREAMING_SNAKE_CASE_ = [self.sep_token_id]
SCREAMING_SNAKE_CASE_ = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def _UpperCamelCase ( self , _A , _A = None ) -> Tuple[str]:
SCREAMING_SNAKE_CASE_ = self._tokenizer.model.save(_A , name=_A )
return tuple(_A )
| 715 |
import re
import warnings
from contextlib import contextmanager
from ...processing_utils import ProcessorMixin
class UpperCamelCase__ ( __SCREAMING_SNAKE_CASE ):
"""simple docstring"""
UpperCAmelCase_ =["image_processor", "tokenizer"]
UpperCAmelCase_ ="AutoImageProcessor"
UpperCAmelCase_ ="AutoTokenizer"
def __init__( self , _A=None , _A=None , **_A ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE_ = None
if "feature_extractor" in kwargs:
warnings.warn(
'''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
''' instead.''' , _A , )
SCREAMING_SNAKE_CASE_ = kwargs.pop('''feature_extractor''' )
SCREAMING_SNAKE_CASE_ = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('''You need to specify an `image_processor`.''' )
if tokenizer is None:
raise ValueError('''You need to specify a `tokenizer`.''' )
super().__init__(_A , _A )
SCREAMING_SNAKE_CASE_ = self.image_processor
SCREAMING_SNAKE_CASE_ = False
def __call__( self , *_A , **_A ) -> Union[str, Any]:
# For backward compatibility
if self._in_target_context_manager:
return self.current_processor(*_A , **_A )
SCREAMING_SNAKE_CASE_ = kwargs.pop('''images''' , _A )
SCREAMING_SNAKE_CASE_ = kwargs.pop('''text''' , _A )
if len(_A ) > 0:
SCREAMING_SNAKE_CASE_ = args[0]
SCREAMING_SNAKE_CASE_ = args[1:]
if images is None and text is None:
raise ValueError('''You need to specify either an `images` or `text` input to process.''' )
if images is not None:
SCREAMING_SNAKE_CASE_ = self.image_processor(_A , *_A , **_A )
if text is not None:
SCREAMING_SNAKE_CASE_ = self.tokenizer(_A , **_A )
if text is None:
return inputs
elif images is None:
return encodings
else:
SCREAMING_SNAKE_CASE_ = encodings['''input_ids''']
return inputs
def _UpperCamelCase ( self , *_A , **_A ) -> Tuple:
return self.tokenizer.batch_decode(*_A , **_A )
def _UpperCamelCase ( self , *_A , **_A ) -> str:
return self.tokenizer.decode(*_A , **_A )
@contextmanager
def _UpperCamelCase ( self ) -> Tuple:
warnings.warn(
'''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '''
'''labels by using the argument `text` of the regular `__call__` method (either in the same call as '''
'''your images inputs, or in a separate call.''' )
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = self.tokenizer
yield
SCREAMING_SNAKE_CASE_ = self.image_processor
SCREAMING_SNAKE_CASE_ = False
def _UpperCamelCase ( self , _A , _A=False , _A=None ) -> Optional[Any]:
if added_vocab is None:
SCREAMING_SNAKE_CASE_ = self.tokenizer.get_added_vocab()
SCREAMING_SNAKE_CASE_ = {}
while tokens:
SCREAMING_SNAKE_CASE_ = re.search(R'''<s_(.*?)>''' , _A , re.IGNORECASE )
if start_token is None:
break
SCREAMING_SNAKE_CASE_ = start_token.group(1 )
SCREAMING_SNAKE_CASE_ = re.search(RF'''</s_{key}>''' , _A , re.IGNORECASE )
SCREAMING_SNAKE_CASE_ = start_token.group()
if end_token is None:
SCREAMING_SNAKE_CASE_ = tokens.replace(_A , '''''' )
else:
SCREAMING_SNAKE_CASE_ = end_token.group()
SCREAMING_SNAKE_CASE_ = re.escape(_A )
SCREAMING_SNAKE_CASE_ = re.escape(_A )
SCREAMING_SNAKE_CASE_ = re.search(F'''{start_token_escaped}(.*?){end_token_escaped}''' , _A , re.IGNORECASE )
if content is not None:
SCREAMING_SNAKE_CASE_ = content.group(1 ).strip()
if r"<s_" in content and r"</s_" in content: # non-leaf node
SCREAMING_SNAKE_CASE_ = self.tokenajson(_A , is_inner_value=_A , added_vocab=_A )
if value:
if len(_A ) == 1:
SCREAMING_SNAKE_CASE_ = value[0]
SCREAMING_SNAKE_CASE_ = value
else: # leaf nodes
SCREAMING_SNAKE_CASE_ = []
for leaf in content.split(R'''<sep/>''' ):
SCREAMING_SNAKE_CASE_ = leaf.strip()
if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
SCREAMING_SNAKE_CASE_ = leaf[1:-2] # for categorical special tokens
output[key].append(_A )
if len(output[key] ) == 1:
SCREAMING_SNAKE_CASE_ = output[key][0]
SCREAMING_SNAKE_CASE_ = tokens[tokens.find(_A ) + len(_A ) :].strip()
if tokens[:6] == r"<sep/>": # non-leaf nodes
return [output] + self.tokenajson(tokens[6:] , is_inner_value=_A , added_vocab=_A )
if len(_A ):
return [output] if is_inner_value else output
else:
return [] if is_inner_value else {"text_sequence": tokens}
@property
def _UpperCamelCase ( self ) -> Tuple:
warnings.warn(
'''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , _A , )
return self.image_processor_class
@property
def _UpperCamelCase ( self ) -> List[str]:
warnings.warn(
'''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , _A , )
return self.image_processor
| 597 | 0 |
from string import ascii_uppercase
SCREAMING_SNAKE_CASE : Optional[Any] = {str(ord(c) - 55): c for c in ascii_uppercase}
def lowerCAmelCase_ ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] ):
if isinstance(_A , _A ):
raise TypeError("""int() can't convert non-string with explicit base""" )
if num < 0:
raise ValueError("""parameter must be positive int""" )
if isinstance(_A , _A ):
raise TypeError("""'str' object cannot be interpreted as an integer""" )
if isinstance(_A , _A ):
raise TypeError("""'float' object cannot be interpreted as an integer""" )
if base in (0, 1):
raise ValueError("""base must be >= 2""" )
if base > 36:
raise ValueError("""base must be <= 36""" )
UpperCamelCase_ : Optional[int] = """"""
UpperCamelCase_ : List[str] = 0
UpperCamelCase_ : Tuple = 0
while div != 1:
UpperCamelCase_,UpperCamelCase_ : Dict = divmod(_A , _A )
if base >= 11 and 9 < mod < 36:
UpperCamelCase_ : List[Any] = ALPHABET_VALUES[str(_A )]
else:
UpperCamelCase_ : List[str] = str(_A )
new_value += actual_value
UpperCamelCase_ : Any = num // base
UpperCamelCase_ : int = div
if div == 0:
return str(new_value[::-1] )
elif div == 1:
new_value += str(_A )
return str(new_value[::-1] )
return new_value[::-1]
if __name__ == "__main__":
import doctest
doctest.testmod()
for base in range(2, 37):
for num in range(1000):
assert int(decimal_to_any(num, base), base) == num, (
num,
base,
decimal_to_any(num, base),
int(decimal_to_any(num, base), base),
)
| 635 | import argparse
import json
from collections import OrderedDict
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__)
def __A ( _A , _A , _A , _A ):
"""simple docstring"""
__a = original_name.split("." )[0]
__a = key.split("." )
__a = int(key_list[key_list.index(_A ) - 2] )
__a = int(key_list[key_list.index(_A ) - 1] )
__a = orig_block_num - offset
__a = key.replace(f"""{orig_block_num}.{layer_num}.{original_name}""" , f"""block.{new_block_num}.{layer_num}.{new_name}""" )
return key
def __A ( _A ):
"""simple docstring"""
__a = OrderedDict()
__a , __a = 0, 0
for key, value in state_dict.items():
if key.startswith("network" ):
__a = key.replace("network" , "poolformer.encoder" )
if "proj" in key:
# Works for the first embedding as well as the internal embedding layers
if key.endswith("bias" ) and "patch_embed" not in key:
patch_emb_offset += 1
__a = key[: key.find("proj" )]
__a = key.replace(_A , f"""patch_embeddings.{total_embed_found}.""" )
__a = key.replace("proj" , "projection" )
if key.endswith("bias" ):
total_embed_found += 1
if "patch_embeddings" in key:
__a = "poolformer.encoder." + key
if "mlp.fc1" in key:
__a = replace_key_with_offset(_A , _A , "mlp.fc1" , "output.conv1" )
if "mlp.fc2" in key:
__a = replace_key_with_offset(_A , _A , "mlp.fc2" , "output.conv2" )
if "norm1" in key:
__a = replace_key_with_offset(_A , _A , "norm1" , "before_norm" )
if "norm2" in key:
__a = replace_key_with_offset(_A , _A , "norm2" , "after_norm" )
if "layer_scale_1" in key:
__a = replace_key_with_offset(_A , _A , "layer_scale_1" , "layer_scale_1" )
if "layer_scale_2" in key:
__a = replace_key_with_offset(_A , _A , "layer_scale_2" , "layer_scale_2" )
if "head" in key:
__a = key.replace("head" , "classifier" )
__a = value
return new_state_dict
def __A ( ):
"""simple docstring"""
__a = "http://images.cocodataset.org/val2017/000000039769.jpg"
__a = Image.open(requests.get(_A , stream=_A ).raw )
return image
@torch.no_grad()
def __A ( _A , _A , _A ):
"""simple docstring"""
__a = PoolFormerConfig()
# set attributes based on model_name
__a = "huggingface/label-files"
__a = model_name[-3:]
__a = 1000
__a = "imagenet-1k-id2label.json"
__a = (1, 1000)
# set config attributes
__a = json.load(open(hf_hub_download(_A , _A , repo_type="dataset" ) , "r" ) )
__a = {int(_A ): v for k, v in idalabel.items()}
__a = idalabel
__a = {v: k for k, v in idalabel.items()}
if size == "s12":
__a = [2, 2, 6, 2]
__a = [64, 128, 320, 512]
__a = 4.0
__a = 0.9
elif size == "s24":
__a = [4, 4, 12, 4]
__a = [64, 128, 320, 512]
__a = 4.0
__a = 0.9
elif size == "s36":
__a = [6, 6, 18, 6]
__a = [64, 128, 320, 512]
__a = 4.0
__a = 1E-6
__a = 0.9
elif size == "m36":
__a = [6, 6, 18, 6]
__a = [96, 192, 384, 768]
__a = 4.0
__a = 1E-6
__a = 0.95
elif size == "m48":
__a = [8, 8, 24, 8]
__a = [96, 192, 384, 768]
__a = 4.0
__a = 1E-6
__a = 0.95
else:
raise ValueError(f"""Size {size} not supported""" )
# load image processor
__a = PoolFormerImageProcessor(crop_pct=_A )
# Prepare image
__a = prepare_img()
__a = image_processor(images=_A , return_tensors="pt" ).pixel_values
logger.info(f"""Converting model {model_name}...""" )
# load original state dict
__a = torch.load(_A , map_location=torch.device("cpu" ) )
# rename keys
__a = rename_keys(_A )
# create HuggingFace model and load state dict
__a = PoolFormerForImageClassification(_A )
model.load_state_dict(_A )
model.eval()
# Define image processor
__a = PoolFormerImageProcessor(crop_pct=_A )
__a = image_processor(images=prepare_img() , return_tensors="pt" ).pixel_values
# forward pass
__a = model(_A )
__a = outputs.logits
# define expected logit slices for different models
if size == "s12":
__a = torch.tensor([-0.3045, -0.6758, -0.4869] )
elif size == "s24":
__a = torch.tensor([0.4402, -0.1374, -0.8045] )
elif size == "s36":
__a = torch.tensor([-0.6080, -0.5133, -0.5898] )
elif size == "m36":
__a = torch.tensor([0.3952, 0.2263, -1.2668] )
elif size == "m48":
__a = torch.tensor([0.1167, -0.0656, -0.3423] )
else:
raise ValueError(f"""Size {size} not supported""" )
# verify logits
assert logits.shape == expected_shape
assert torch.allclose(logits[0, :3] , _A , atol=1E-2 )
# finally, save model and image processor
logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" )
Path(_A ).mkdir(exist_ok=_A )
model.save_pretrained(_A )
print(f"""Saving image processor to {pytorch_dump_folder_path}""" )
image_processor.save_pretrained(_A )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser()
parser.add_argument(
"""--model_name""",
default="""poolformer_s12""",
type=str,
help="""Name of the model you'd like to convert.""",
)
parser.add_argument(
"""--checkpoint_path""", default=None, type=str, help="""Path to the original PyTorch checkpoint (.pth file)."""
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model."""
)
SCREAMING_SNAKE_CASE : Any = parser.parse_args()
convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
| 197 | 0 |
from __future__ import annotations
import unittest
from transformers import is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import numpy as np
import tensorflow as tf
from transformers import (
TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
FlaubertConfig,
TFFlaubertForMultipleChoice,
TFFlaubertForQuestionAnsweringSimple,
TFFlaubertForSequenceClassification,
TFFlaubertForTokenClassification,
TFFlaubertModel,
TFFlaubertWithLMHeadModel,
)
class a_ :
def __init__( self :Union[str, Any] , _lowercase :int , ) -> Any:
UpperCAmelCase_ = parent
UpperCAmelCase_ = 13
UpperCAmelCase_ = 7
UpperCAmelCase_ = True
UpperCAmelCase_ = True
UpperCAmelCase_ = True
UpperCAmelCase_ = True
UpperCAmelCase_ = True
UpperCAmelCase_ = False
UpperCAmelCase_ = False
UpperCAmelCase_ = False
UpperCAmelCase_ = 2
UpperCAmelCase_ = 99
UpperCAmelCase_ = 0
UpperCAmelCase_ = 32
UpperCAmelCase_ = 2
UpperCAmelCase_ = 4
UpperCAmelCase_ = 0.1
UpperCAmelCase_ = 0.1
UpperCAmelCase_ = 512
UpperCAmelCase_ = 16
UpperCAmelCase_ = 2
UpperCAmelCase_ = 0.02
UpperCAmelCase_ = 3
UpperCAmelCase_ = 4
UpperCAmelCase_ = '''last'''
UpperCAmelCase_ = True
UpperCAmelCase_ = None
UpperCAmelCase_ = 0
def __a ( self :List[str]) -> Optional[int]:
UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
UpperCAmelCase_ = random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa)
UpperCAmelCase_ = None
if self.use_input_lengths:
UpperCAmelCase_ = (
ids_tensor([self.batch_size] , vocab_size=2) + self.seq_length - 2
) # small variation of seq_length
UpperCAmelCase_ = None
if self.use_token_type_ids:
UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.n_langs)
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] , 2 , dtype=tf.floataa)
UpperCAmelCase_ = ids_tensor([self.batch_size] , self.num_choices)
UpperCAmelCase_ = FlaubertConfig(
vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , bos_token_id=self.bos_token_id , )
return (
config,
input_ids,
token_type_ids,
input_lengths,
sequence_labels,
token_labels,
is_impossible_labels,
choice_labels,
input_mask,
)
def __a ( self :int , _lowercase :Union[str, Any] , _lowercase :List[Any] , _lowercase :Dict , _lowercase :Optional[Any] , _lowercase :int , _lowercase :List[str] , _lowercase :Any , _lowercase :Optional[int] , _lowercase :Any , ) -> Any:
UpperCAmelCase_ = TFFlaubertModel(config=_lowercase)
UpperCAmelCase_ = {'''input_ids''': input_ids, '''lengths''': input_lengths, '''langs''': token_type_ids}
UpperCAmelCase_ = model(_lowercase)
UpperCAmelCase_ = [input_ids, input_mask]
UpperCAmelCase_ = model(_lowercase)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def __a ( self :Dict , _lowercase :Optional[Any] , _lowercase :Union[str, Any] , _lowercase :Any , _lowercase :int , _lowercase :Tuple , _lowercase :int , _lowercase :Tuple , _lowercase :Optional[Any] , _lowercase :Optional[int] , ) -> Union[str, Any]:
UpperCAmelCase_ = TFFlaubertWithLMHeadModel(_lowercase)
UpperCAmelCase_ = {'''input_ids''': input_ids, '''lengths''': input_lengths, '''langs''': token_type_ids}
UpperCAmelCase_ = model(_lowercase)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size))
def __a ( self :Optional[Any] , _lowercase :List[str] , _lowercase :Optional[Any] , _lowercase :Optional[Any] , _lowercase :List[str] , _lowercase :str , _lowercase :Any , _lowercase :str , _lowercase :List[str] , _lowercase :Optional[int] , ) -> Optional[Any]:
UpperCAmelCase_ = TFFlaubertForQuestionAnsweringSimple(_lowercase)
UpperCAmelCase_ = {'''input_ids''': input_ids, '''lengths''': input_lengths}
UpperCAmelCase_ = model(_lowercase)
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length))
def __a ( self :List[str] , _lowercase :Dict , _lowercase :int , _lowercase :Any , _lowercase :List[str] , _lowercase :Any , _lowercase :List[Any] , _lowercase :Dict , _lowercase :Tuple , _lowercase :Optional[int] , ) -> Optional[int]:
UpperCAmelCase_ = TFFlaubertForSequenceClassification(_lowercase)
UpperCAmelCase_ = {'''input_ids''': input_ids, '''lengths''': input_lengths}
UpperCAmelCase_ = model(_lowercase)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size))
def __a ( self :Optional[Any] , _lowercase :Any , _lowercase :Union[str, Any] , _lowercase :List[str] , _lowercase :Any , _lowercase :List[str] , _lowercase :Union[str, Any] , _lowercase :List[Any] , _lowercase :Optional[int] , _lowercase :List[str] , ) -> str:
UpperCAmelCase_ = self.num_labels
UpperCAmelCase_ = TFFlaubertForTokenClassification(config=_lowercase)
UpperCAmelCase_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
UpperCAmelCase_ = model(_lowercase)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels))
def __a ( self :Any , _lowercase :Optional[int] , _lowercase :Optional[int] , _lowercase :List[Any] , _lowercase :Optional[Any] , _lowercase :Union[str, Any] , _lowercase :Tuple , _lowercase :Union[str, Any] , _lowercase :Any , _lowercase :Optional[Any] , ) -> List[Any]:
UpperCAmelCase_ = self.num_choices
UpperCAmelCase_ = TFFlaubertForMultipleChoice(config=_lowercase)
UpperCAmelCase_ = tf.tile(tf.expand_dims(_lowercase , 1) , (1, self.num_choices, 1))
UpperCAmelCase_ = tf.tile(tf.expand_dims(_lowercase , 1) , (1, self.num_choices, 1))
UpperCAmelCase_ = tf.tile(tf.expand_dims(_lowercase , 1) , (1, self.num_choices, 1))
UpperCAmelCase_ = {
'''input_ids''': multiple_choice_inputs_ids,
'''attention_mask''': multiple_choice_input_mask,
'''token_type_ids''': multiple_choice_token_type_ids,
}
UpperCAmelCase_ = model(_lowercase)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices))
def __a ( self :Optional[int]) -> Any:
UpperCAmelCase_ = self.prepare_config_and_inputs()
(
(
UpperCAmelCase_
) , (
UpperCAmelCase_
) , (
UpperCAmelCase_
) , (
UpperCAmelCase_
) , (
UpperCAmelCase_
) , (
UpperCAmelCase_
) , (
UpperCAmelCase_
) , (
UpperCAmelCase_
) , (
UpperCAmelCase_
) ,
) = config_and_inputs
UpperCAmelCase_ = {
'''input_ids''': input_ids,
'''token_type_ids''': token_type_ids,
'''langs''': token_type_ids,
'''lengths''': input_lengths,
}
return config, inputs_dict
@require_tf
class a_ ( _snake_case , _snake_case , unittest.TestCase ):
UpperCamelCase__ : List[Any] =(
(
TFFlaubertModel,
TFFlaubertWithLMHeadModel,
TFFlaubertForSequenceClassification,
TFFlaubertForQuestionAnsweringSimple,
TFFlaubertForTokenClassification,
TFFlaubertForMultipleChoice,
)
if is_tf_available()
else ()
)
UpperCamelCase__ : Tuple =(
(TFFlaubertWithLMHeadModel,) if is_tf_available() else ()
) # TODO (PVP): Check other models whether language generation is also applicable
UpperCamelCase__ : Optional[Any] =(
{
"feature-extraction": TFFlaubertModel,
"fill-mask": TFFlaubertWithLMHeadModel,
"question-answering": TFFlaubertForQuestionAnsweringSimple,
"text-classification": TFFlaubertForSequenceClassification,
"token-classification": TFFlaubertForTokenClassification,
"zero-shot": TFFlaubertForSequenceClassification,
}
if is_tf_available()
else {}
)
UpperCamelCase__ : Any =False
UpperCamelCase__ : List[str] =False
def __a ( self :List[Any] , _lowercase :Optional[Any] , _lowercase :Optional[Any] , _lowercase :Optional[Any] , _lowercase :Any , _lowercase :Optional[Any]) -> int:
if (
pipeline_test_casse_name == "QAPipelineTests"
and tokenizer_name is not None
and not tokenizer_name.endswith('''Fast''')
):
# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
return True
return False
def __a ( self :Union[str, Any]) -> Any:
UpperCAmelCase_ = TFFlaubertModelTester(self)
UpperCAmelCase_ = ConfigTester(self , config_class=_lowercase , emb_dim=37)
def __a ( self :int) -> Any:
self.config_tester.run_common_tests()
def __a ( self :List[str]) -> Union[str, Any]:
UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_model(*_lowercase)
def __a ( self :Any) -> int:
UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_lm_head(*_lowercase)
def __a ( self :List[Any]) -> Any:
UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_qa(*_lowercase)
def __a ( self :str) -> int:
UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_sequence_classif(*_lowercase)
def __a ( self :Dict) -> Union[str, Any]:
UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_for_token_classification(*_lowercase)
def __a ( self :Optional[int]) -> Tuple:
UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_for_multiple_choice(*_lowercase)
@slow
def __a ( self :List[Any]) -> Any:
for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCAmelCase_ = TFFlaubertModel.from_pretrained(_lowercase)
self.assertIsNotNone(_lowercase)
@require_tf
@require_sentencepiece
@require_tokenizers
class a_ ( unittest.TestCase ):
@slow
def __a ( self :str) -> Optional[Any]:
UpperCAmelCase_ = TFFlaubertModel.from_pretrained('''jplu/tf-flaubert-small-cased''')
UpperCAmelCase_ = tf.convert_to_tensor(
[[0, 158, 735, 2592, 1424, 6727, 82, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !"
UpperCAmelCase_ = model(_lowercase)[0]
UpperCAmelCase_ = tf.TensorShape((1, 8, 512))
self.assertEqual(output.shape , _lowercase)
# compare the actual values for a slice.
UpperCAmelCase_ = tf.convert_to_tensor(
[
[
[-1.8_768_773, -1.566_555, 0.27_072_418],
[-1.6_920_038, -0.5_873_505, 1.9_329_599],
[-2.9_563_985, -1.6_993_835, 1.7_972_052],
]
] , dtype=tf.floataa , )
self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
| 561 |
import unittest
from transformers import GPTSwaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
UpperCamelCase_ = get_tests_dir("fixtures/test_sentencepiece_with_bytefallback.model")
@require_sentencepiece
@require_tokenizers
class a_ ( _snake_case , unittest.TestCase ):
UpperCamelCase__ : Tuple =GPTSwaTokenizer
UpperCamelCase__ : Optional[int] =False
UpperCamelCase__ : Dict =True
UpperCamelCase__ : Union[str, Any] =False
def __a ( self :Optional[Any]) -> str:
super().setUp()
# We have a SentencePiece fixture for testing
UpperCAmelCase_ = GPTSwaTokenizer(_lowercase , eos_token='''<unk>''' , bos_token='''<unk>''' , pad_token='''<unk>''')
tokenizer.save_pretrained(self.tmpdirname)
def __a ( self :Optional[Any] , _lowercase :Optional[int]) -> Union[str, Any]:
UpperCAmelCase_ = '''This is a test'''
UpperCAmelCase_ = '''This is a test'''
return input_text, output_text
def __a ( self :Dict) -> Tuple:
UpperCAmelCase_ = '''<s>'''
UpperCAmelCase_ = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowercase) , _lowercase)
self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowercase) , _lowercase)
def __a ( self :int) -> Optional[int]:
UpperCAmelCase_ = list(self.get_tokenizer().get_vocab().keys())
self.assertEqual(vocab_keys[0] , '''<unk>''')
self.assertEqual(vocab_keys[1] , '''<s>''')
self.assertEqual(vocab_keys[-1] , '''j''')
self.assertEqual(len(_lowercase) , 2000)
def __a ( self :List[str]) -> Optional[Any]:
self.assertEqual(self.get_tokenizer().vocab_size , 2000)
def __a ( self :Tuple) -> Union[str, Any]:
UpperCAmelCase_ = GPTSwaTokenizer(_lowercase)
UpperCAmelCase_ = tokenizer.tokenize('''This is a test''')
self.assertListEqual(_lowercase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''])
self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowercase) , [465, 287, 265, 631, 842])
UpperCAmelCase_ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''')
# fmt: off
self.assertListEqual(
_lowercase , ['''▁I''', '''▁was''', '''▁bor''', '''n''', '''▁in''', '''▁''', '''<0x39>''', '''2''', '''0''', '''0''', '''0''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁f''', '''al''', '''s''', '''<0xC3>''', '''<0xA9>''', '''.'''] , )
# fmt: on
UpperCAmelCase_ = tokenizer.convert_tokens_to_ids(_lowercase)
self.assertListEqual(
_lowercase , [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , )
UpperCAmelCase_ = tokenizer.convert_ids_to_tokens(_lowercase)
# fmt: off
self.assertListEqual(
_lowercase , ['''▁I''', '''▁was''', '''▁bor''', '''n''', '''▁in''', '''▁''', '''<0x39>''', '''2''', '''0''', '''0''', '''0''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁f''', '''al''', '''s''', '''<0xC3>''', '''<0xA9>''', '''.'''])
# fmt: on
def __a ( self :Union[str, Any]) -> List[str]:
UpperCAmelCase_ = GPTSwaTokenizer(_lowercase)
UpperCAmelCase_ = ['''This is a test''', '''I was born in 92000, and this is falsé.''']
UpperCAmelCase_ = [
[465, 287, 265, 631, 842],
[262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260],
]
# Test that encode_fast returns the same as tokenize + convert_tokens_to_ids
for text, expected_ids in zip(_lowercase , _lowercase):
self.assertListEqual(tokenizer.encode_fast(_lowercase) , _lowercase)
# Test that decode_fast returns the input text
for text, token_ids in zip(_lowercase , _lowercase):
self.assertEqual(tokenizer.decode_fast(_lowercase) , _lowercase)
@slow
def __a ( self :int) -> List[str]:
UpperCAmelCase_ = [
'''<|python|>def fibonacci(n)\n if n < 0:\n print(\'Incorrect input\')''',
'''Hey there, how are you doing this fine day?''',
'''This is a text with a trailing spaces followed by a dot .''',
'''Häj sväjs lillebrör! =)''',
'''Det är inget fel på Mr. Cool''',
]
# fmt: off
UpperCAmelCase_ = {'''input_ids''': [[63423, 5, 6811, 14954, 282, 816, 3821, 63466, 63425, 63462, 18, 63978, 678, 301, 1320, 63423, 63455, 63458, 18, 63982, 4246, 3940, 1901, 47789, 5547, 18994], [19630, 1100, 63446, 1342, 633, 544, 4488, 593, 5102, 2416, 63495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1652, 428, 268, 1936, 515, 268, 58593, 22413, 9106, 546, 268, 33213, 63979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55130, 63450, 924, 63449, 2249, 4062, 1558, 318, 63504, 21498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2827, 2559, 332, 6575, 63443, 26801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=_lowercase , model_name='''AI-Sweden/gpt-sw3-126m''' , sequences=_lowercase , )
| 561 | 1 |
'''simple docstring'''
def lowerCamelCase__ ( __lowerCamelCase : Dict , __lowerCamelCase : Tuple , __lowerCamelCase : Dict ):
'''simple docstring'''
def update_area_of_max_square(__lowerCamelCase : str , __lowerCamelCase : Union[str, Any] ) -> int:
# BASE CASE
if row >= rows or col >= cols:
return 0
_UpperCAmelCase : Tuple =update_area_of_max_square(lowercase_ , col + 1 )
_UpperCAmelCase : Optional[Any] =update_area_of_max_square(row + 1 , col + 1 )
_UpperCAmelCase : Optional[Any] =update_area_of_max_square(row + 1 , lowercase_ )
if mat[row][col]:
_UpperCAmelCase : Tuple =1 + min([right, diagonal, down] )
_UpperCAmelCase : Dict =max(largest_square_area[0] , lowercase_ )
return sub_problem_sol
else:
return 0
_UpperCAmelCase : Tuple =[0]
update_area_of_max_square(0 , 0 )
return largest_square_area[0]
def lowerCamelCase__ ( __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : Optional[Any] ):
'''simple docstring'''
def update_area_of_max_square_using_dp_array(
__lowerCamelCase : str , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] ) -> int:
if row >= rows or col >= cols:
return 0
if dp_array[row][col] != -1:
return dp_array[row][col]
_UpperCAmelCase : Dict =update_area_of_max_square_using_dp_array(lowercase_ , col + 1 , lowercase_ )
_UpperCAmelCase : List[Any] =update_area_of_max_square_using_dp_array(row + 1 , col + 1 , lowercase_ )
_UpperCAmelCase : List[Any] =update_area_of_max_square_using_dp_array(row + 1 , lowercase_ , lowercase_ )
if mat[row][col]:
_UpperCAmelCase : Any =1 + min([right, diagonal, down] )
_UpperCAmelCase : Union[str, Any] =max(largest_square_area[0] , lowercase_ )
_UpperCAmelCase : List[str] =sub_problem_sol
return sub_problem_sol
else:
return 0
_UpperCAmelCase : Optional[Any] =[0]
_UpperCAmelCase : Union[str, Any] =[[-1] * cols for _ in range(lowercase_ )]
update_area_of_max_square_using_dp_array(0 , 0 , lowercase_ )
return largest_square_area[0]
def lowerCamelCase__ ( __lowerCamelCase : Tuple , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any] ):
'''simple docstring'''
_UpperCAmelCase : Optional[Any] =[[0] * (cols + 1) for _ in range(rows + 1 )]
_UpperCAmelCase : Dict =0
for row in range(rows - 1 , -1 , -1 ):
for col in range(cols - 1 , -1 , -1 ):
_UpperCAmelCase : int =dp_array[row][col + 1]
_UpperCAmelCase : List[str] =dp_array[row + 1][col + 1]
_UpperCAmelCase : Union[str, Any] =dp_array[row + 1][col]
if mat[row][col] == 1:
_UpperCAmelCase : List[Any] =1 + min(lowercase_ , lowercase_ , lowercase_ )
_UpperCAmelCase : Union[str, Any] =max(dp_array[row][col] , lowercase_ )
else:
_UpperCAmelCase : Tuple =0
return largest_square_area
def lowerCamelCase__ ( __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : List[str] ):
'''simple docstring'''
_UpperCAmelCase : int =[0] * (cols + 1)
_UpperCAmelCase : Optional[int] =[0] * (cols + 1)
_UpperCAmelCase : List[str] =0
for row in range(rows - 1 , -1 , -1 ):
for col in range(cols - 1 , -1 , -1 ):
_UpperCAmelCase : Optional[Any] =current_row[col + 1]
_UpperCAmelCase : Union[str, Any] =next_row[col + 1]
_UpperCAmelCase : List[str] =next_row[col]
if mat[row][col] == 1:
_UpperCAmelCase : Optional[Any] =1 + min(lowercase_ , lowercase_ , lowercase_ )
_UpperCAmelCase : Tuple =max(current_row[col] , lowercase_ )
else:
_UpperCAmelCase : Union[str, Any] =0
_UpperCAmelCase : Union[str, Any] =current_row
return largest_square_area
if __name__ == "__main__":
import doctest
doctest.testmod()
print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
| 446 |
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 os
import jsonlines
import numpy as np
from tqdm import tqdm
lowerCAmelCase : Optional[Any] = 2048
lowerCAmelCase : Union[str, Any] = 4096
lowerCAmelCase : str = 42
lowerCAmelCase : str = os.environ.pop("""PROCESS_TRAIN""", """false""")
lowerCAmelCase : Optional[Any] = {"""null""": 0, """short""": 1, """long""": 2, """yes""": 3, """no""": 4}
def lowerCAmelCase ( UpperCamelCase__ : List[str] ) -> List[str]:
"""simple docstring"""
def choose_first(UpperCamelCase__ : str , UpperCamelCase__ : Dict=False ):
assert isinstance(UpperCamelCase__ , UpperCamelCase__ )
if len(UpperCamelCase__ ) == 1:
__SCREAMING_SNAKE_CASE: List[str] = answer[0]
return {k: [answer[k]] for k in answer} if is_long_answer else answer
for a in answer:
if is_long_answer:
__SCREAMING_SNAKE_CASE: Union[str, Any] = {k: [a[k]] for k in a}
if len(a['''start_token'''] ) > 0:
break
return a
__SCREAMING_SNAKE_CASE: str = {'''id''': example['''id''']}
__SCREAMING_SNAKE_CASE: List[str] = example['''annotations''']
__SCREAMING_SNAKE_CASE: Tuple = annotation['''yes_no_answer''']
if 0 in yes_no_answer or 1 in yes_no_answer:
__SCREAMING_SNAKE_CASE: Any = ['''yes'''] if 1 in yes_no_answer else ['''no''']
__SCREAMING_SNAKE_CASE: int = []
__SCREAMING_SNAKE_CASE: Any = []
__SCREAMING_SNAKE_CASE: int = ['''<cls>''']
else:
__SCREAMING_SNAKE_CASE: List[Any] = ['''short''']
__SCREAMING_SNAKE_CASE: Optional[Any] = choose_first(annotation['''short_answers'''] )
if len(out['''start_token'''] ) == 0:
# answer will be long if short is not available
__SCREAMING_SNAKE_CASE: Tuple = ['''long''']
__SCREAMING_SNAKE_CASE: List[Any] = choose_first(annotation['''long_answer'''] , is_long_answer=UpperCamelCase__ )
__SCREAMING_SNAKE_CASE: Union[str, Any] = []
answer.update(UpperCamelCase__ )
# disregard some samples
if len(answer['''start_token'''] ) > 1 or answer["start_token"] == answer["end_token"]:
__SCREAMING_SNAKE_CASE: Dict = True
else:
__SCREAMING_SNAKE_CASE: List[str] = False
__SCREAMING_SNAKE_CASE: List[str] = ['''start_token''', '''end_token''', '''start_byte''', '''end_byte''', '''text''']
if not all(isinstance(answer[k] , UpperCamelCase__ ) for k in cols ):
raise ValueError('''Issue in ID''' , example['''id'''] )
return answer
def lowerCAmelCase ( UpperCamelCase__ : Tuple , UpperCamelCase__ : List[str]=False ) -> Tuple:
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Optional[Any] = _get_single_answer(UpperCamelCase__ )
# bytes are of no use
del answer["start_byte"]
del answer["end_byte"]
# handle yes_no answers explicitly
if answer["category"][0] in ["yes", "no"]: # category is list with one element
__SCREAMING_SNAKE_CASE: Optional[Any] = example['''document''']['''tokens''']
__SCREAMING_SNAKE_CASE: Optional[Any] = []
for i in range(len(doc['''token'''] ) ):
if not doc["is_html"][i]:
context.append(doc['''token'''][i] )
return {
"context": " ".join(UpperCamelCase__ ),
"answer": {
"start_token": -100, # ignore index in cross-entropy
"end_token": -100, # ignore index in cross-entropy
"category": answer["category"],
"span": answer["category"], # extra
},
}
# later, help in removing all no answers
if answer["start_token"] == [-1]:
return {
"context": "None",
"answer": {
"start_token": -1,
"end_token": -1,
"category": "null",
"span": "None", # extra
},
}
# handling normal samples
__SCREAMING_SNAKE_CASE: Optional[Any] = ['''start_token''', '''end_token''']
answer.update({k: answer[k][0] if len(answer[k] ) > 0 else answer[k] for k in cols} ) # e.g. [10] == 10
__SCREAMING_SNAKE_CASE: List[Any] = example['''document''']['''tokens''']
__SCREAMING_SNAKE_CASE: Optional[Any] = answer['''start_token''']
__SCREAMING_SNAKE_CASE: Tuple = answer['''end_token''']
__SCREAMING_SNAKE_CASE: List[str] = []
for i in range(len(doc['''token'''] ) ):
if not doc["is_html"][i]:
context.append(doc['''token'''][i] )
else:
if answer["start_token"] > i:
start_token -= 1
if answer["end_token"] > i:
end_token -= 1
__SCREAMING_SNAKE_CASE: List[Any] = ''' '''.join(context[start_token:end_token] )
# checking above code
if assertion:
__SCREAMING_SNAKE_CASE: Optional[int] = doc['''is_html'''][answer['''start_token'''] : answer['''end_token''']]
__SCREAMING_SNAKE_CASE: Union[str, Any] = doc['''token'''][answer['''start_token'''] : answer['''end_token''']]
__SCREAMING_SNAKE_CASE: List[str] = ''' '''.join([old[i] for i in range(len(UpperCamelCase__ ) ) if not is_html[i]] )
if new != old:
print('''ID:''' , example['''id'''] )
print('''New:''' , UpperCamelCase__ , end='''\n''' )
print('''Old:''' , UpperCamelCase__ , end='''\n\n''' )
return {
"context": " ".join(UpperCamelCase__ ),
"answer": {
"start_token": start_token,
"end_token": end_token - 1, # this makes it inclusive
"category": answer["category"], # either long or short
"span": new, # extra
},
}
def lowerCAmelCase ( UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str]=2_048 , UpperCamelCase__ : List[Any]=4_096 , UpperCamelCase__ : Any=True ) -> int:
"""simple docstring"""
__SCREAMING_SNAKE_CASE: str = get_context_and_ans(UpperCamelCase__ , assertion=UpperCamelCase__ )
__SCREAMING_SNAKE_CASE: Optional[int] = out['''answer''']
# later, removing these samples
if answer["start_token"] == -1:
return {
"example_id": example["id"],
"input_ids": [[-1]],
"labels": {
"start_token": [-1],
"end_token": [-1],
"category": ["null"],
},
}
__SCREAMING_SNAKE_CASE: Optional[int] = tokenizer(example['''question''']['''text'''] , out['''context'''] ).input_ids
__SCREAMING_SNAKE_CASE: Optional[int] = input_ids.index(tokenizer.sep_token_id ) + 1
# return yes/no
if answer["category"][0] in ["yes", "no"]: # category is list with one element
__SCREAMING_SNAKE_CASE: Dict = []
__SCREAMING_SNAKE_CASE: Optional[Any] = []
__SCREAMING_SNAKE_CASE: Tuple = input_ids[:q_len]
__SCREAMING_SNAKE_CASE: Union[str, Any] = range(UpperCamelCase__ , len(UpperCamelCase__ ) , max_length - doc_stride )
for i in doc_start_indices:
__SCREAMING_SNAKE_CASE: List[Any] = i + max_length - q_len
__SCREAMING_SNAKE_CASE: List[Any] = input_ids[i:end_index]
inputs.append(q_indices + slice )
category.append(answer['''category'''][0] )
if slice[-1] == tokenizer.sep_token_id:
break
return {
"example_id": example["id"],
"input_ids": inputs,
"labels": {
"start_token": [-100] * len(UpperCamelCase__ ),
"end_token": [-100] * len(UpperCamelCase__ ),
"category": category,
},
}
__SCREAMING_SNAKE_CASE: int = out['''context'''].split()
__SCREAMING_SNAKE_CASE: List[str] = splitted_context[answer['''end_token''']]
__SCREAMING_SNAKE_CASE: Dict = len(
tokenizer(
''' '''.join(splitted_context[: answer['''start_token''']] ) , add_special_tokens=UpperCamelCase__ , ).input_ids )
__SCREAMING_SNAKE_CASE: Dict = len(
tokenizer(''' '''.join(splitted_context[: answer['''end_token''']] ) , add_special_tokens=UpperCamelCase__ ).input_ids )
answer["start_token"] += q_len
answer["end_token"] += q_len
# fixing end token
__SCREAMING_SNAKE_CASE: Dict = len(tokenizer(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ).input_ids )
if num_sub_tokens > 1:
answer["end_token"] += num_sub_tokens - 1
__SCREAMING_SNAKE_CASE: Tuple = input_ids[answer['''start_token'''] : answer['''end_token'''] + 1] # right & left are inclusive
__SCREAMING_SNAKE_CASE: Optional[Any] = answer['''start_token''']
__SCREAMING_SNAKE_CASE: str = answer['''end_token''']
if assertion:
__SCREAMING_SNAKE_CASE: Union[str, Any] = tokenizer.decode(UpperCamelCase__ )
if answer["span"] != new:
print('''ISSUE IN TOKENIZATION''' )
print('''OLD:''' , answer['''span'''] )
print('''NEW:''' , UpperCamelCase__ , end='''\n\n''' )
if len(UpperCamelCase__ ) <= max_length:
return {
"example_id": example["id"],
"input_ids": [input_ids],
"labels": {
"start_token": [answer["start_token"]],
"end_token": [answer["end_token"]],
"category": answer["category"],
},
}
__SCREAMING_SNAKE_CASE: Any = input_ids[:q_len]
__SCREAMING_SNAKE_CASE: Any = range(UpperCamelCase__ , len(UpperCamelCase__ ) , max_length - doc_stride )
__SCREAMING_SNAKE_CASE: Union[str, Any] = []
__SCREAMING_SNAKE_CASE: Tuple = []
__SCREAMING_SNAKE_CASE: int = []
__SCREAMING_SNAKE_CASE: Tuple = [] # null, yes, no, long, short
for i in doc_start_indices:
__SCREAMING_SNAKE_CASE: Tuple = i + max_length - q_len
__SCREAMING_SNAKE_CASE: Union[str, Any] = input_ids[i:end_index]
inputs.append(q_indices + slice )
assert len(inputs[-1] ) <= max_length, "Issue in truncating length"
if start_token >= i and end_token <= end_index - 1:
__SCREAMING_SNAKE_CASE: List[Any] = start_token - i + q_len
__SCREAMING_SNAKE_CASE: int = end_token - i + q_len
answers_category.append(answer['''category'''][0] ) # ["short"] -> "short"
else:
__SCREAMING_SNAKE_CASE: Tuple = -100
__SCREAMING_SNAKE_CASE: Tuple = -100
answers_category.append('''null''' )
__SCREAMING_SNAKE_CASE: Optional[int] = inputs[-1][start_token : end_token + 1]
answers_start_token.append(UpperCamelCase__ )
answers_end_token.append(UpperCamelCase__ )
if assertion:
if new != old and new != [tokenizer.cls_token_id]:
print('''ISSUE in strided for ID:''' , example['''id'''] )
print('''New:''' , tokenizer.decode(UpperCamelCase__ ) )
print('''Old:''' , tokenizer.decode(UpperCamelCase__ ) , end='''\n\n''' )
if slice[-1] == tokenizer.sep_token_id:
break
return {
"example_id": example["id"],
"input_ids": inputs,
"labels": {
"start_token": answers_start_token,
"end_token": answers_end_token,
"category": answers_category,
},
}
def lowerCAmelCase ( UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Tuple=2_048 , UpperCamelCase__ : Optional[int]=4_096 , UpperCamelCase__ : List[str]=False ) -> List[str]:
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Dict = get_strided_contexts_and_ans(
UpperCamelCase__ , UpperCamelCase__ , doc_stride=UpperCamelCase__ , max_length=UpperCamelCase__ , assertion=UpperCamelCase__ , )
return example
def lowerCAmelCase ( UpperCamelCase__ : Tuple , UpperCamelCase__ : int ) -> str:
"""simple docstring"""
with jsonlines.open(UpperCamelCase__ , '''a''' ) as writer:
for example in tqdm(UpperCamelCase__ , total=len(UpperCamelCase__ ) , desc='''Saving samples ... ''' ):
__SCREAMING_SNAKE_CASE: Optional[Any] = example['''labels''']
for ids, start, end, cat in zip(
example['''input_ids'''] , labels['''start_token'''] , labels['''end_token'''] , labels['''category'''] , ):
if start == -1 and end == -1:
continue # leave waste samples with no answer
if cat == "null" and np.random.rand() < 0.6:
continue # removing 50 % samples
writer.write(
{
'''input_ids''': ids,
'''start_token''': start,
'''end_token''': end,
'''category''': CATEGORY_MAPPING[cat],
} )
if __name__ == "__main__":
from datasets import load_dataset
from transformers import BigBirdTokenizer
lowerCAmelCase : Tuple = load_dataset("""natural_questions""")
lowerCAmelCase : int = BigBirdTokenizer.from_pretrained("""google/bigbird-roberta-base""")
lowerCAmelCase : Optional[int] = data["""train""" if PROCESS_TRAIN == """true""" else """validation"""]
lowerCAmelCase : Optional[int] = {
"""tokenizer""": tokenizer,
"""doc_stride""": DOC_STRIDE,
"""max_length""": MAX_LENGTH,
"""assertion""": False,
}
lowerCAmelCase : Optional[Any] = data.map(prepare_inputs, fn_kwargs=fn_kwargs)
lowerCAmelCase : Tuple = data.remove_columns(["""annotations""", """document""", """id""", """question"""])
print(data)
np.random.seed(SEED)
lowerCAmelCase : Dict = """nq-training.jsonl""" if PROCESS_TRAIN == """true""" else """nq-validation.jsonl"""
save_to_disk(data, file_name=cache_file_name)
| 146 |
import subprocess
import sys
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch
class a ( __lowercase ):
@require_torch
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: List[str] = '''
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
'''
__SCREAMING_SNAKE_CASE: Dict = '''
mname = "hf-internal-testing/tiny-random-bert"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
BertTokenizer.from_pretrained(mname)
pipe = pipeline(task="fill-mask", model=mname)
print("success")
'''
__SCREAMING_SNAKE_CASE: Tuple = '''
import socket
def offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")
socket.socket = offline_socket
'''
# Force fetching the files so that we can use the cache
__SCREAMING_SNAKE_CASE: Optional[int] = '''hf-internal-testing/tiny-random-bert'''
BertConfig.from_pretrained(_lowerCAmelCase )
BertModel.from_pretrained(_lowerCAmelCase )
BertTokenizer.from_pretrained(_lowerCAmelCase )
pipeline(task='''fill-mask''' , model=_lowerCAmelCase )
# baseline - just load from_pretrained with normal network
__SCREAMING_SNAKE_CASE: str = [sys.executable, '''-c''', '''\n'''.join([load, run, mock] )]
# should succeed
__SCREAMING_SNAKE_CASE: List[str] = self.get_env()
# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
__SCREAMING_SNAKE_CASE: Union[str, Any] = '''1'''
__SCREAMING_SNAKE_CASE: Union[str, Any] = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 0 , result.stderr )
self.assertIn('''success''' , result.stdout.decode() )
@require_torch
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: int = '''
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
'''
__SCREAMING_SNAKE_CASE: Tuple = '''
mname = "hf-internal-testing/tiny-random-bert"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
BertTokenizer.from_pretrained(mname)
pipe = pipeline(task="fill-mask", model=mname)
print("success")
'''
__SCREAMING_SNAKE_CASE: List[Any] = '''
import socket
def offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")
socket.socket = offline_socket
'''
# Force fetching the files so that we can use the cache
__SCREAMING_SNAKE_CASE: Tuple = '''hf-internal-testing/tiny-random-bert'''
BertConfig.from_pretrained(_lowerCAmelCase )
BertModel.from_pretrained(_lowerCAmelCase )
BertTokenizer.from_pretrained(_lowerCAmelCase )
pipeline(task='''fill-mask''' , model=_lowerCAmelCase )
# baseline - just load from_pretrained with normal network
__SCREAMING_SNAKE_CASE: Optional[int] = [sys.executable, '''-c''', '''\n'''.join([load, run, mock] )]
# should succeed
__SCREAMING_SNAKE_CASE: Union[str, Any] = self.get_env()
__SCREAMING_SNAKE_CASE: Dict = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 0 , result.stderr )
self.assertIn('''success''' , result.stdout.decode() )
@require_torch
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: List[str] = '''
from transformers import BertConfig, BertModel, BertTokenizer
'''
__SCREAMING_SNAKE_CASE: str = '''
mname = "hf-internal-testing/tiny-random-bert-sharded"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
print("success")
'''
__SCREAMING_SNAKE_CASE: Optional[int] = '''
import socket
def offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")
socket.socket = offline_socket
'''
# baseline - just load from_pretrained with normal network
__SCREAMING_SNAKE_CASE: str = [sys.executable, '''-c''', '''\n'''.join([load, run] )]
# should succeed
__SCREAMING_SNAKE_CASE: List[str] = self.get_env()
__SCREAMING_SNAKE_CASE: List[Any] = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 0 , result.stderr )
self.assertIn('''success''' , result.stdout.decode() )
# next emulate no network
__SCREAMING_SNAKE_CASE: List[Any] = [sys.executable, '''-c''', '''\n'''.join([load, mock, run] )]
# Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
# env["TRANSFORMERS_OFFLINE"] = "0"
# result = subprocess.run(cmd, env=env, check=False, capture_output=True)
# self.assertEqual(result.returncode, 1, result.stderr)
# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
__SCREAMING_SNAKE_CASE: Any = '''1'''
__SCREAMING_SNAKE_CASE: Optional[int] = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 0 , result.stderr )
self.assertIn('''success''' , result.stdout.decode() )
@require_torch
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: List[Any] = '''
from transformers import pipeline
'''
__SCREAMING_SNAKE_CASE: Dict = '''
mname = "hf-internal-testing/tiny-random-bert"
pipe = pipeline(model=mname)
'''
__SCREAMING_SNAKE_CASE: List[str] = '''
import socket
def offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")
socket.socket = offline_socket
'''
__SCREAMING_SNAKE_CASE: List[str] = self.get_env()
__SCREAMING_SNAKE_CASE: int = '''1'''
__SCREAMING_SNAKE_CASE: List[str] = [sys.executable, '''-c''', '''\n'''.join([load, mock, run] )]
__SCREAMING_SNAKE_CASE: List[Any] = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 1 , result.stderr )
self.assertIn(
'''You cannot infer task automatically within `pipeline` when using offline mode''' , result.stderr.decode().replace('''\n''' , '''''' ) , )
@require_torch
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Optional[Any] = '''
from transformers import AutoModel
'''
__SCREAMING_SNAKE_CASE: Tuple = '''
mname = "hf-internal-testing/test_dynamic_model"
AutoModel.from_pretrained(mname, trust_remote_code=True)
print("success")
'''
# baseline - just load from_pretrained with normal network
__SCREAMING_SNAKE_CASE: Dict = [sys.executable, '''-c''', '''\n'''.join([load, run] )]
# should succeed
__SCREAMING_SNAKE_CASE: List[str] = self.get_env()
__SCREAMING_SNAKE_CASE: str = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 0 , result.stderr )
self.assertIn('''success''' , result.stdout.decode() )
# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
__SCREAMING_SNAKE_CASE: List[str] = '''1'''
__SCREAMING_SNAKE_CASE: Tuple = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 0 , result.stderr )
self.assertIn('''success''' , result.stdout.decode() )
| 146 | 1 |
from typing import List
import numpy as np
def __snake_case ( lowerCAmelCase_ ) -> int:
SCREAMING_SNAKE_CASE__ = {key: len(lowerCAmelCase_ ) for key, value in gen_kwargs.items() if isinstance(lowerCAmelCase_ , lowerCAmelCase_ )}
if len(set(lists_lengths.values() ) ) > 1:
raise RuntimeError(
(
'''Sharding is ambiguous for this dataset: '''
+ '''we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n'''
+ '''\n'''.join(f'''\t- key {key} has length {length}''' for key, length in lists_lengths.items() )
+ '''\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, '''
+ '''and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.'''
) )
SCREAMING_SNAKE_CASE__ = max(lists_lengths.values() , default=0 )
return max(1 , lowerCAmelCase_ )
def __snake_case ( lowerCAmelCase_ , lowerCAmelCase_ ) -> List[range]:
SCREAMING_SNAKE_CASE__ = []
for group_idx in range(lowerCAmelCase_ ):
SCREAMING_SNAKE_CASE__ = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs))
if num_shards_to_add == 0:
break
SCREAMING_SNAKE_CASE__ = shards_indices_per_group[-1].stop if shards_indices_per_group else 0
SCREAMING_SNAKE_CASE__ = range(lowerCAmelCase_ , start + num_shards_to_add )
shards_indices_per_group.append(lowerCAmelCase_ )
return shards_indices_per_group
def __snake_case ( lowerCAmelCase_ , lowerCAmelCase_ ) -> List[dict]:
SCREAMING_SNAKE_CASE__ = _number_of_shards_in_gen_kwargs(lowerCAmelCase_ )
if num_shards == 1:
return [dict(lowerCAmelCase_ )]
else:
SCREAMING_SNAKE_CASE__ = _distribute_shards(num_shards=lowerCAmelCase_ , max_num_jobs=lowerCAmelCase_ )
return [
{
key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]]
if isinstance(lowerCAmelCase_ , lowerCAmelCase_ )
else value
for key, value in gen_kwargs.items()
}
for group_idx in range(len(lowerCAmelCase_ ) )
]
def __snake_case ( lowerCAmelCase_ ) -> dict:
return {
key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]]
if isinstance(gen_kwargs_list[0][key] , lowerCAmelCase_ )
else gen_kwargs_list[0][key]
for key in gen_kwargs_list[0]
}
def __snake_case ( lowerCAmelCase_ , lowerCAmelCase_ ) -> dict:
SCREAMING_SNAKE_CASE__ = {len(lowerCAmelCase_ ) for value in gen_kwargs.values() if isinstance(lowerCAmelCase_ , lowerCAmelCase_ )}
SCREAMING_SNAKE_CASE__ = {}
for size in list_sizes:
SCREAMING_SNAKE_CASE__ = list(range(lowerCAmelCase_ ) )
rng.shuffle(indices_per_size[size] )
# Now let's copy the gen_kwargs and shuffle the lists based on their sizes
SCREAMING_SNAKE_CASE__ = dict(lowerCAmelCase_ )
for key, value in shuffled_kwargs.items():
if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ):
SCREAMING_SNAKE_CASE__ = [value[i] for i in indices_per_size[len(lowerCAmelCase_ )]]
return shuffled_kwargs
| 100 | from __future__ import annotations
import csv
import requests
from bsa import BeautifulSoup
def lowerCAmelCase_ ( lowercase: str = "" ) -> dict[str, float]:
'''simple docstring'''
_UpperCamelCase: Tuple = url or '''https://www.imdb.com/chart/top/?ref_=nv_mv_250'''
_UpperCamelCase: Union[str, Any] = BeautifulSoup(requests.get(lowercase ).text , '''html.parser''' )
_UpperCamelCase: List[Any] = soup.find_all('''td''' , attrs='''titleColumn''' )
_UpperCamelCase: str = soup.find_all('''td''' , class_='''ratingColumn imdbRating''' )
return {
title.a.text: float(rating.strong.text )
for title, rating in zip(lowercase , lowercase )
}
def lowerCAmelCase_ ( lowercase: str = "IMDb_Top_250_Movies.csv" ) -> None:
'''simple docstring'''
_UpperCamelCase: Any = get_imdb_top_aaa_movies()
with open(lowercase , '''w''' , newline='''''' ) as out_file:
_UpperCamelCase: Optional[Any] = csv.writer(lowercase )
writer.writerow(['''Movie title''', '''IMDb rating'''] )
for title, rating in movies.items():
writer.writerow([title, rating] )
if __name__ == "__main__":
write_movies() | 271 | 0 |
import torch
from diffusers import UnCLIPScheduler
from .test_schedulers import SchedulerCommonTest
class a__ ( __snake_case ):
A__ : Dict = (UnCLIPScheduler,)
def __SCREAMING_SNAKE_CASE ( self , **UpperCAmelCase ) -> Union[str, Any]:
__a = {
'num_train_timesteps': 1_0_0_0,
'variance_type': 'fixed_small_log',
'clip_sample': True,
'clip_sample_range': 1.0,
'prediction_type': 'epsilon',
}
config.update(**UpperCAmelCase )
return config
def __SCREAMING_SNAKE_CASE ( self ) -> str:
for timesteps in [1, 5, 1_0_0, 1_0_0_0]:
self.check_over_configs(num_train_timesteps=UpperCAmelCase )
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
for variance in ["fixed_small_log", "learned_range"]:
self.check_over_configs(variance_type=UpperCAmelCase )
def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
for clip_sample in [True, False]:
self.check_over_configs(clip_sample=UpperCAmelCase )
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
for clip_sample_range in [1, 5, 1_0, 2_0]:
self.check_over_configs(clip_sample_range=UpperCAmelCase )
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(prediction_type=UpperCAmelCase )
def __SCREAMING_SNAKE_CASE ( self ) -> Any:
for time_step in [0, 5_0_0, 9_9_9]:
for prev_timestep in [None, 5, 1_0_0, 2_5_0, 5_0_0, 7_5_0]:
if prev_timestep is not None and prev_timestep >= time_step:
continue
self.check_over_forward(time_step=UpperCAmelCase , prev_timestep=UpperCAmelCase )
def __SCREAMING_SNAKE_CASE ( self ) -> int:
__a = self.scheduler_classes[0]
__a = self.get_scheduler_config(variance_type='fixed_small_log' )
__a = scheduler_class(**UpperCAmelCase )
assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0000e-10 ) ) < 1e-5
assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 ) - 0.0_549_625 ) ) < 1e-5
assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 ) - 0.9_994_987 ) ) < 1e-5
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
__a = self.scheduler_classes[0]
__a = self.get_scheduler_config(variance_type='learned_range' )
__a = scheduler_class(**UpperCAmelCase )
__a = 0.5
assert scheduler._get_variance(1 , predicted_variance=UpperCAmelCase ) - -10.1_712_790 < 1e-5
assert scheduler._get_variance(4_8_7 , predicted_variance=UpperCAmelCase ) - -5.7_998_052 < 1e-5
assert scheduler._get_variance(9_9_9 , predicted_variance=UpperCAmelCase ) - -0.0_010_011 < 1e-5
def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
__a = self.scheduler_classes[0]
__a = self.get_scheduler_config()
__a = scheduler_class(**UpperCAmelCase )
__a = scheduler.timesteps
__a = self.dummy_model()
__a = self.dummy_sample_deter
__a = torch.manual_seed(0 )
for i, t in enumerate(UpperCAmelCase ):
# 1. predict noise residual
__a = model(UpperCAmelCase , UpperCAmelCase )
# 2. predict previous mean of sample x_t-1
__a = scheduler.step(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , generator=UpperCAmelCase ).prev_sample
__a = pred_prev_sample
__a = torch.sum(torch.abs(UpperCAmelCase ) )
__a = torch.mean(torch.abs(UpperCAmelCase ) )
assert abs(result_sum.item() - 252.2_682_495 ) < 1e-2
assert abs(result_mean.item() - 0.3_284_743 ) < 1e-3
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
__a = self.scheduler_classes[0]
__a = self.get_scheduler_config()
__a = scheduler_class(**UpperCAmelCase )
scheduler.set_timesteps(2_5 )
__a = scheduler.timesteps
__a = self.dummy_model()
__a = self.dummy_sample_deter
__a = torch.manual_seed(0 )
for i, t in enumerate(UpperCAmelCase ):
# 1. predict noise residual
__a = model(UpperCAmelCase , UpperCAmelCase )
if i + 1 == timesteps.shape[0]:
__a = None
else:
__a = timesteps[i + 1]
# 2. predict previous mean of sample x_t-1
__a = scheduler.step(
UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , prev_timestep=UpperCAmelCase , generator=UpperCAmelCase ).prev_sample
__a = pred_prev_sample
__a = torch.sum(torch.abs(UpperCAmelCase ) )
__a = torch.mean(torch.abs(UpperCAmelCase ) )
assert abs(result_sum.item() - 258.2_044_983 ) < 1e-2
assert abs(result_mean.item() - 0.3_362_038 ) < 1e-3
def __SCREAMING_SNAKE_CASE ( self ) -> Tuple:
pass
def __SCREAMING_SNAKE_CASE ( self ) -> int:
pass
| 246 | from math import factorial
def lowerCAmelCase( __lowerCamelCase = 100 ):
return sum(int(__lowerCamelCase ) for x in str(factorial(__lowerCamelCase ) ) )
if __name__ == "__main__":
print(solution(int(input("""Enter the Number: """).strip())))
| 246 | 1 |
'''simple docstring'''
import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple
from transformers import AddedToken, BatchEncoding, PerceiverTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available
from ...test_tokenization_common import TokenizerTesterMixin
if is_torch_available():
lowerCAmelCase_ : Any = """pt"""
elif is_tf_available():
lowerCAmelCase_ : Optional[Any] = """tf"""
else:
lowerCAmelCase_ : int = """jax"""
class __SCREAMING_SNAKE_CASE (__SCREAMING_SNAKE_CASE , unittest.TestCase ):
"""simple docstring"""
__a =PerceiverTokenizer
__a =False
def UpperCamelCase__ ( self : Any ):
super().setUp()
_a = PerceiverTokenizer()
tokenizer.save_pretrained(self.tmpdirname )
@cached_property
def UpperCamelCase__ ( self : Union[str, Any] ):
return PerceiverTokenizer.from_pretrained("deepmind/language-perceiver" )
def UpperCamelCase__ ( self : Optional[Any] , **__a : Optional[int] ):
return self.tokenizer_class.from_pretrained(self.tmpdirname , **_A )
def UpperCamelCase__ ( self : Optional[int] , __a : str , __a : Dict=False , __a : Union[str, Any]=20 , __a : int=5 ):
_a = []
for i in range(len(_A ) ):
try:
_a = tokenizer.decode([i] , clean_up_tokenization_spaces=_A )
except UnicodeDecodeError:
pass
toks.append((i, tok) )
_a = list(filter(lambda __a : re.match(r"^[ a-zA-Z]+$" , t[1] ) , _A ) )
_a = list(filter(lambda __a : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=_A ) , _A ) )
if max_length is not None and len(_A ) > max_length:
_a = toks[:max_length]
if min_length is not None and len(_A ) < min_length and len(_A ) > 0:
while len(_A ) < min_length:
_a = toks + toks
# toks_str = [t[1] for t in toks]
_a = [t[0] for t in toks]
# Ensure consistency
_a = tokenizer.decode(_A , clean_up_tokenization_spaces=_A )
if " " not in output_txt and len(_A ) > 1:
_a = (
tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=_A )
+ """ """
+ tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=_A )
)
if with_prefix_space:
_a = """ """ + output_txt
_a = tokenizer.encode(_A , add_special_tokens=_A )
return output_txt, output_ids
def UpperCamelCase__ ( self : Any ):
_a = self.perceiver_tokenizer
_a = """Unicode €."""
_a = tokenizer(_A )
_a = [4, 91, 1_16, 1_11, 1_05, 1_17, 1_06, 1_07, 38, 2_32, 1_36, 1_78, 52, 5]
self.assertEqual(encoded["input_ids"] , _A )
# decoding
_a = tokenizer.decode(_A )
self.assertEqual(_A , "[CLS]Unicode €.[SEP]" )
_a = tokenizer("e è é ê ë" )
_a = [4, 1_07, 38, 2_01, 1_74, 38, 2_01, 1_75, 38, 2_01, 1_76, 38, 2_01, 1_77, 5]
self.assertEqual(encoded["input_ids"] , _A )
# decoding
_a = tokenizer.decode(_A )
self.assertEqual(_A , "[CLS]e è é ê ë[SEP]" )
# encode/decode, but with `encode` instead of `__call__`
self.assertEqual(tokenizer.decode(tokenizer.encode("e è é ê ë" ) ) , "[CLS]e è é ê ë[SEP]" )
def UpperCamelCase__ ( self : List[Any] ):
_a = self.perceiver_tokenizer
_a = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""]
# fmt: off
_a = [4, 71, 38, 1_14, 1_17, 1_16, 1_09, 38, 1_18, 1_03, 1_20, 1_03, 1_09, 1_20, 1_03, 1_18, 1_10, 38, 1_08, 1_17, 1_20, 38, 1_21, 1_23, 1_15, 1_15, 1_03, 1_20, 1_11, 1_28, 1_03, 1_22, 1_11, 1_17, 1_16, 52, 5, 0]
# fmt: on
_a = tokenizer(_A , padding=_A , return_tensors=_A )
self.assertIsInstance(_A , _A )
if FRAMEWORK != "jax":
_a = list(batch.input_ids.numpy()[0] )
else:
_a = list(batch.input_ids.tolist()[0] )
self.assertListEqual(_A , _A )
self.assertEqual((2, 38) , batch.input_ids.shape )
self.assertEqual((2, 38) , batch.attention_mask.shape )
def UpperCamelCase__ ( self : Optional[Any] ):
_a = self.perceiver_tokenizer
_a = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""]
_a = tokenizer(_A , padding=_A , return_tensors=_A )
# check if input_ids are returned and no decoder_input_ids
self.assertIn("input_ids" , _A )
self.assertIn("attention_mask" , _A )
self.assertNotIn("decoder_input_ids" , _A )
self.assertNotIn("decoder_attention_mask" , _A )
def UpperCamelCase__ ( self : str ):
_a = self.perceiver_tokenizer
_a = [
"""Summary of the text.""",
"""Another summary.""",
]
_a = tokenizer(
text_target=_A , max_length=32 , padding="max_length" , truncation=_A , return_tensors=_A )
self.assertEqual(32 , targets["input_ids"].shape[1] )
def UpperCamelCase__ ( self : int ):
_a = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(f'{tokenizer.__class__.__name__}' ):
self.assertNotEqual(tokenizer.model_max_length , 42 )
# Now let's start the test
_a = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(f'{tokenizer.__class__.__name__}' ):
# Isolate this from the other tests because we save additional tokens/etc
_a = tempfile.mkdtemp()
_a = """ He is very happy, UNwant\u00E9d,running"""
_a = tokenizer.encode(_A , add_special_tokens=_A )
tokenizer.save_pretrained(_A )
_a = tokenizer.__class__.from_pretrained(_A )
_a = after_tokenizer.encode(_A , add_special_tokens=_A )
self.assertListEqual(_A , _A )
shutil.rmtree(_A )
_a = self.get_tokenizers(model_max_length=42 )
for tokenizer in tokenizers:
with self.subTest(f'{tokenizer.__class__.__name__}' ):
# Isolate this from the other tests because we save additional tokens/etc
_a = tempfile.mkdtemp()
_a = """ He is very happy, UNwant\u00E9d,running"""
tokenizer.add_tokens(["bim", "bambam"] )
_a = tokenizer.additional_special_tokens
additional_special_tokens.append("new_additional_special_token" )
tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens} )
_a = tokenizer.encode(_A , add_special_tokens=_A )
tokenizer.save_pretrained(_A )
_a = tokenizer.__class__.from_pretrained(_A )
_a = after_tokenizer.encode(_A , add_special_tokens=_A )
self.assertListEqual(_A , _A )
self.assertIn("new_additional_special_token" , after_tokenizer.additional_special_tokens )
self.assertEqual(after_tokenizer.model_max_length , 42 )
_a = tokenizer.__class__.from_pretrained(_A , model_max_length=43 )
self.assertEqual(tokenizer.model_max_length , 43 )
shutil.rmtree(_A )
def UpperCamelCase__ ( self : Optional[Any] ):
_a = []
if self.test_slow_tokenizer:
tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) )
if self.test_rust_tokenizer:
tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) )
for tokenizer_class, tokenizer_utils in tokenizer_list:
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer_utils.save_pretrained(_A )
with open(os.path.join(_A , "special_tokens_map.json" ) , encoding="utf-8" ) as json_file:
_a = json.load(_A )
with open(os.path.join(_A , "tokenizer_config.json" ) , encoding="utf-8" ) as json_file:
_a = json.load(_A )
_a = [f'<extra_id_{i}>' for i in range(1_25 )]
_a = added_tokens_extra_ids + [
"""an_additional_special_token"""
]
_a = added_tokens_extra_ids + [
"""an_additional_special_token"""
]
with open(os.path.join(_A , "special_tokens_map.json" ) , "w" , encoding="utf-8" ) as outfile:
json.dump(_A , _A )
with open(os.path.join(_A , "tokenizer_config.json" ) , "w" , encoding="utf-8" ) as outfile:
json.dump(_A , _A )
# the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
# into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
# "special_tokens_map.json" files
_a = tokenizer_class.from_pretrained(
_A , )
self.assertIn(
"an_additional_special_token" , tokenizer_without_change_in_init.additional_special_tokens )
self.assertEqual(
["an_additional_special_token"] , tokenizer_without_change_in_init.convert_ids_to_tokens(
tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"] ) ) , )
# Now we test that we can change the value of additional_special_tokens in the from_pretrained
_a = added_tokens_extra_ids + [AddedToken("a_new_additional_special_token" , lstrip=_A )]
_a = tokenizer_class.from_pretrained(
_A , additional_special_tokens=_A , )
self.assertIn("a_new_additional_special_token" , tokenizer.additional_special_tokens )
self.assertEqual(
["a_new_additional_special_token"] , tokenizer.convert_ids_to_tokens(
tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"] ) ) , )
def UpperCamelCase__ ( self : Tuple ):
_a = self.perceiver_tokenizer
self.assertEqual(tokenizer.decode([1_78] ) , "�" )
def UpperCamelCase__ ( self : List[str] ):
pass
def UpperCamelCase__ ( self : Optional[Any] ):
pass
def UpperCamelCase__ ( self : Optional[int] ):
pass
def UpperCamelCase__ ( self : int ):
pass
def UpperCamelCase__ ( self : List[str] ):
_a = self.get_tokenizers(fast=_A , do_lower_case=_A )
for tokenizer in tokenizers:
with self.subTest(f'{tokenizer.__class__.__name__}' ):
_a = ["""[CLS]""", """t""", """h""", """i""", """s""", """ """, """i""", """s""", """ """, """a""", """ """, """t""", """e""", """s""", """t""", """[SEP]"""]
_a = tokenizer.convert_tokens_to_string(_A )
self.assertIsInstance(_A , _A )
| 692 |
"""simple docstring"""
import io
import json
import fsspec
import pytest
from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.json import JsonDatasetReader, JsonDatasetWriter
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
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 UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
UpperCamelCase : Tuple = tmp_path / """cache"""
UpperCamelCase : Optional[int] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
UpperCamelCase : Tuple = JsonDatasetReader(SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE , keep_in_memory=SCREAMING_SNAKE_CASE ).read()
_check_json_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
@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 UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
UpperCamelCase : Optional[Any] = tmp_path / """cache"""
UpperCamelCase : int = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
UpperCamelCase : Union[str, Any] = features.copy() if features else default_expected_features
UpperCamelCase : str = (
Features({feature: Value(SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None
)
UpperCamelCase : Optional[int] = JsonDatasetReader(SCREAMING_SNAKE_CASE , features=SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read()
_check_json_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
@pytest.mark.parametrize(
"""features""" , [
None,
{"""col_3""": """float64""", """col_1""": """string""", """col_2""": """int64"""},
] , )
def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
UpperCamelCase : int = tmp_path / """cache"""
UpperCamelCase : Optional[int] = {"""col_3""": """float64""", """col_1""": """string""", """col_2""": """int64"""}
UpperCamelCase : Optional[Any] = features.copy() if features else default_expected_features
UpperCamelCase : Tuple = (
Features({feature: Value(SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None
)
UpperCamelCase : int = JsonDatasetReader(SCREAMING_SNAKE_CASE , features=SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read()
assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
assert dataset.num_rows == 2
assert dataset.num_columns == 3
assert dataset.column_names == ["col_3", "col_1", "col_2"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
# jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"}
UpperCamelCase : str = {"""col_2""": """int64""", """col_3""": """float64""", """col_1""": """string"""}
UpperCamelCase : Tuple = features.copy()
UpperCamelCase : Tuple = (
Features({feature: Value(SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None
)
UpperCamelCase : Optional[int] = tmp_path / """cache"""
UpperCamelCase : List[Any] = JsonDatasetReader(SCREAMING_SNAKE_CASE , features=SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read()
assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
assert dataset.num_rows == 2
assert dataset.num_columns == 3
assert dataset.column_names == ["col_2", "col_3", "col_1"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] )
def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
UpperCamelCase : Optional[int] = tmp_path / """cache"""
UpperCamelCase : Any = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
UpperCamelCase : Dict = JsonDatasetReader(SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE , split=SCREAMING_SNAKE_CASE ).read()
_check_json_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize("""path_type""" , [str, list] )
def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
if issubclass(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
UpperCamelCase : List[str] = jsonl_path
elif issubclass(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
UpperCamelCase : List[str] = [jsonl_path]
UpperCamelCase : List[Any] = tmp_path / """cache"""
UpperCamelCase : List[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
UpperCamelCase : Optional[int] = JsonDatasetReader(SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read()
_check_json_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=("train",) ):
assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
for split in splits:
UpperCamelCase : Optional[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 UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
UpperCamelCase : int = tmp_path / """cache"""
UpperCamelCase : int = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
UpperCamelCase : Any = JsonDatasetReader({"""train""": jsonl_path} , cache_dir=SCREAMING_SNAKE_CASE , keep_in_memory=SCREAMING_SNAKE_CASE ).read()
_check_json_datasetdict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
@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 UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
UpperCamelCase : List[str] = tmp_path / """cache"""
UpperCamelCase : Optional[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
UpperCamelCase : Optional[Any] = features.copy() if features else default_expected_features
UpperCamelCase : Optional[Any] = (
Features({feature: Value(SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None
)
UpperCamelCase : Optional[Any] = JsonDatasetReader({"""train""": jsonl_path} , features=SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read()
_check_json_datasetdict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
@pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] )
def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
if split:
UpperCamelCase : List[Any] = {split: jsonl_path}
else:
UpperCamelCase : Tuple = """train"""
UpperCamelCase : Union[str, Any] = {"""train""": jsonl_path, """test""": jsonl_path}
UpperCamelCase : Optional[Any] = tmp_path / """cache"""
UpperCamelCase : Optional[int] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
UpperCamelCase : Union[str, Any] = JsonDatasetReader(SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read()
_check_json_datasetdict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
def UpperCamelCase (SCREAMING_SNAKE_CASE ):
return json.load(SCREAMING_SNAKE_CASE )
def UpperCamelCase (SCREAMING_SNAKE_CASE ):
return [json.loads(SCREAMING_SNAKE_CASE ) for line in buffer]
class lowercase__ :
"""simple docstring"""
@pytest.mark.parametrize("""lines, load_json_function""" , [(True, load_json_lines), (False, load_json)] )
def _a ( self , _A , _A , _A ):
'''simple docstring'''
with io.BytesIO() as buffer:
JsonDatasetWriter(_A , _A , lines=_A ).write()
buffer.seek(0 )
UpperCamelCase : Optional[Any] = load_json_function(_A )
assert isinstance(_A , _A )
assert isinstance(exported_content[0] , _A )
assert len(_A ) == 1_0
@pytest.mark.parametrize(
"""orient, container, keys, len_at""" , [
("""records""", list, {"""tokens""", """labels""", """answers""", """id"""}, None),
("""split""", dict, {"""columns""", """data"""}, """data"""),
("""index""", dict, set("""0123456789""" ), None),
("""columns""", dict, {"""tokens""", """labels""", """answers""", """id"""}, """tokens"""),
("""values""", list, None, None),
("""table""", dict, {"""schema""", """data"""}, """data"""),
] , )
def _a ( self , _A , _A , _A , _A , _A ):
'''simple docstring'''
with io.BytesIO() as buffer:
JsonDatasetWriter(_A , _A , lines=_A , orient=_A ).write()
buffer.seek(0 )
UpperCamelCase : str = load_json(_A )
assert isinstance(_A , _A )
if keys:
if container is dict:
assert exported_content.keys() == keys
else:
assert exported_content[0].keys() == keys
else:
assert not hasattr(_A , """keys""" ) and not hasattr(exported_content[0] , """keys""" )
if len_at:
assert len(exported_content[len_at] ) == 1_0
else:
assert len(_A ) == 1_0
@pytest.mark.parametrize("""lines, load_json_function""" , [(True, load_json_lines), (False, load_json)] )
def _a ( self , _A , _A , _A ):
'''simple docstring'''
with io.BytesIO() as buffer:
JsonDatasetWriter(_A , _A , lines=_A , num_proc=2 ).write()
buffer.seek(0 )
UpperCamelCase : List[Any] = load_json_function(_A )
assert isinstance(_A , _A )
assert isinstance(exported_content[0] , _A )
assert len(_A ) == 1_0
@pytest.mark.parametrize(
"""orient, container, keys, len_at""" , [
("""records""", list, {"""tokens""", """labels""", """answers""", """id"""}, None),
("""split""", dict, {"""columns""", """data"""}, """data"""),
("""index""", dict, set("""0123456789""" ), None),
("""columns""", dict, {"""tokens""", """labels""", """answers""", """id"""}, """tokens"""),
("""values""", list, None, None),
("""table""", dict, {"""schema""", """data"""}, """data"""),
] , )
def _a ( self , _A , _A , _A , _A , _A ):
'''simple docstring'''
with io.BytesIO() as buffer:
JsonDatasetWriter(_A , _A , lines=_A , orient=_A , num_proc=2 ).write()
buffer.seek(0 )
UpperCamelCase : Dict = load_json(_A )
assert isinstance(_A , _A )
if keys:
if container is dict:
assert exported_content.keys() == keys
else:
assert exported_content[0].keys() == keys
else:
assert not hasattr(_A , """keys""" ) and not hasattr(exported_content[0] , """keys""" )
if len_at:
assert len(exported_content[len_at] ) == 1_0
else:
assert len(_A ) == 1_0
def _a ( self , _A ):
'''simple docstring'''
with pytest.raises(_A ):
with io.BytesIO() as buffer:
JsonDatasetWriter(_A , _A , num_proc=0 )
@pytest.mark.parametrize("""compression, extension""" , [("""gzip""", """gz"""), ("""bz2""", """bz2"""), ("""xz""", """xz""")] )
def _a ( self , _A , _A , _A , _A , _A ):
'''simple docstring'''
UpperCamelCase : List[str] = tmp_path_factory.mktemp("""data""" ) / f"""test.json.{extension}"""
UpperCamelCase : Tuple = str(shared_datadir / f"""test_file.json.{extension}""" )
JsonDatasetWriter(_A , _A , compression=_A ).write()
with fsspec.open(_A , """rb""" , compression="""infer""" ) as f:
UpperCamelCase : Dict = f.read()
with fsspec.open(_A , """rb""" , compression="""infer""" ) as f:
UpperCamelCase : Tuple = f.read()
assert exported_content == original_content
| 102 | 0 |
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Dict = {
'Pillow': 'Pillow',
'accelerate': 'accelerate>=0.11.0',
'compel': 'compel==0.1.8',
'black': 'black~=23.1',
'datasets': 'datasets',
'filelock': 'filelock',
'flax': 'flax>=0.4.1',
'hf-doc-builder': 'hf-doc-builder>=0.3.0',
'huggingface-hub': 'huggingface-hub>=0.13.2',
'requests-mock': 'requests-mock==1.10.0',
'importlib_metadata': 'importlib_metadata',
'invisible-watermark': 'invisible-watermark',
'isort': 'isort>=5.5.4',
'jax': 'jax>=0.2.8,!=0.3.2',
'jaxlib': 'jaxlib>=0.1.65',
'Jinja2': 'Jinja2',
'k-diffusion': 'k-diffusion>=0.0.12',
'torchsde': 'torchsde',
'note_seq': 'note_seq',
'librosa': 'librosa',
'numpy': 'numpy',
'omegaconf': 'omegaconf',
'parameterized': 'parameterized',
'protobuf': 'protobuf>=3.20.3,<4',
'pytest': 'pytest',
'pytest-timeout': 'pytest-timeout',
'pytest-xdist': 'pytest-xdist',
'ruff': 'ruff>=0.0.241',
'safetensors': 'safetensors',
'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92',
'scipy': 'scipy',
'onnx': 'onnx',
'regex': 'regex!=2019.12.17',
'requests': 'requests',
'tensorboard': 'tensorboard',
'torch': 'torch>=1.4',
'torchvision': 'torchvision',
'transformers': 'transformers>=4.25.1',
'urllib3': 'urllib3<=2.0.0',
}
| 700 |
"""simple docstring"""
def _snake_case ( UpperCAmelCase_ : int ):
A__ = generate_pascal_triangle(UpperCAmelCase_ )
for row_idx in range(UpperCAmelCase_ ):
# Print left spaces
for _ in range(num_rows - row_idx - 1 ):
print(end=""" """ )
# Print row values
for col_idx in range(row_idx + 1 ):
if col_idx != row_idx:
print(triangle[row_idx][col_idx] , end=""" """ )
else:
print(triangle[row_idx][col_idx] , end="""""" )
print()
def _snake_case ( UpperCAmelCase_ : int ):
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ):
raise TypeError("""The input value of 'num_rows' should be 'int'""" )
if num_rows == 0:
return []
elif num_rows < 0:
raise ValueError(
"""The input value of 'num_rows' should be greater than or equal to 0""" )
A__ = []
for current_row_idx in range(UpperCAmelCase_ ):
A__ = populate_current_row(UpperCAmelCase_ , UpperCAmelCase_ )
triangle.append(UpperCAmelCase_ )
return triangle
def _snake_case ( UpperCAmelCase_ : list[list[int]] , UpperCAmelCase_ : int ):
A__ = [-1] * (current_row_idx + 1)
# first and last elements of current row are equal to 1
A__ , A__ = 1, 1
for current_col_idx in range(1 , UpperCAmelCase_ ):
calculate_current_element(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
return current_row
def _snake_case ( UpperCAmelCase_ : list[list[int]] , UpperCAmelCase_ : list[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , ):
A__ = triangle[current_row_idx - 1][current_col_idx - 1]
A__ = triangle[current_row_idx - 1][current_col_idx]
A__ = above_to_left_elt + above_to_right_elt
def _snake_case ( UpperCAmelCase_ : int ):
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ):
raise TypeError("""The input value of 'num_rows' should be 'int'""" )
if num_rows == 0:
return []
elif num_rows < 0:
raise ValueError(
"""The input value of 'num_rows' should be greater than or equal to 0""" )
A__ = [[1]]
for row_index in range(1 , UpperCAmelCase_ ):
A__ = [0] + result[-1] + [0]
A__ = row_index + 1
# Calculate the number of distinct elements in a row
A__ = sum(divmod(UpperCAmelCase_ , 2 ) )
A__ = [
temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 )
]
A__ = row_first_half[: (row_index + 1) // 2]
row_second_half.reverse()
A__ = row_first_half + row_second_half
result.append(UpperCAmelCase_ )
return result
def _snake_case ( ):
from collections.abc import Callable
from timeit import timeit
def benchmark_a_function(UpperCAmelCase_ : Callable , UpperCAmelCase_ : int ) -> None:
A__ = F"""{func.__name__}({value})"""
A__ = timeit(F"""__main__.{call}""" , setup="""import __main__""" )
# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
print(F"""{call:38} -- {timing:.4f} seconds""" )
for value in range(15 ): # (1, 7, 14):
for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
benchmark_a_function(UpperCAmelCase_ , UpperCAmelCase_ )
print()
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 500 | 0 |
import os
import tempfile
import unittest
from transformers import DistilBertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
DistilBertForMaskedLM,
DistilBertForMultipleChoice,
DistilBertForQuestionAnswering,
DistilBertForSequenceClassification,
DistilBertForTokenClassification,
DistilBertModel,
)
class lowerCamelCase_ ( _lowercase ):
def __init__( self : List[Any] , __A : Any , __A : str=13 , __A : str=7 , __A : Union[str, Any]=True , __A : int=True , __A : Optional[int]=False , __A : Tuple=True , __A : Union[str, Any]=99 , __A : List[str]=32 , __A : Tuple=5 , __A : Tuple=4 , __A : Union[str, Any]=37 , __A : int="gelu" , __A : int=0.1 , __A : Dict=0.1 , __A : int=512 , __A : List[str]=16 , __A : Union[str, Any]=2 , __A : Dict=0.0_2 , __A : Dict=3 , __A : str=4 , __A : str=None , ):
__A : List[Any] = parent
__A : Optional[Any] = batch_size
__A : Tuple = seq_length
__A : int = is_training
__A : str = use_input_mask
__A : List[str] = use_token_type_ids
__A : Dict = use_labels
__A : Optional[int] = vocab_size
__A : Dict = hidden_size
__A : List[Any] = num_hidden_layers
__A : Dict = num_attention_heads
__A : Union[str, Any] = intermediate_size
__A : Any = hidden_act
__A : List[Any] = hidden_dropout_prob
__A : Optional[int] = attention_probs_dropout_prob
__A : Tuple = max_position_embeddings
__A : List[str] = type_vocab_size
__A : Dict = type_sequence_label_size
__A : List[Any] = initializer_range
__A : int = num_labels
__A : Dict = num_choices
__A : Union[str, Any] = scope
def lowerCAmelCase_ ( self : List[Any] ):
__A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__A : List[Any] = None
if self.use_input_mask:
__A : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] )
__A : Union[str, Any] = None
__A : int = None
__A : List[Any] = None
if self.use_labels:
__A : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__A : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__A : Optional[int] = ids_tensor([self.batch_size] , self.num_choices )
__A : Any = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def lowerCAmelCase_ ( self : List[Any] ):
return 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 , )
def lowerCAmelCase_ ( self : Optional[Any] , __A : str , __A : Optional[Any] , __A : str , __A : List[Any] , __A : Any , __A : Tuple ):
__A : Any = DistilBertModel(config=__A )
model.to(__A )
model.eval()
__A : Optional[Any] = model(__A , __A )
__A : List[str] = model(__A )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def lowerCAmelCase_ ( self : Any , __A : Tuple , __A : Optional[int] , __A : Tuple , __A : List[Any] , __A : Any , __A : List[str] ):
__A : Optional[int] = DistilBertForMaskedLM(config=__A )
model.to(__A )
model.eval()
__A : Optional[int] = model(__A , attention_mask=__A , labels=__A )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def lowerCAmelCase_ ( self : Optional[Any] , __A : Dict , __A : Any , __A : Any , __A : Optional[int] , __A : Optional[int] , __A : List[Any] ):
__A : List[str] = DistilBertForQuestionAnswering(config=__A )
model.to(__A )
model.eval()
__A : int = model(
__A , attention_mask=__A , start_positions=__A , end_positions=__A )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def lowerCAmelCase_ ( self : int , __A : Optional[Any] , __A : List[Any] , __A : str , __A : Optional[Any] , __A : Optional[int] , __A : List[Any] ):
__A : Dict = self.num_labels
__A : Optional[Any] = DistilBertForSequenceClassification(__A )
model.to(__A )
model.eval()
__A : Optional[Any] = model(__A , attention_mask=__A , labels=__A )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def lowerCAmelCase_ ( self : List[str] , __A : str , __A : Any , __A : Tuple , __A : Tuple , __A : Tuple , __A : Any ):
__A : Any = self.num_labels
__A : Any = DistilBertForTokenClassification(config=__A )
model.to(__A )
model.eval()
__A : Dict = model(__A , attention_mask=__A , labels=__A )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def lowerCAmelCase_ ( self : List[str] , __A : Optional[Any] , __A : Dict , __A : List[Any] , __A : Optional[int] , __A : Tuple , __A : Any ):
__A : List[Any] = self.num_choices
__A : Any = DistilBertForMultipleChoice(config=__A )
model.to(__A )
model.eval()
__A : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__A : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__A : Optional[Any] = model(
__A , attention_mask=__A , labels=__A , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def lowerCAmelCase_ ( self : List[Any] ):
__A : Union[str, Any] = self.prepare_config_and_inputs()
((__A) , (__A) , (__A) , (__A) , (__A) , (__A)) : Any = config_and_inputs
__A : List[str] = {"""input_ids""": input_ids, """attention_mask""": input_mask}
return config, inputs_dict
@require_torch
class lowerCamelCase_ ( _lowercase , _lowercase , unittest.TestCase ):
_lowercase : Union[str, Any] = (
(
DistilBertModel,
DistilBertForMaskedLM,
DistilBertForMultipleChoice,
DistilBertForQuestionAnswering,
DistilBertForSequenceClassification,
DistilBertForTokenClassification,
)
if is_torch_available()
else None
)
_lowercase : List[str] = (
{
'''feature-extraction''': DistilBertModel,
'''fill-mask''': DistilBertForMaskedLM,
'''question-answering''': DistilBertForQuestionAnswering,
'''text-classification''': DistilBertForSequenceClassification,
'''token-classification''': DistilBertForTokenClassification,
'''zero-shot''': DistilBertForSequenceClassification,
}
if is_torch_available()
else {}
)
_lowercase : Dict = True
_lowercase : List[Any] = True
_lowercase : str = True
_lowercase : Dict = True
def lowerCAmelCase_ ( self : Optional[Any] ):
__A : Optional[int] = DistilBertModelTester(self )
__A : Dict = ConfigTester(self , config_class=__A , dim=37 )
def lowerCAmelCase_ ( self : List[Any] ):
self.config_tester.run_common_tests()
def lowerCAmelCase_ ( self : Any ):
__A : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_model(*__A )
def lowerCAmelCase_ ( self : Dict ):
__A : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_masked_lm(*__A )
def lowerCAmelCase_ ( self : Union[str, Any] ):
__A : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_question_answering(*__A )
def lowerCAmelCase_ ( self : Optional[int] ):
__A : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_sequence_classification(*__A )
def lowerCAmelCase_ ( self : str ):
__A : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_token_classification(*__A )
def lowerCAmelCase_ ( self : str ):
__A : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_multiple_choice(*__A )
@slow
def lowerCAmelCase_ ( self : int ):
for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__A : Union[str, Any] = DistilBertModel.from_pretrained(__A )
self.assertIsNotNone(__A )
@slow
@require_torch_gpu
def lowerCAmelCase_ ( self : int ):
__A , __A : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
# BertForMultipleChoice behaves incorrectly in JIT environments.
if model_class == DistilBertForMultipleChoice:
return
__A : List[str] = True
__A : List[str] = model_class(config=__A )
__A : Any = self._prepare_for_class(__A , __A )
__A : Tuple = torch.jit.trace(
__A , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) )
with tempfile.TemporaryDirectory() as tmp:
torch.jit.save(__A , os.path.join(__A , """traced_model.pt""" ) )
__A : List[str] = torch.jit.load(os.path.join(__A , """traced_model.pt""" ) , map_location=__A )
loaded(inputs_dict["""input_ids"""].to(__A ) , inputs_dict["""attention_mask"""].to(__A ) )
@require_torch
class lowerCamelCase_ ( unittest.TestCase ):
@slow
def lowerCAmelCase_ ( self : Optional[int] ):
__A : Dict = DistilBertModel.from_pretrained("""distilbert-base-uncased""" )
__A : Union[str, Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] )
__A : List[Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
with torch.no_grad():
__A : Tuple = model(__A , attention_mask=__A )[0]
__A : int = torch.Size((1, 11, 768) )
self.assertEqual(output.shape , __A )
__A : Optional[int] = torch.tensor(
[[[-0.1_6_3_9, 0.3_2_9_9, 0.1_6_4_8], [-0.1_7_4_6, 0.3_2_8_9, 0.1_7_1_0], [-0.1_8_8_4, 0.3_3_5_7, 0.1_8_1_0]]] )
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __A , atol=1e-4 ) )
| 17 |
"""simple docstring"""
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import MobileViTImageProcessor
class lowerCamelCase (unittest.TestCase ):
def __init__( self : Tuple , __UpperCAmelCase : str , __UpperCAmelCase : Any=7 , __UpperCAmelCase : Union[str, Any]=3 , __UpperCAmelCase : Any=1_8 , __UpperCAmelCase : Tuple=3_0 , __UpperCAmelCase : List[Any]=4_0_0 , __UpperCAmelCase : Dict=True , __UpperCAmelCase : int=None , __UpperCAmelCase : List[Any]=True , __UpperCAmelCase : Any=None , __UpperCAmelCase : Any=True , ) -> Tuple:
SCREAMING_SNAKE_CASE__ = size if size is not None else {"""shortest_edge""": 2_0}
SCREAMING_SNAKE_CASE__ = crop_size if crop_size is not None else {"""height""": 1_8, """width""": 1_8}
SCREAMING_SNAKE_CASE__ = parent
SCREAMING_SNAKE_CASE__ = batch_size
SCREAMING_SNAKE_CASE__ = num_channels
SCREAMING_SNAKE_CASE__ = image_size
SCREAMING_SNAKE_CASE__ = min_resolution
SCREAMING_SNAKE_CASE__ = max_resolution
SCREAMING_SNAKE_CASE__ = do_resize
SCREAMING_SNAKE_CASE__ = size
SCREAMING_SNAKE_CASE__ = do_center_crop
SCREAMING_SNAKE_CASE__ = crop_size
SCREAMING_SNAKE_CASE__ = do_flip_channel_order
def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any:
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_flip_channel_order": self.do_flip_channel_order,
}
@require_torch
@require_vision
class lowerCamelCase (A__ ,unittest.TestCase ):
lowerCamelCase__ : Tuple = MobileViTImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE ( self : Dict ) -> Any:
SCREAMING_SNAKE_CASE__ = MobileViTImageProcessingTester(self )
@property
def SCREAMING_SNAKE_CASE ( self : List[str] ) -> int:
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]:
SCREAMING_SNAKE_CASE__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__UpperCAmelCase , """do_resize""" ) )
self.assertTrue(hasattr(__UpperCAmelCase , """size""" ) )
self.assertTrue(hasattr(__UpperCAmelCase , """do_center_crop""" ) )
self.assertTrue(hasattr(__UpperCAmelCase , """center_crop""" ) )
self.assertTrue(hasattr(__UpperCAmelCase , """do_flip_channel_order""" ) )
def SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]:
SCREAMING_SNAKE_CASE__ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"""shortest_edge""": 2_0} )
self.assertEqual(image_processor.crop_size , {"""height""": 1_8, """width""": 1_8} )
SCREAMING_SNAKE_CASE__ = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4 )
self.assertEqual(image_processor.size , {"""shortest_edge""": 4_2} )
self.assertEqual(image_processor.crop_size , {"""height""": 8_4, """width""": 8_4} )
def SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict:
pass
def SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]:
# Initialize image_processing
SCREAMING_SNAKE_CASE__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
SCREAMING_SNAKE_CASE__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase )
for image in image_inputs:
self.assertIsInstance(__UpperCAmelCase , Image.Image )
# Test not batched input
SCREAMING_SNAKE_CASE__ = 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
SCREAMING_SNAKE_CASE__ = image_processing(__UpperCAmelCase , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["""height"""],
self.image_processor_tester.crop_size["""width"""],
) , )
def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]:
# Initialize image_processing
SCREAMING_SNAKE_CASE__ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
SCREAMING_SNAKE_CASE__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase )
for image in image_inputs:
self.assertIsInstance(__UpperCAmelCase , np.ndarray )
# Test not batched input
SCREAMING_SNAKE_CASE__ = 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
SCREAMING_SNAKE_CASE__ = image_processing(__UpperCAmelCase , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["""height"""],
self.image_processor_tester.crop_size["""width"""],
) , )
def SCREAMING_SNAKE_CASE ( self : List[str] ) -> str:
# Initialize image_processing
SCREAMING_SNAKE_CASE__ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
SCREAMING_SNAKE_CASE__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase )
for image in image_inputs:
self.assertIsInstance(__UpperCAmelCase , torch.Tensor )
# Test not batched input
SCREAMING_SNAKE_CASE__ = 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
SCREAMING_SNAKE_CASE__ = image_processing(__UpperCAmelCase , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["""height"""],
self.image_processor_tester.crop_size["""width"""],
) , )
| 196 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
A_ = {
"configuration_bridgetower": [
"BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP",
"BridgeTowerConfig",
"BridgeTowerTextConfig",
"BridgeTowerVisionConfig",
],
"processing_bridgetower": ["BridgeTowerProcessor"],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A_ = ["BridgeTowerImageProcessor"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A_ = [
"BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST",
"BridgeTowerForContrastiveLearning",
"BridgeTowerForImageAndTextRetrieval",
"BridgeTowerForMaskedLM",
"BridgeTowerModel",
"BridgeTowerPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_bridgetower import (
BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP,
BridgeTowerConfig,
BridgeTowerTextConfig,
BridgeTowerVisionConfig,
)
from .processing_bridgetower import BridgeTowerProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_bridgetower import BridgeTowerImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_bridgetower import (
BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST,
BridgeTowerForContrastiveLearning,
BridgeTowerForImageAndTextRetrieval,
BridgeTowerForMaskedLM,
BridgeTowerModel,
BridgeTowerPreTrainedModel,
)
else:
import sys
A_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
| 479 | from __future__ import annotations
from fractions import Fraction
from math import gcd, sqrt
def __UpperCAmelCase ( UpperCAmelCase )-> bool:
"""simple docstring"""
lowercase = int(number**0.5 )
return number == sq * sq
def __UpperCAmelCase ( UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase )-> tuple[int, int]:
"""simple docstring"""
lowercase = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den
lowercase = x_den * y_den * z_den
lowercase = gcd(UpperCAmelCase, UpperCAmelCase )
top //= hcf
bottom //= hcf
return top, bottom
def __UpperCAmelCase ( UpperCAmelCase = 35 )-> int:
"""simple docstring"""
lowercase = set()
lowercase = 42
lowercase = Fraction(0 )
lowercase = 42
for x_num in range(1, order + 1 ):
for x_den in range(x_num + 1, order + 1 ):
for y_num in range(1, order + 1 ):
for y_den in range(y_num + 1, order + 1 ):
# n=1
lowercase = x_num * y_den + x_den * y_num
lowercase = x_den * y_den
lowercase = gcd(UpperCAmelCase, UpperCAmelCase )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
lowercase = add_three(
UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase )
unique_s.add(UpperCAmelCase )
# n=2
lowercase = (
x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num
)
lowercase = x_den * x_den * y_den * y_den
if is_sq(UpperCAmelCase ) and is_sq(UpperCAmelCase ):
lowercase = int(sqrt(UpperCAmelCase ) )
lowercase = int(sqrt(UpperCAmelCase ) )
lowercase = gcd(UpperCAmelCase, UpperCAmelCase )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
lowercase = add_three(
UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase )
unique_s.add(UpperCAmelCase )
# n=-1
lowercase = x_num * y_num
lowercase = x_den * y_num + x_num * y_den
lowercase = gcd(UpperCAmelCase, UpperCAmelCase )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
lowercase = add_three(
UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase )
unique_s.add(UpperCAmelCase )
# n=2
lowercase = x_num * x_num * y_num * y_num
lowercase = (
x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den
)
if is_sq(UpperCAmelCase ) and is_sq(UpperCAmelCase ):
lowercase = int(sqrt(UpperCAmelCase ) )
lowercase = int(sqrt(UpperCAmelCase ) )
lowercase = gcd(UpperCAmelCase, UpperCAmelCase )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
lowercase = add_three(
UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase )
unique_s.add(UpperCAmelCase )
for num, den in unique_s:
total += Fraction(UpperCAmelCase, UpperCAmelCase )
return total.denominator + total.numerator
if __name__ == "__main__":
print(F"{solution() = }")
| 479 | 1 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__snake_case = logging.get_logger(__name__)
__snake_case = {
"""microsoft/markuplm-base""": """https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json""",
"""microsoft/markuplm-large""": """https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json""",
}
class _lowerCAmelCase ( snake_case_ ):
__UpperCAmelCase : Optional[Any] = '''markuplm'''
def __init__( self , UpperCamelCase__=3_0522 , UpperCamelCase__=768 , UpperCamelCase__=12 , UpperCamelCase__=12 , UpperCamelCase__=3072 , UpperCamelCase__="gelu" , UpperCamelCase__=0.1 , UpperCamelCase__=0.1 , UpperCamelCase__=512 , UpperCamelCase__=2 , UpperCamelCase__=0.02 , UpperCamelCase__=1e-12 , UpperCamelCase__=0 , UpperCamelCase__=0 , UpperCamelCase__=2 , UpperCamelCase__=256 , UpperCamelCase__=1024 , UpperCamelCase__=216 , UpperCamelCase__=1001 , UpperCamelCase__=32 , UpperCamelCase__=50 , UpperCamelCase__="absolute" , UpperCamelCase__=True , UpperCamelCase__=None , **UpperCamelCase__ , ) -> List[str]:
'''simple docstring'''
super().__init__(
pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ , )
snake_case : Optional[Any] = vocab_size
snake_case : Union[str, Any] = hidden_size
snake_case : str = num_hidden_layers
snake_case : Tuple = num_attention_heads
snake_case : Dict = hidden_act
snake_case : Any = intermediate_size
snake_case : Tuple = hidden_dropout_prob
snake_case : Optional[int] = attention_probs_dropout_prob
snake_case : Optional[Any] = max_position_embeddings
snake_case : List[str] = type_vocab_size
snake_case : int = initializer_range
snake_case : List[Any] = layer_norm_eps
snake_case : Optional[Any] = position_embedding_type
snake_case : Union[str, Any] = use_cache
snake_case : Dict = classifier_dropout
# additional properties
snake_case : List[Any] = max_depth
snake_case : int = max_xpath_tag_unit_embeddings
snake_case : Optional[int] = max_xpath_subs_unit_embeddings
snake_case : Union[str, Any] = tag_pad_id
snake_case : List[str] = subs_pad_id
snake_case : int = xpath_unit_hidden_size
| 178 |
"""simple docstring"""
import uuid
from typing import Any, Dict, List, Optional, Union
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_tf_available():
import tensorflow as tf
if is_torch_available():
import torch
__snake_case = logging.get_logger(__name__)
class _lowerCAmelCase :
def __init__( self , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__=None , UpperCamelCase__=None ) -> Optional[Any]:
'''simple docstring'''
if not conversation_id:
snake_case : Union[str, Any] = uuid.uuida()
if past_user_inputs is None:
snake_case : Optional[Any] = []
if generated_responses is None:
snake_case : Optional[Any] = []
snake_case : uuid.UUID = conversation_id
snake_case : List[str] = past_user_inputs
snake_case : List[str] = generated_responses
snake_case : Optional[str] = text
def __eq__( self , UpperCamelCase__ ) -> Any:
'''simple docstring'''
if not isinstance(UpperCamelCase__ , UpperCamelCase__ ):
return False
if self.uuid == other.uuid:
return True
return (
self.new_user_input == other.new_user_input
and self.past_user_inputs == other.past_user_inputs
and self.generated_responses == other.generated_responses
)
def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__ = False ) -> Dict:
'''simple docstring'''
if self.new_user_input:
if overwrite:
logger.warning(
F'User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten '
F'with: "{text}".' )
snake_case : int = text
else:
logger.warning(
F'User input added while unprocessed input was existing: "{self.new_user_input}" new input '
F'ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input' )
else:
snake_case : Any = text
def lowerCamelCase ( self ) -> List[str]:
'''simple docstring'''
if self.new_user_input:
self.past_user_inputs.append(self.new_user_input )
snake_case : Dict = None
def lowerCamelCase ( self , UpperCamelCase__ ) -> List[str]:
'''simple docstring'''
self.generated_responses.append(UpperCamelCase__ )
def lowerCamelCase ( self ) -> List[Any]:
'''simple docstring'''
for user_input, generated_response in zip(self.past_user_inputs , self.generated_responses ):
yield True, user_input
yield False, generated_response
if self.new_user_input:
yield True, self.new_user_input
def __repr__( self ) -> Union[str, Any]:
'''simple docstring'''
snake_case : Optional[Any] = F'Conversation id: {self.uuid} \n'
for is_user, text in self.iter_texts():
snake_case : List[str] = "user" if is_user else "bot"
output += F'{name} >> {text} \n'
return output
@add_end_docstrings(
snake_case_ , R'''
min_length_for_response (`int`, *optional*, defaults to 32):
The minimum length (in number of tokens) for a response.
minimum_tokens (`int`, *optional*, defaults to 10):
The minimum length of tokens to leave for a response.
''' , )
class _lowerCAmelCase ( snake_case_ ):
def __init__( self , *UpperCamelCase__ , **UpperCamelCase__ ) -> str:
'''simple docstring'''
super().__init__(*UpperCamelCase__ , **UpperCamelCase__ )
if self.tokenizer.pad_token_id is None:
snake_case : str = self.tokenizer.eos_token
def lowerCamelCase ( self , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , **UpperCamelCase__ ) -> Union[str, Any]:
'''simple docstring'''
snake_case : Tuple = {}
snake_case : Optional[int] = {}
snake_case : Optional[Any] = {}
if min_length_for_response is not None:
snake_case : int = min_length_for_response
if minimum_tokens is not None:
snake_case : Dict = minimum_tokens
if "max_length" in generate_kwargs:
snake_case : Any = generate_kwargs["max_length"]
# self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
if clean_up_tokenization_spaces is not None:
snake_case : Optional[Any] = clean_up_tokenization_spaces
if generate_kwargs:
forward_params.update(UpperCamelCase__ )
return preprocess_params, forward_params, postprocess_params
def __call__( self , UpperCamelCase__ , UpperCamelCase__=0 , **UpperCamelCase__ ) -> List[str]:
'''simple docstring'''
snake_case : int = super().__call__(UpperCamelCase__ , num_workers=UpperCamelCase__ , **UpperCamelCase__ )
if isinstance(UpperCamelCase__ , UpperCamelCase__ ) and len(UpperCamelCase__ ) == 1:
return outputs[0]
return outputs
def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__=32 ) -> Dict[str, Any]:
'''simple docstring'''
if not isinstance(UpperCamelCase__ , UpperCamelCase__ ):
raise ValueError("ConversationalPipeline, expects Conversation as inputs" )
if conversation.new_user_input is None:
raise ValueError(
F'Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. '
"Add user inputs with the conversation's `add_user_input` method" )
if hasattr(self.tokenizer , "_build_conversation_input_ids" ):
snake_case : Optional[Any] = self.tokenizer._build_conversation_input_ids(UpperCamelCase__ )
else:
# If the tokenizer cannot handle conversations, we default to only the old version
snake_case : Optional[Any] = self._legacy_parse_and_tokenize(UpperCamelCase__ )
if self.framework == "pt":
snake_case : Union[str, Any] = torch.LongTensor([input_ids] )
elif self.framework == "tf":
snake_case : Optional[int] = tf.constant([input_ids] )
return {"input_ids": input_ids, "conversation": conversation}
def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__=10 , **UpperCamelCase__ ) -> Union[str, Any]:
'''simple docstring'''
snake_case : Dict = generate_kwargs.get("max_length" , self.model.config.max_length )
snake_case : Optional[Any] = model_inputs["input_ids"].shape[1]
if max_length - minimum_tokens < n:
logger.warning(F'Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})' )
snake_case : List[str] = max_length - minimum_tokens
snake_case : Dict = model_inputs["input_ids"][:, -trim:]
if "attention_mask" in model_inputs:
snake_case : List[Any] = model_inputs["attention_mask"][:, -trim:]
snake_case : Union[str, Any] = model_inputs.pop("conversation" )
snake_case : Union[str, Any] = max_length
snake_case : Any = self.model.generate(**UpperCamelCase__ , **UpperCamelCase__ )
if self.model.config.is_encoder_decoder:
snake_case : Optional[int] = 1
else:
snake_case : int = n
return {"output_ids": output_ids[:, start_position:], "conversation": conversation}
def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__=True ) -> Tuple:
'''simple docstring'''
snake_case : Union[str, Any] = model_outputs["output_ids"]
snake_case : str = self.tokenizer.decode(
output_ids[0] , skip_special_tokens=UpperCamelCase__ , clean_up_tokenization_spaces=UpperCamelCase__ , )
snake_case : List[Any] = model_outputs["conversation"]
conversation.mark_processed()
conversation.append_response(UpperCamelCase__ )
return conversation
def lowerCamelCase ( self , UpperCamelCase__ ) -> Dict:
'''simple docstring'''
snake_case : str = self.tokenizer.eos_token_id
snake_case : str = []
for is_user, text in conversation.iter_texts():
if eos_token_id is not None:
input_ids.extend(self.tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) + [eos_token_id] )
else:
input_ids.extend(self.tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) )
if len(UpperCamelCase__ ) > self.tokenizer.model_max_length:
snake_case : str = input_ids[-self.tokenizer.model_max_length :]
return input_ids
| 178 | 1 |
def lowerCamelCase__ (_UpperCAmelCase = 100):
SCREAMING_SNAKE_CASE = 0
SCREAMING_SNAKE_CASE = 0
for i in range(1 , n + 1):
sum_of_squares += i**2
sum_of_ints += i
return sum_of_ints**2 - sum_of_squares
if __name__ == "__main__":
print(f"""{solution() = }""")
| 444 |
a_ : Tuple = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.',
'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.',
'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-',
'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '1': '.----',
'2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...',
'8': '---..', '9': '----.', '0': '-----', '&': '.-...', '@': '.--.-.',
':': '---...', ',': '--..--', '.': '.-.-.-', '\'': '.----.', '"': '.-..-.',
'?': '..--..', '/': '-..-.', '=': '-...-', '+': '.-.-.', '-': '-....-',
'(': '-.--.', ')': '-.--.-', '!': '-.-.--', ' ': '/'
} # Exclamation mark is not in ITU-R recommendation
# fmt: on
a_ : List[Any] = {value: key for key, value in MORSE_CODE_DICT.items()}
def lowerCamelCase__ (_UpperCAmelCase):
return " ".join(MORSE_CODE_DICT[char] for char in message.upper())
def lowerCamelCase__ (_UpperCAmelCase):
return "".join(REVERSE_DICT[char] for char in message.split())
def lowerCamelCase__ ():
SCREAMING_SNAKE_CASE = 'Morse code here!'
print(_UpperCAmelCase)
SCREAMING_SNAKE_CASE = encrypt(_UpperCAmelCase)
print(_UpperCAmelCase)
SCREAMING_SNAKE_CASE = decrypt(_UpperCAmelCase)
print(_UpperCAmelCase)
if __name__ == "__main__":
main()
| 444 | 1 |
"""simple docstring"""
from math import isqrt
def lowercase ( __UpperCamelCase ) -> bool:
return all(number % divisor != 0 for divisor in range(2 , isqrt(__UpperCamelCase ) + 1 ) )
def lowercase ( __UpperCamelCase = 10**6 ) -> int:
__magic_name__ = 0
__magic_name__ = 1
__magic_name__ = 7
while prime_candidate < max_prime:
primes_count += is_prime(__UpperCamelCase )
cube_index += 1
prime_candidate += 6 * cube_index
return primes_count
if __name__ == "__main__":
print(f"""{solution() = }""")
| 490 |
"""simple docstring"""
import unittest
from transformers import PegasusTokenizer, PegasusTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
__lowerCamelCase = get_tests_dir("fixtures/test_sentencepiece_no_bos.model")
@require_sentencepiece
@require_tokenizers
class _lowercase ( __UpperCAmelCase , unittest.TestCase ):
_lowerCamelCase = PegasusTokenizer
_lowerCamelCase = PegasusTokenizerFast
_lowerCamelCase = True
_lowerCamelCase = True
def lowerCAmelCase__ ( self ):
super().setUp()
# We have a SentencePiece fixture for testing
__magic_name__ = PegasusTokenizer(UpperCamelCase_ )
tokenizer.save_pretrained(self.tmpdirname )
@cached_property
def lowerCAmelCase__ ( self ):
return PegasusTokenizer.from_pretrained('''google/pegasus-large''' )
def lowerCAmelCase__ ( self , **UpperCamelCase_ ):
return PegasusTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase_ )
def lowerCAmelCase__ ( self , UpperCamelCase_ ):
return ("This is a test", "This is a test")
def lowerCAmelCase__ ( self ):
__magic_name__ = '''</s>'''
__magic_name__ = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase_ ) , UpperCamelCase_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase_ ) , UpperCamelCase_ )
def lowerCAmelCase__ ( self ):
__magic_name__ = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '''<pad>''' )
self.assertEqual(vocab_keys[1] , '''</s>''' )
self.assertEqual(vocab_keys[-1] , '''v''' )
self.assertEqual(len(UpperCamelCase_ ) , 1103 )
def lowerCAmelCase__ ( self ):
self.assertEqual(self.get_tokenizer().vocab_size , 1103 )
def lowerCAmelCase__ ( self ):
__magic_name__ = self.rust_tokenizer_class.from_pretrained(self.tmpdirname )
__magic_name__ = self.tokenizer_class.from_pretrained(self.tmpdirname )
__magic_name__ = (
'''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important'''
''' </s> <pad> <pad> <pad>'''
)
__magic_name__ = rust_tokenizer([raw_input_str] , return_tensors=UpperCamelCase_ , add_special_tokens=UpperCamelCase_ ).input_ids[0]
__magic_name__ = py_tokenizer([raw_input_str] , return_tensors=UpperCamelCase_ , add_special_tokens=UpperCamelCase_ ).input_ids[0]
self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ )
def lowerCAmelCase__ ( self ):
__magic_name__ = self._large_tokenizer
# <mask_1> masks whole sentence while <mask_2> masks single word
__magic_name__ = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.'''
__magic_name__ = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1]
__magic_name__ = tokenizer([raw_input_str] , return_tensors=UpperCamelCase_ ).input_ids[0]
self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ )
def lowerCAmelCase__ ( self ):
__magic_name__ = self._large_tokenizer
# The tracebacks for the following asserts are **better** without messages or self.assertEqual
assert tokenizer.vocab_size == 9_6103
assert tokenizer.pad_token_id == 0
assert tokenizer.eos_token_id == 1
assert tokenizer.offset == 103
assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105
assert tokenizer.unk_token == "<unk>"
assert tokenizer.model_max_length == 1024
__magic_name__ = '''To ensure a smooth flow of bank resolutions.'''
__magic_name__ = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1]
__magic_name__ = tokenizer([raw_input_str] , return_tensors=UpperCamelCase_ ).input_ids[0]
self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ )
assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"]
@require_torch
def lowerCAmelCase__ ( self ):
__magic_name__ = ['''This is going to be way too long.''' * 150, '''short example''']
__magic_name__ = ['''not super long but more than 5 tokens''', '''tiny''']
__magic_name__ = self._large_tokenizer(UpperCamelCase_ , padding=UpperCamelCase_ , truncation=UpperCamelCase_ , return_tensors='''pt''' )
__magic_name__ = self._large_tokenizer(
text_target=UpperCamelCase_ , max_length=5 , padding=UpperCamelCase_ , truncation=UpperCamelCase_ , return_tensors='''pt''' )
assert batch.input_ids.shape == (2, 1024)
assert batch.attention_mask.shape == (2, 1024)
assert targets["input_ids"].shape == (2, 5)
assert len(UpperCamelCase_ ) == 2 # input_ids, attention_mask.
@slow
def lowerCAmelCase__ ( self ):
# fmt: off
__magic_name__ = {'''input_ids''': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=UpperCamelCase_ , model_name='''google/bigbird-pegasus-large-arxiv''' , revision='''ba85d0851d708441f91440d509690f1ab6353415''' , )
@require_sentencepiece
@require_tokenizers
class _lowercase ( __UpperCAmelCase , unittest.TestCase ):
_lowerCamelCase = PegasusTokenizer
_lowerCamelCase = PegasusTokenizerFast
_lowerCamelCase = True
_lowerCamelCase = True
def lowerCAmelCase__ ( self ):
super().setUp()
# We have a SentencePiece fixture for testing
__magic_name__ = PegasusTokenizer(UpperCamelCase_ , offset=0 , mask_token_sent=UpperCamelCase_ , mask_token='''[MASK]''' )
tokenizer.save_pretrained(self.tmpdirname )
@cached_property
def lowerCAmelCase__ ( self ):
return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' )
def lowerCAmelCase__ ( self , **UpperCamelCase_ ):
return PegasusTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase_ )
def lowerCAmelCase__ ( self , UpperCamelCase_ ):
return ("This is a test", "This is a test")
def lowerCAmelCase__ ( self ):
__magic_name__ = self.rust_tokenizer_class.from_pretrained(self.tmpdirname )
__magic_name__ = self.tokenizer_class.from_pretrained(self.tmpdirname )
__magic_name__ = (
'''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>'''
''' <pad> <pad> <pad>'''
)
__magic_name__ = rust_tokenizer([raw_input_str] , return_tensors=UpperCamelCase_ , add_special_tokens=UpperCamelCase_ ).input_ids[0]
__magic_name__ = py_tokenizer([raw_input_str] , return_tensors=UpperCamelCase_ , add_special_tokens=UpperCamelCase_ ).input_ids[0]
self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ )
@require_torch
def lowerCAmelCase__ ( self ):
__magic_name__ = ['''This is going to be way too long.''' * 1000, '''short example''']
__magic_name__ = ['''not super long but more than 5 tokens''', '''tiny''']
__magic_name__ = self._large_tokenizer(UpperCamelCase_ , padding=UpperCamelCase_ , truncation=UpperCamelCase_ , return_tensors='''pt''' )
__magic_name__ = self._large_tokenizer(
text_target=UpperCamelCase_ , max_length=5 , padding=UpperCamelCase_ , truncation=UpperCamelCase_ , return_tensors='''pt''' )
assert batch.input_ids.shape == (2, 4096)
assert batch.attention_mask.shape == (2, 4096)
assert targets["input_ids"].shape == (2, 5)
assert len(UpperCamelCase_ ) == 2 # input_ids, attention_mask.
def lowerCAmelCase__ ( self ):
__magic_name__ = (
'''This is an example string that is used to test the original TF implementation against the HF'''
''' implementation'''
)
__magic_name__ = self._large_tokenizer(UpperCamelCase_ ).input_ids
self.assertListEqual(
UpperCamelCase_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
| 490 | 1 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A =logging.get_logger(__name__)
__A ={
"uclanlp/visualbert-vqa": "https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json",
"uclanlp/visualbert-vqa-pre": "https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json",
"uclanlp/visualbert-vqa-coco-pre": (
"https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json"
),
"uclanlp/visualbert-vcr": "https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json",
"uclanlp/visualbert-vcr-pre": "https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json",
"uclanlp/visualbert-vcr-coco-pre": (
"https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json"
),
"uclanlp/visualbert-nlvr2": "https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json",
"uclanlp/visualbert-nlvr2-pre": "https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json",
"uclanlp/visualbert-nlvr2-coco-pre": (
"https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json"
)
# See all VisualBERT models at https://huggingface.co/models?filter=visual_bert
}
class UpperCAmelCase__ ( __UpperCamelCase ):
'''simple docstring'''
UpperCamelCase = """visual_bert"""
def __init__( self : int , a_ : List[Any]=3_05_22 , a_ : Any=7_68 , a_ : int=5_12 , a_ : Tuple=12 , a_ : str=12 , a_ : int=30_72 , a_ : List[str]="gelu" , a_ : int=0.1 , a_ : Optional[int]=0.1 , a_ : List[Any]=5_12 , a_ : Any=2 , a_ : str=0.0_2 , a_ : List[Any]=1e-12 , a_ : str=False , a_ : Tuple=True , a_ : Union[str, Any]=1 , a_ : str=0 , a_ : List[str]=2 , **a_ : List[str] , ):
'''simple docstring'''
super().__init__(pad_token_id=__UpperCamelCase , bos_token_id=__UpperCamelCase , eos_token_id=__UpperCamelCase , **__UpperCamelCase )
__UpperCAmelCase : Any = vocab_size
__UpperCAmelCase : int = max_position_embeddings
__UpperCAmelCase : Tuple = hidden_size
__UpperCAmelCase : Any = visual_embedding_dim
__UpperCAmelCase : Tuple = num_hidden_layers
__UpperCAmelCase : List[str] = num_attention_heads
__UpperCAmelCase : Any = intermediate_size
__UpperCAmelCase : int = hidden_act
__UpperCAmelCase : Any = hidden_dropout_prob
__UpperCAmelCase : Any = attention_probs_dropout_prob
__UpperCAmelCase : List[Any] = initializer_range
__UpperCAmelCase : Any = type_vocab_size
__UpperCAmelCase : Optional[int] = layer_norm_eps
__UpperCAmelCase : List[Any] = bypass_transformer
__UpperCAmelCase : Tuple = special_visual_initialize
| 707 |
from typing import List, Optional, Tuple, Union
import torch
from ...models import UNetaDModel
from ...schedulers import KarrasVeScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class UpperCAmelCase__ ( __UpperCamelCase ):
'''simple docstring'''
UpperCamelCase = 42
UpperCamelCase = 42
def __init__( self : Optional[int] , a_ : UNetaDModel , a_ : KarrasVeScheduler ):
'''simple docstring'''
super().__init__()
self.register_modules(unet=a_ , scheduler=a_ )
@torch.no_grad()
def __call__( self : Optional[Any] , a_ : int = 1 , a_ : int = 50 , a_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , a_ : Optional[str] = "pil" , a_ : bool = True , **a_ : List[Any] , ):
'''simple docstring'''
__UpperCAmelCase : Any = self.unet.config.sample_size
__UpperCAmelCase : int = (batch_size, 3, img_size, img_size)
__UpperCAmelCase : Optional[Any] = self.unet
# sample x_0 ~ N(0, sigma_0^2 * I)
__UpperCAmelCase : str = randn_tensor(a_ , generator=a_ , device=self.device ) * self.scheduler.init_noise_sigma
self.scheduler.set_timesteps(a_ )
for t in self.progress_bar(self.scheduler.timesteps ):
# here sigma_t == t_i from the paper
__UpperCAmelCase : str = self.scheduler.schedule[t]
__UpperCAmelCase : str = self.scheduler.schedule[t - 1] if t > 0 else 0
# 1. Select temporarily increased noise level sigma_hat
# 2. Add new noise to move from sample_i to sample_hat
__UpperCAmelCase , __UpperCAmelCase : List[str] = self.scheduler.add_noise_to_input(a_ , a_ , generator=a_ )
# 3. Predict the noise residual given the noise magnitude `sigma_hat`
# The model inputs and output are adjusted by following eq. (213) in [1].
__UpperCAmelCase : str = (sigma_hat / 2) * model((sample_hat + 1) / 2 , sigma_hat / 2 ).sample
# 4. Evaluate dx/dt at sigma_hat
# 5. Take Euler step from sigma to sigma_prev
__UpperCAmelCase : Optional[Any] = self.scheduler.step(a_ , a_ , a_ , a_ )
if sigma_prev != 0:
# 6. Apply 2nd order correction
# The model inputs and output are adjusted by following eq. (213) in [1].
__UpperCAmelCase : Tuple = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 , sigma_prev / 2 ).sample
__UpperCAmelCase : Optional[Any] = self.scheduler.step_correct(
a_ , a_ , a_ , a_ , step_output.prev_sample , step_output['''derivative'''] , )
__UpperCAmelCase : List[Any] = step_output.prev_sample
__UpperCAmelCase : str = (sample / 2 + 0.5).clamp(0 , 1 )
__UpperCAmelCase : Optional[int] = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
__UpperCAmelCase : Tuple = self.numpy_to_pil(a_ )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=a_ )
| 241 | 0 |
'''simple docstring'''
def _UpperCAmelCase ( _lowerCamelCase : str , _lowerCamelCase : int ) -> list:
_lowerCAmelCase : Optional[Any] = word.split()
def justify(_lowerCamelCase : list , _lowerCamelCase : int , _lowerCamelCase : int ) -> str:
_lowerCAmelCase : Any = max_width - width
_lowerCAmelCase : Optional[Any] = len(_lowerCamelCase )
if len(_lowerCamelCase ) == 1:
# if there is only word in line
# just insert overall_spaces_count for the remainder of line
return line[0] + " " * overall_spaces_count
else:
_lowerCAmelCase : Any = words_count - 1
# num_spaces_between_words_list[i] : tells you to insert
# num_spaces_between_words_list[i] spaces
# after word on line[i]
_lowerCAmelCase : List[str] = spaces_to_insert_between_words * [
overall_spaces_count // spaces_to_insert_between_words
]
_lowerCAmelCase : Optional[Any] = (
overall_spaces_count % spaces_to_insert_between_words
)
# distribute spaces via round robin to the left words
for i in range(_lowerCamelCase ):
num_spaces_between_words_list[i] += 1
_lowerCAmelCase : Dict = []
for i in range(_lowerCamelCase ):
# add the word
aligned_words_list.append(line[i] )
# add the spaces to insert
aligned_words_list.append(num_spaces_between_words_list[i] * """ """ )
# just add the last word to the sentence
aligned_words_list.append(line[-1] )
# join the aligned words list to form a justified line
return "".join(_lowerCamelCase )
_lowerCAmelCase : str = []
_lowerCAmelCase : list[str] = []
_lowerCAmelCase : str = 0
for word in words:
if width + len(_lowerCamelCase ) + len(_lowerCamelCase ) <= max_width:
# keep adding words until we can fill out max_width
# width = sum of length of all words (without overall_spaces_count)
# len(word) = length of current word
# len(line) = number of overall_spaces_count to insert between words
line.append(_lowerCamelCase )
width += len(_lowerCamelCase )
else:
# justify the line and add it to result
answer.append(justify(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) )
# reset new line and new width
_lowerCAmelCase , _lowerCAmelCase : List[Any] = [word], len(_lowerCamelCase )
_lowerCAmelCase : List[Any] = max_width - width - len(_lowerCamelCase )
answer.append(""" """.join(_lowerCamelCase ) + (remaining_spaces + 1) * """ """ )
return answer
if __name__ == "__main__":
from doctest import testmod
testmod()
| 384 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
UpperCamelCase_ = {"""configuration_mra""": ["""MRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MraConfig"""]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ = [
"""MRA_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""MraForMaskedLM""",
"""MraForMultipleChoice""",
"""MraForQuestionAnswering""",
"""MraForSequenceClassification""",
"""MraForTokenClassification""",
"""MraLayer""",
"""MraModel""",
"""MraPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mra import (
MRA_PRETRAINED_MODEL_ARCHIVE_LIST,
MraForMaskedLM,
MraForMultipleChoice,
MraForQuestionAnswering,
MraForSequenceClassification,
MraForTokenClassification,
MraLayer,
MraModel,
MraPreTrainedModel,
)
else:
import sys
UpperCamelCase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
| 384 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_UpperCAmelCase : List[str] = {"""configuration_wavlm""": ["""WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """WavLMConfig"""]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCAmelCase : List[str] = [
"""WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""WavLMForAudioFrameClassification""",
"""WavLMForCTC""",
"""WavLMForSequenceClassification""",
"""WavLMForXVector""",
"""WavLMModel""",
"""WavLMPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_wavlm import (
WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST,
WavLMForAudioFrameClassification,
WavLMForCTC,
WavLMForSequenceClassification,
WavLMForXVector,
WavLMModel,
WavLMPreTrainedModel,
)
else:
import sys
_UpperCAmelCase : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 108 |
import os
import unittest
from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer
from ...test_tokenization_common import TokenizerTesterMixin
class lowercase ( lowercase_ , unittest.TestCase ):
__SCREAMING_SNAKE_CASE : int = PhobertTokenizer
__SCREAMING_SNAKE_CASE : int = False
def a ( self ):
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
snake_case_ = ['T@@', 'i', 'I', 'R@@', 'r', 'e@@']
snake_case_ = dict(zip(snake_case , range(len(snake_case ) ) ) )
snake_case_ = ['#version: 0.2', 'l à</w>']
snake_case_ = {'unk_token': '<unk>'}
snake_case_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] )
snake_case_ = 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(snake_case ) )
def a ( self , **snake_case ):
kwargs.update(self.special_tokens_map )
return PhobertTokenizer.from_pretrained(self.tmpdirname , **snake_case )
def a ( self , snake_case ):
snake_case_ = 'Tôi là VinAI Research'
snake_case_ = '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 ):
snake_case_ = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
snake_case_ = 'Tôi là VinAI Research'
snake_case_ = 'T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h'.split()
snake_case_ = tokenizer.tokenize(snake_case )
print(snake_case )
self.assertListEqual(snake_case , snake_case )
snake_case_ = tokens + [tokenizer.unk_token]
snake_case_ = [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(snake_case ) , snake_case )
| 108 | 1 |
from __future__ import annotations
import time
from collections.abc import Sequence
from random import randint
from matplotlib import pyplot as plt
def __UpperCamelCase ( lowercase__ : Sequence[float] , lowercase__ : int , lowercase__ : int ) -> tuple[int | None, int | None, float]:
'''simple docstring'''
if not arr:
return None, None, 0
if low == high:
return low, high, arr[low]
lowerCAmelCase_ : Optional[int] = (low + high) // 2
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Any = max_subarray(lowercase__ , lowercase__ , lowercase__ )
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Tuple = max_subarray(lowercase__ , mid + 1 , lowercase__ )
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Optional[Any] = max_cross_sum(lowercase__ , lowercase__ , lowercase__ , lowercase__ )
if left_sum >= right_sum and left_sum >= cross_sum:
return left_low, left_high, left_sum
elif right_sum >= left_sum and right_sum >= cross_sum:
return right_low, right_high, right_sum
return cross_left, cross_right, cross_sum
def __UpperCamelCase ( lowercase__ : Sequence[float] , lowercase__ : int , lowercase__ : int , lowercase__ : int ) -> tuple[int, int, float]:
'''simple docstring'''
lowerCAmelCase_ , lowerCAmelCase_ : str = float("""-inf""" ), -1
lowerCAmelCase_ , lowerCAmelCase_ : Optional[Any] = float("""-inf""" ), -1
lowerCAmelCase_ : int | float = 0
for i in range(lowercase__ , low - 1 , -1 ):
summ += arr[i]
if summ > left_sum:
lowerCAmelCase_ : Optional[Any] = summ
lowerCAmelCase_ : List[Any] = i
lowerCAmelCase_ : Tuple = 0
for i in range(mid + 1 , high + 1 ):
summ += arr[i]
if summ > right_sum:
lowerCAmelCase_ : List[Any] = summ
lowerCAmelCase_ : Optional[Any] = i
return max_left, max_right, (left_sum + right_sum)
def __UpperCamelCase ( lowercase__ : int ) -> float:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = [randint(1 , lowercase__ ) for _ in range(lowercase__ )]
lowerCAmelCase_ : Optional[Any] = time.time()
max_subarray(lowercase__ , 0 , input_size - 1 )
lowerCAmelCase_ : Union[str, Any] = time.time()
return end - start
def __UpperCamelCase ( ) -> None:
'''simple docstring'''
lowerCAmelCase_ : Union[str, Any] = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000]
lowerCAmelCase_ : str = [time_max_subarray(lowercase__ ) for input_size in input_sizes]
print("""No of Inputs\t\tTime Taken""" )
for input_size, runtime in zip(lowercase__ , lowercase__ ):
print(lowercase__ , """\t\t""" , lowercase__ )
plt.plot(lowercase__ , lowercase__ )
plt.xlabel("""Number of Inputs""" )
plt.ylabel("""Time taken in seconds""" )
plt.show()
if __name__ == "__main__":
from doctest import testmod
testmod()
| 600 |
import pprint
import requests
__UpperCAmelCase = 'https://zenquotes.io/api'
def __UpperCamelCase ( ) -> list:
'''simple docstring'''
return requests.get(API_ENDPOINT_URL + """/today""" ).json()
def __UpperCamelCase ( ) -> list:
'''simple docstring'''
return requests.get(API_ENDPOINT_URL + """/random""" ).json()
if __name__ == "__main__":
__UpperCAmelCase = random_quotes()
pprint.pprint(response)
| 600 | 1 |
import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile
import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load
try:
import torch
__SCREAMING_SNAKE_CASE : Optional[Any] = True
except ImportError:
__SCREAMING_SNAKE_CASE : List[str] = False
try:
from torch.hub import _get_torch_home
__SCREAMING_SNAKE_CASE : str = _get_torch_home()
except ImportError:
__SCREAMING_SNAKE_CASE : Any = os.path.expanduser(
os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch'))
)
__SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(torch_cache_home, 'transformers')
__SCREAMING_SNAKE_CASE : Any = 'https://cdn.huggingface.co'
__SCREAMING_SNAKE_CASE : Tuple = 'https://s3.amazonaws.com/models.huggingface.co/bert'
__SCREAMING_SNAKE_CASE : Union[str, Any] = '/'.join(str(Path(__file__).resolve()).split('/')[:-1])
__SCREAMING_SNAKE_CASE : Tuple = os.path.join(PATH, 'config.yaml')
__SCREAMING_SNAKE_CASE : Tuple = os.path.join(PATH, 'attributes.txt')
__SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(PATH, 'objects.txt')
__SCREAMING_SNAKE_CASE : Optional[Any] = os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path)
__SCREAMING_SNAKE_CASE : List[Any] = os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE)
__SCREAMING_SNAKE_CASE : Any = os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE)
__SCREAMING_SNAKE_CASE : Any = 'pytorch_model.bin'
__SCREAMING_SNAKE_CASE : Optional[int] = 'config.yaml'
def snake_case (__lowercase=OBJECTS , __lowercase=ATTRIBUTES ) -> Dict:
'''simple docstring'''
_snake_case : int = []
with open(__lowercase ) as f:
for object in f.readlines():
vg_classes.append(object.split("," )[0].lower().strip() )
_snake_case : int = []
with open(__lowercase ) as f:
for object in f.readlines():
vg_attrs.append(object.split("," )[0].lower().strip() )
return vg_classes, vg_attrs
def snake_case (__lowercase ) -> Any:
'''simple docstring'''
_snake_case : Any = OrderedDict()
with open(__lowercase , "rb" ) as f:
_snake_case : int = pkl.load(__lowercase )["model"]
for k in copy.deepcopy(list(ckp.keys() ) ):
_snake_case : Any = ckp.pop(__lowercase )
if isinstance(__lowercase , np.ndarray ):
_snake_case : Optional[int] = torch.tensor(__lowercase )
else:
assert isinstance(__lowercase , torch.tensor ), type(__lowercase )
_snake_case : Optional[Any] = v
return r
class lowercase_ :
_lowerCamelCase = {}
def __init__( self , lowercase_ , lowercase_ = "root" , lowercase_=0 ):
_snake_case : str = name
_snake_case : Optional[int] = level
_snake_case : List[str] = {}
for k, v in dictionary.items():
if v is None:
raise ValueError()
_snake_case : Tuple = copy.deepcopy(lowercase_ )
_snake_case : Any = copy.deepcopy(lowercase_ )
if isinstance(lowercase_ , lowercase_ ):
_snake_case : Optional[int] = Config(lowercase_ , name=lowercase_ , level=level + 1 )
_snake_case : Dict = v
setattr(self , lowercase_ , lowercase_ )
_snake_case : Any = d
def __repr__( self ):
return str(list((self._pointer.keys()) ) )
def __setattr__( self , lowercase_ , lowercase_ ):
_snake_case : Union[str, Any] = val
_snake_case : str = val
_snake_case : List[str] = key.split("." )
_snake_case : int = len(lowercase_ ) - 1
_snake_case : List[str] = self._pointer
if len(lowercase_ ) > 1:
for i, l in enumerate(lowercase_ ):
if hasattr(self , lowercase_ ) and isinstance(getattr(self , lowercase_ ) , lowercase_ ):
setattr(getattr(self , lowercase_ ) , ".".join(levels[i:] ) , lowercase_ )
if l == last_level:
_snake_case : List[str] = val
else:
_snake_case : int = pointer[l]
def UpperCamelCase ( self ):
return self._pointer
def UpperCamelCase ( self , lowercase_ , lowercase_ ):
with open(f"""{file_name}""" , "w" ) as stream:
dump(lowercase_ , lowercase_ )
def UpperCamelCase ( self , lowercase_ , lowercase_ ):
with open(f"""{file_name}""" , "w" ) as stream:
json.dump(lowercase_ , lowercase_ )
@staticmethod
def UpperCamelCase ( lowercase_ ):
with open(lowercase_ ) as stream:
_snake_case : Any = load(lowercase_ , Loader=lowercase_ )
return data
def __str__( self ):
_snake_case : str = " "
if self._name != "root":
_snake_case : Optional[int] = f"""{t * (self._level-1)}{self._name}:\n"""
else:
_snake_case : str = ""
_snake_case : int = self._level
for i, (k, v) in enumerate(self._pointer.items() ):
if isinstance(lowercase_ , lowercase_ ):
r += f"""{t * (self._level)}{v}\n"""
self._level += 1
else:
r += f"""{t * (self._level)}{k}: {v} ({type(lowercase_ ).__name__})\n"""
_snake_case : str = level
return r[:-1]
@classmethod
def UpperCamelCase ( cls , lowercase_ , **lowercase_ ):
_snake_case : List[Any] = cls.get_config_dict(lowercase_ , **lowercase_ )
return cls(lowercase_ )
@classmethod
def UpperCamelCase ( cls , lowercase_ , **lowercase_ ):
_snake_case : Optional[Any] = kwargs.pop("cache_dir" , lowercase_ )
_snake_case : int = kwargs.pop("force_download" , lowercase_ )
_snake_case : Union[str, Any] = kwargs.pop("resume_download" , lowercase_ )
_snake_case : Any = kwargs.pop("proxies" , lowercase_ )
_snake_case : str = kwargs.pop("local_files_only" , lowercase_ )
if os.path.isdir(lowercase_ ):
_snake_case : Optional[int] = os.path.join(lowercase_ , lowercase_ )
elif os.path.isfile(lowercase_ ) or is_remote_url(lowercase_ ):
_snake_case : Any = pretrained_model_name_or_path
else:
_snake_case : Optional[int] = hf_bucket_url(lowercase_ , filename=lowercase_ , use_cdn=lowercase_ )
try:
# Load from URL or cache if already cached
_snake_case : Optional[Any] = cached_path(
lowercase_ , cache_dir=lowercase_ , force_download=lowercase_ , proxies=lowercase_ , resume_download=lowercase_ , local_files_only=lowercase_ , )
# Load config dict
if resolved_config_file is None:
raise EnvironmentError
_snake_case : Optional[int] = Config.load_yaml(lowercase_ )
except EnvironmentError:
_snake_case : Optional[Any] = "Can't load config for"
raise EnvironmentError(lowercase_ )
if resolved_config_file == config_file:
print("loading configuration file from path" )
else:
print("loading configuration file cache" )
return Config.load_yaml(lowercase_ ), kwargs
def snake_case (__lowercase ) -> List[str]:
'''simple docstring'''
_snake_case : Any = torch.load("dump.pt" , map_location=in_tensor.device )
_snake_case : int = in_tensor.numpy()
_snake_case : Union[str, Any] = out_tensor.numpy()[0]
print(na.shape , na[0, 0, :5] )
print(na.shape , na[0, 0, :5] )
assert np.allclose(__lowercase , __lowercase , rtol=0.01 , atol=0.1 ), (
F"""{sum([1 for x in np.isclose(__lowercase , __lowercase , rtol=0.01 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %"""
" element-wise mismatch"
)
raise Exception("tensors are all good" )
# Hugging face functions below
def snake_case (__lowercase ) -> str:
'''simple docstring'''
_snake_case : List[str] = urlparse(__lowercase )
return parsed.scheme in ("http", "https")
def snake_case (__lowercase , __lowercase , __lowercase=True ) -> str:
'''simple docstring'''
_snake_case : str = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
_snake_case : Optional[Any] = "/" not in model_id
if legacy_format:
return F"""{endpoint}/{model_id}-{filename}"""
else:
return F"""{endpoint}/{model_id}/{filename}"""
def snake_case (__lowercase , __lowercase , __lowercase=None , __lowercase=0 , __lowercase=None , ) -> Optional[int]:
'''simple docstring'''
_snake_case : Dict = "python/{}".format(sys.version.split()[0] )
if _torch_available:
ua += "; torch/{}".format(torch.__version__ )
if isinstance(__lowercase , __lowercase ):
ua += "; " + "; ".join("{}/{}".format(__lowercase , __lowercase ) for k, v in user_agent.items() )
elif isinstance(__lowercase , __lowercase ):
ua += "; " + user_agent
_snake_case : Any = {"user-agent": ua}
if resume_size > 0:
_snake_case : Any = "bytes=%d-" % (resume_size,)
_snake_case : Union[str, Any] = requests.get(__lowercase , stream=__lowercase , proxies=__lowercase , headers=__lowercase )
if response.status_code == 416: # Range not satisfiable
return
_snake_case : str = response.headers.get("Content-Length" )
_snake_case : List[str] = resume_size + int(__lowercase ) if content_length is not None else None
_snake_case : str = tqdm(
unit="B" , unit_scale=__lowercase , total=__lowercase , initial=__lowercase , desc="Downloading" , )
for chunk in response.iter_content(chunk_size=1_024 ):
if chunk: # filter out keep-alive new chunks
progress.update(len(__lowercase ) )
temp_file.write(__lowercase )
progress.close()
def snake_case (__lowercase , __lowercase=None , __lowercase=False , __lowercase=None , __lowercase=10 , __lowercase=False , __lowercase=None , __lowercase=False , ) -> Optional[Any]:
'''simple docstring'''
if cache_dir is None:
_snake_case : int = TRANSFORMERS_CACHE
if isinstance(__lowercase , __lowercase ):
_snake_case : List[str] = str(__lowercase )
os.makedirs(__lowercase , exist_ok=__lowercase )
_snake_case : List[str] = None
if not local_files_only:
try:
_snake_case : Optional[int] = requests.head(__lowercase , allow_redirects=__lowercase , proxies=__lowercase , timeout=__lowercase )
if response.status_code == 200:
_snake_case : Optional[Any] = response.headers.get("ETag" )
except (EnvironmentError, requests.exceptions.Timeout):
# etag is already None
pass
_snake_case : Union[str, Any] = url_to_filename(__lowercase , __lowercase )
# get cache path to put the file
_snake_case : Dict = os.path.join(__lowercase , __lowercase )
# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
# try to get the last downloaded one
if etag is None:
if os.path.exists(__lowercase ):
return cache_path
else:
_snake_case : List[str] = [
file
for file in fnmatch.filter(os.listdir(__lowercase ) , filename + ".*" )
if not file.endswith(".json" ) and not file.endswith(".lock" )
]
if len(__lowercase ) > 0:
return os.path.join(__lowercase , matching_files[-1] )
else:
# If files cannot be found and local_files_only=True,
# the models might've been found if local_files_only=False
# Notify the user about that
if local_files_only:
raise ValueError(
"Cannot find the requested files in the cached path and outgoing traffic has been"
" disabled. To enable model look-ups and downloads online, set 'local_files_only'"
" to False." )
return None
# From now on, etag is not None.
if os.path.exists(__lowercase ) and not force_download:
return cache_path
# Prevent parallel downloads of the same file with a lock.
_snake_case : Dict = cache_path + ".lock"
with FileLock(__lowercase ):
# If the download just completed while the lock was activated.
if os.path.exists(__lowercase ) and not force_download:
# Even if returning early like here, the lock will be released.
return cache_path
if resume_download:
_snake_case : Union[str, Any] = cache_path + ".incomplete"
@contextmanager
def _resumable_file_manager():
with open(__lowercase , "a+b" ) as f:
yield f
_snake_case : Union[str, Any] = _resumable_file_manager
if os.path.exists(__lowercase ):
_snake_case : Optional[Any] = os.stat(__lowercase ).st_size
else:
_snake_case : List[str] = 0
else:
_snake_case : Dict = partial(tempfile.NamedTemporaryFile , dir=__lowercase , delete=__lowercase )
_snake_case : Tuple = 0
# Download to temporary file, then copy to cache dir once finished.
# Otherwise you get corrupt cache entries if the download gets interrupted.
with temp_file_manager() as temp_file:
print(
"%s not found in cache or force_download set to True, downloading to %s" , __lowercase , temp_file.name , )
http_get(
__lowercase , __lowercase , proxies=__lowercase , resume_size=__lowercase , user_agent=__lowercase , )
os.replace(temp_file.name , __lowercase )
_snake_case : Dict = {"url": url, "etag": etag}
_snake_case : Union[str, Any] = cache_path + ".json"
with open(__lowercase , "w" ) as meta_file:
json.dump(__lowercase , __lowercase )
return cache_path
def snake_case (__lowercase , __lowercase=None ) -> List[str]:
'''simple docstring'''
_snake_case : str = url.encode("utf-8" )
_snake_case : Tuple = shaaaa(__lowercase )
_snake_case : Dict = url_hash.hexdigest()
if etag:
_snake_case : Union[str, Any] = etag.encode("utf-8" )
_snake_case : Dict = shaaaa(__lowercase )
filename += "." + etag_hash.hexdigest()
if url.endswith(".h5" ):
filename += ".h5"
return filename
def snake_case (__lowercase , __lowercase=None , __lowercase=False , __lowercase=None , __lowercase=False , __lowercase=None , __lowercase=False , __lowercase=False , __lowercase=False , ) -> str:
'''simple docstring'''
if cache_dir is None:
_snake_case : int = TRANSFORMERS_CACHE
if isinstance(__lowercase , __lowercase ):
_snake_case : Any = str(__lowercase )
if isinstance(__lowercase , __lowercase ):
_snake_case : int = str(__lowercase )
if is_remote_url(__lowercase ):
# URL, so get it from the cache (downloading if necessary)
_snake_case : Dict = get_from_cache(
__lowercase , cache_dir=__lowercase , force_download=__lowercase , proxies=__lowercase , resume_download=__lowercase , user_agent=__lowercase , local_files_only=__lowercase , )
elif os.path.exists(__lowercase ):
# File, and it exists.
_snake_case : Optional[Any] = url_or_filename
elif urlparse(__lowercase ).scheme == "":
# File, but it doesn't exist.
raise EnvironmentError("file {} not found".format(__lowercase ) )
else:
# Something unknown
raise ValueError("unable to parse {} as a URL or as a local path".format(__lowercase ) )
if extract_compressed_file:
if not is_zipfile(__lowercase ) and not tarfile.is_tarfile(__lowercase ):
return output_path
# Path where we extract compressed archives
# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
_snake_case : Optional[Any] = os.path.split(__lowercase )
_snake_case : Tuple = output_file.replace("." , "-" ) + "-extracted"
_snake_case : Optional[int] = os.path.join(__lowercase , __lowercase )
if os.path.isdir(__lowercase ) and os.listdir(__lowercase ) and not force_extract:
return output_path_extracted
# Prevent parallel extractions
_snake_case : Dict = output_path + ".lock"
with FileLock(__lowercase ):
shutil.rmtree(__lowercase , ignore_errors=__lowercase )
os.makedirs(__lowercase )
if is_zipfile(__lowercase ):
with ZipFile(__lowercase , "r" ) as zip_file:
zip_file.extractall(__lowercase )
zip_file.close()
elif tarfile.is_tarfile(__lowercase ):
_snake_case : Dict = tarfile.open(__lowercase )
tar_file.extractall(__lowercase )
tar_file.close()
else:
raise EnvironmentError("Archive format of {} could not be identified".format(__lowercase ) )
return output_path_extracted
return output_path
def snake_case (__lowercase , __lowercase="," ) -> int:
'''simple docstring'''
assert isinstance(__lowercase , __lowercase )
if os.path.isfile(__lowercase ):
with open(__lowercase ) as f:
_snake_case : Tuple = eval(f.read() )
else:
_snake_case : Any = requests.get(__lowercase )
try:
_snake_case : Optional[int] = requests.json()
except Exception:
_snake_case : List[str] = req.content.decode()
assert data is not None, "could not connect"
try:
_snake_case : Tuple = eval(__lowercase )
except Exception:
_snake_case : Dict = data.split("\n" )
req.close()
return data
def snake_case (__lowercase ) -> str:
'''simple docstring'''
_snake_case : Tuple = requests.get(__lowercase )
_snake_case : Optional[Any] = np.array(Image.open(BytesIO(response.content ) ) )
return img
def snake_case (__lowercase ) -> int:
'''simple docstring'''
_snake_case : Tuple = url.split("/" )[-1]
if fn not in os.listdir(os.getcwd() ):
wget.download(__lowercase )
with open(__lowercase , "rb" ) as stream:
_snake_case : Dict = pkl.load(__lowercase )
_snake_case : List[Any] = weights.pop("model" )
_snake_case : Optional[Any] = {}
for k, v in model.items():
_snake_case : Union[str, Any] = torch.from_numpy(__lowercase )
if "running_var" in k:
_snake_case : str = torch.tensor([0] )
_snake_case : Optional[int] = k.replace("running_var" , "num_batches_tracked" )
_snake_case : Optional[Any] = zero
return new
def snake_case () -> Any:
'''simple docstring'''
print(F"""{os.path.abspath(os.path.join(__lowercase , os.pardir ) )}/demo.ipynb""" )
def snake_case (__lowercase , __lowercase="RGB" ) -> str:
'''simple docstring'''
assert isinstance(__lowercase , __lowercase )
if os.path.isfile(__lowercase ):
_snake_case : Optional[int] = cva.imread(__lowercase )
else:
_snake_case : Optional[Any] = get_image_from_url(__lowercase )
assert img is not None, F"""could not connect to: {im}"""
_snake_case : List[Any] = cva.cvtColor(__lowercase , cva.COLOR_BGR2RGB )
if input_format == "RGB":
_snake_case : Optional[int] = img[:, :, ::-1]
return img
def snake_case (__lowercase , __lowercase=1 ) -> Any:
'''simple docstring'''
return (images[i : i + batch] for i in range(0 , len(__lowercase ) , __lowercase )) | 716 | import itertools
import os
import random
import tempfile
import unittest
import numpy as np
from datasets import load_dataset
from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available
from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin
if is_speech_available():
from transformers import WhisperFeatureExtractor
if is_torch_available():
import torch
__SCREAMING_SNAKE_CASE : str = random.Random()
def snake_case (__lowercase , __lowercase=1.0 , __lowercase=None , __lowercase=None ) -> Union[str, Any]:
'''simple docstring'''
if rng is None:
_snake_case : Any = global_rng
_snake_case : Optional[Any] = []
for batch_idx in range(shape[0] ):
values.append([] )
for _ in range(shape[1] ):
values[-1].append(rng.random() * scale )
return values
@require_torch
@require_torchaudio
class lowercase_ ( unittest.TestCase ):
def __init__( self , lowercase_ , lowercase_=7 , lowercase_=400 , lowercase_=2_000 , lowercase_=10 , lowercase_=160 , lowercase_=8 , lowercase_=0.0 , lowercase_=4_000 , lowercase_=False , lowercase_=True , ):
_snake_case : List[Any] = parent
_snake_case : Optional[Any] = batch_size
_snake_case : Optional[Any] = min_seq_length
_snake_case : int = max_seq_length
_snake_case : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
_snake_case : Optional[Any] = padding_value
_snake_case : List[str] = sampling_rate
_snake_case : Any = return_attention_mask
_snake_case : str = do_normalize
_snake_case : Any = feature_size
_snake_case : Optional[int] = chunk_length
_snake_case : Optional[Any] = hop_length
def UpperCamelCase ( self ):
return {
"feature_size": self.feature_size,
"hop_length": self.hop_length,
"chunk_length": self.chunk_length,
"padding_value": self.padding_value,
"sampling_rate": self.sampling_rate,
"return_attention_mask": self.return_attention_mask,
"do_normalize": self.do_normalize,
}
def UpperCamelCase ( self , lowercase_=False , lowercase_=False ):
def _flatten(lowercase_ ):
return list(itertools.chain(*lowercase_ ) )
if equal_length:
_snake_case : Tuple = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )]
else:
# make sure that inputs increase in size
_snake_case : List[str] = [
floats_list((x, self.feature_size) )
for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff )
]
if numpify:
_snake_case : Optional[Any] = [np.asarray(lowercase_ ) for x in speech_inputs]
return speech_inputs
@require_torch
@require_torchaudio
class lowercase_ ( __snake_case , unittest.TestCase ):
_lowerCamelCase = WhisperFeatureExtractor if is_speech_available() else None
def UpperCamelCase ( self ):
_snake_case : int = WhisperFeatureExtractionTester(self )
def UpperCamelCase ( self ):
_snake_case : int = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
_snake_case : int = feat_extract_first.save_pretrained(lowercase_ )[0]
check_json_file_has_correct_format(lowercase_ )
_snake_case : Any = self.feature_extraction_class.from_pretrained(lowercase_ )
_snake_case : str = feat_extract_first.to_dict()
_snake_case : Any = feat_extract_second.to_dict()
_snake_case : List[str] = feat_extract_first.mel_filters
_snake_case : Any = feat_extract_second.mel_filters
self.assertTrue(np.allclose(lowercase_ , lowercase_ ) )
self.assertEqual(lowercase_ , lowercase_ )
def UpperCamelCase ( self ):
_snake_case : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
_snake_case : Dict = os.path.join(lowercase_ , "feat_extract.json" )
feat_extract_first.to_json_file(lowercase_ )
_snake_case : str = self.feature_extraction_class.from_json_file(lowercase_ )
_snake_case : Optional[int] = feat_extract_first.to_dict()
_snake_case : Optional[Any] = feat_extract_second.to_dict()
_snake_case : Optional[int] = feat_extract_first.mel_filters
_snake_case : Optional[int] = feat_extract_second.mel_filters
self.assertTrue(np.allclose(lowercase_ , lowercase_ ) )
self.assertEqual(lowercase_ , lowercase_ )
def UpperCamelCase ( self ):
# Tests that all call wrap to encode_plus and batch_encode_plus
_snake_case : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
# create three inputs of length 800, 1000, and 1200
_snake_case : str = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )]
_snake_case : int = [np.asarray(lowercase_ ) for speech_input in speech_inputs]
# Test feature size
_snake_case : Any = feature_extractor(lowercase_ , padding="max_length" , return_tensors="np" ).input_features
self.assertTrue(input_features.ndim == 3 )
self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames )
self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size )
# Test not batched input
_snake_case : Union[str, Any] = feature_extractor(speech_inputs[0] , return_tensors="np" ).input_features
_snake_case : Tuple = feature_extractor(np_speech_inputs[0] , return_tensors="np" ).input_features
self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1e-3 ) )
# Test batched
_snake_case : int = feature_extractor(lowercase_ , return_tensors="np" ).input_features
_snake_case : Any = feature_extractor(lowercase_ , return_tensors="np" ).input_features
for enc_seq_a, enc_seq_a in zip(lowercase_ , lowercase_ ):
self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1e-3 ) )
# Test 2-D numpy arrays are batched.
_snake_case : Any = [floats_list((1, x) )[0] for x in (800, 800, 800)]
_snake_case : Any = np.asarray(lowercase_ )
_snake_case : Any = feature_extractor(lowercase_ , return_tensors="np" ).input_features
_snake_case : Dict = feature_extractor(lowercase_ , return_tensors="np" ).input_features
for enc_seq_a, enc_seq_a in zip(lowercase_ , lowercase_ ):
self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1e-3 ) )
# Test truncation required
_snake_case : List[str] = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )]
_snake_case : str = [np.asarray(lowercase_ ) for speech_input in speech_inputs]
_snake_case : Tuple = [x[: feature_extractor.n_samples] for x in speech_inputs]
_snake_case : Dict = [np.asarray(lowercase_ ) for speech_input in speech_inputs_truncated]
_snake_case : Tuple = feature_extractor(lowercase_ , return_tensors="np" ).input_features
_snake_case : Optional[Any] = feature_extractor(lowercase_ , return_tensors="np" ).input_features
for enc_seq_a, enc_seq_a in zip(lowercase_ , lowercase_ ):
self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1e-3 ) )
def UpperCamelCase ( self ):
import torch
_snake_case : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
_snake_case : List[Any] = np.random.rand(100 , 32 ).astype(np.floataa )
_snake_case : Optional[Any] = np_speech_inputs.tolist()
for inputs in [py_speech_inputs, np_speech_inputs]:
_snake_case : Dict = feature_extractor.pad([{"input_features": inputs}] , return_tensors="np" )
self.assertTrue(np_processed.input_features.dtype == np.floataa )
_snake_case : int = feature_extractor.pad([{"input_features": inputs}] , return_tensors="pt" )
self.assertTrue(pt_processed.input_features.dtype == torch.floataa )
def UpperCamelCase ( self , lowercase_ ):
_snake_case : int = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" )
# automatic decoding with librispeech
_snake_case : Any = ds.sort("id" ).select(range(lowercase_ ) )[:num_samples]["audio"]
return [x["array"] for x in speech_samples]
def UpperCamelCase ( self ):
# fmt: off
_snake_case : Optional[int] = torch.tensor(
[
0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951,
0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678,
0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554,
-0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854
] )
# fmt: on
_snake_case : Tuple = self._load_datasamples(1 )
_snake_case : Dict = WhisperFeatureExtractor()
_snake_case : int = feature_extractor(lowercase_ , return_tensors="pt" ).input_features
self.assertEqual(input_features.shape , (1, 80, 3_000) )
self.assertTrue(torch.allclose(input_features[0, 0, :30] , lowercase_ , atol=1e-4 ) )
def UpperCamelCase ( self ):
_snake_case : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
_snake_case : Optional[Any] = self._load_datasamples(1 )[0]
_snake_case : Union[str, Any] = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue
_snake_case : List[Any] = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=lowercase_ )[0]
self.assertTrue(np.all(np.mean(lowercase_ ) < 1e-3 ) )
self.assertTrue(np.all(np.abs(np.var(lowercase_ ) - 1 ) < 1e-3 ) ) | 580 | 0 |
"""simple docstring"""
import logging
import os
from typing import List, Tuple
import numpy as np
import psutil
import torch
import torch.distributed as dist
from transformers import RagRetriever
A_ : Dict =logging.getLogger(__name__)
class __a ( lowerCAmelCase__ ):
def __init__( self , a__ , a__ , a__ , a__=None ):
super().__init__(
a__ , question_encoder_tokenizer=a__ , generator_tokenizer=a__ , index=a__ , init_retrieval=a__ , )
_lowerCamelCase = None
def snake_case_ ( self , a__ ):
logger.info('initializing retrieval' )
# initializing a separate process group for retrieval as the default
# nccl backend doesn't support gather/scatter operations while gloo
# is too slow to replace nccl for the core gpu communication
if dist.is_initialized():
logger.info('dist initialized' )
# needs to be set manually
_lowerCamelCase = self._infer_socket_ifname()
# avoid clash with the NCCL port
_lowerCamelCase = str(distributed_port + 1 )
_lowerCamelCase = dist.new_group(ranks=a__ , backend='gloo' )
# initialize retriever only on the main worker
if not dist.is_initialized() or self._is_main():
logger.info('dist not initialized / main' )
self.index.init_index()
# all processes wait untill the retriever is initialized by the main process
if dist.is_initialized():
torch.distributed.barrier(group=self.process_group )
def snake_case_ ( self ):
return dist.get_rank(group=self.process_group ) == 0
def snake_case_ ( self , a__ , a__ , a__=torch.floataa ):
_lowerCamelCase = torch.empty(a__ , dtype=a__ )
dist.scatter(a__ , src=0 , scatter_list=a__ , group=self.process_group )
return target_tensor
def snake_case_ ( self ):
_lowerCamelCase = psutil.net_if_addrs()
# a hacky way to deal with varying network interface names
_lowerCamelCase = next((addr for addr in addrs if addr.startswith('e' )) , a__ )
return ifname
def snake_case_ ( self , a__ , a__ ):
# single GPU training
if not dist.is_initialized():
_lowerCamelCase , _lowerCamelCase = self._main_retrieve(a__ , a__ )
return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(a__ )
# distributed training
_lowerCamelCase = dist.get_world_size(group=self.process_group )
# gather logic
_lowerCamelCase = None
if self._is_main():
_lowerCamelCase = [torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(a__ )]
dist.gather(torch.tensor(a__ ) , dst=0 , gather_list=a__ , group=self.process_group )
# scatter logic
_lowerCamelCase = question_hidden_states.shape[0]
_lowerCamelCase = []
_lowerCamelCase = []
if self._is_main():
assert len(a__ ) == world_size
_lowerCamelCase , _lowerCamelCase = self._main_retrieve(torch.cat(a__ ).numpy() , a__ )
_lowerCamelCase , _lowerCamelCase = torch.tensor(a__ ), torch.tensor(a__ )
_lowerCamelCase = self._chunk_tensor(a__ , a__ )
_lowerCamelCase = self._chunk_tensor(a__ , a__ )
_lowerCamelCase = self._scattered(a__ , [n_queries, n_docs] , target_type=torch.intaa )
_lowerCamelCase = self._scattered(a__ , [n_queries, n_docs, question_hidden_states.shape[1]] )
return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(a__ )
| 650 |
"""simple docstring"""
import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple
from transformers import AddedToken, BatchEncoding, ByTaTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available
from ...test_tokenization_common import TokenizerTesterMixin
if is_torch_available():
A_ : Optional[int] ="""pt"""
elif is_tf_available():
A_ : int ="""tf"""
else:
A_ : Tuple ="""jax"""
class __a ( lowerCAmelCase__ , unittest.TestCase ):
SCREAMING_SNAKE_CASE__ : Dict = ByTaTokenizer
SCREAMING_SNAKE_CASE__ : List[str] = False
def snake_case_ ( self ):
super().setUp()
_lowerCamelCase = ByTaTokenizer()
tokenizer.save_pretrained(self.tmpdirname )
@cached_property
def snake_case_ ( self ):
return ByTaTokenizer.from_pretrained('google/byt5-small' )
def snake_case_ ( self , **a__ ):
return self.tokenizer_class.from_pretrained(self.tmpdirname , **a__ )
def snake_case_ ( self , a__ , a__=False , a__=20 , a__=5 ):
# XXX The default common tokenizer tests assume that every ID is decodable on its own.
# This assumption is invalid for ByT5 because single bytes might not be
# valid utf-8 (byte 128 for instance).
# Here we're overriding the smallest possible method to provide
# a clean sequence without making the same assumption.
_lowerCamelCase = []
for i in range(len(a__ ) ):
try:
_lowerCamelCase = tokenizer.decode([i] , clean_up_tokenization_spaces=a__ )
except UnicodeDecodeError:
pass
toks.append((i, tok) )
_lowerCamelCase = list(filter(lambda a__ : re.match(r'^[ a-zA-Z]+$' , t[1] ) , a__ ) )
_lowerCamelCase = list(filter(lambda a__ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=a__ ) , a__ ) )
if max_length is not None and len(a__ ) > max_length:
_lowerCamelCase = toks[:max_length]
if min_length is not None and len(a__ ) < min_length and len(a__ ) > 0:
while len(a__ ) < min_length:
_lowerCamelCase = toks + toks
# toks_str = [t[1] for t in toks]
_lowerCamelCase = [t[0] for t in toks]
# Ensure consistency
_lowerCamelCase = tokenizer.decode(a__ , clean_up_tokenization_spaces=a__ )
if " " not in output_txt and len(a__ ) > 1:
_lowerCamelCase = (
tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=a__ )
+ ' '
+ tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=a__ )
)
if with_prefix_space:
_lowerCamelCase = ' ' + output_txt
_lowerCamelCase = tokenizer.encode(a__ , add_special_tokens=a__ )
return output_txt, output_ids
def snake_case_ ( self ):
_lowerCamelCase = self.ta_base_tokenizer
_lowerCamelCase = tokenizer(['hi</s>', 'I went to the gym</s>', '</s>'] )
_lowerCamelCase = tokenizer(['hi', 'I went to the gym', ''] )
self.assertListEqual(batch_with_eos_added['input_ids'] , batch_without_eos_added['input_ids'] )
def snake_case_ ( self ):
_lowerCamelCase = self.ta_base_tokenizer
_lowerCamelCase = 'Unicode €.'
_lowerCamelCase = tokenizer(a__ )
_lowerCamelCase = [88, 1_13, 1_08, 1_02, 1_14, 1_03, 1_04, 35, 2_29, 1_33, 1_75, 49, 1]
self.assertEqual(encoded['input_ids'] , a__ )
# decoding
_lowerCamelCase = tokenizer.decode(a__ )
self.assertEqual(a__ , 'Unicode €.</s>' )
_lowerCamelCase = tokenizer('e è é ê ë' )
_lowerCamelCase = [1_04, 35, 1_98, 1_71, 35, 1_98, 1_72, 35, 1_98, 1_73, 35, 1_98, 1_74, 1]
self.assertEqual(encoded['input_ids'] , a__ )
# decoding
_lowerCamelCase = tokenizer.decode(a__ )
self.assertEqual(a__ , 'e è é ê ë</s>' )
# encode/decode, but with `encode` instead of `__call__`
self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ) , 'e è é ê ë</s>' )
def snake_case_ ( self ):
_lowerCamelCase = self.ta_base_tokenizer
_lowerCamelCase = ['A long paragraph for summarization.', 'Another paragraph for summarization.']
# fmt: off
_lowerCamelCase = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 1, 0]
# fmt: on
_lowerCamelCase = tokenizer(a__ , padding=a__ , return_tensors=a__ )
self.assertIsInstance(a__ , a__ )
if FRAMEWORK != "jax":
_lowerCamelCase = list(batch.input_ids.numpy()[0] )
else:
_lowerCamelCase = list(batch.input_ids.tolist()[0] )
self.assertListEqual(a__ , a__ )
self.assertEqual((2, 37) , batch.input_ids.shape )
self.assertEqual((2, 37) , batch.attention_mask.shape )
def snake_case_ ( self ):
_lowerCamelCase = self.ta_base_tokenizer
_lowerCamelCase = ['A long paragraph for summarization.', 'Another paragraph for summarization.']
_lowerCamelCase = tokenizer(a__ , padding=a__ , return_tensors=a__ )
# check if input_ids are returned and no decoder_input_ids
self.assertIn('input_ids' , a__ )
self.assertIn('attention_mask' , a__ )
self.assertNotIn('decoder_input_ids' , a__ )
self.assertNotIn('decoder_attention_mask' , a__ )
def snake_case_ ( self ):
_lowerCamelCase = self.ta_base_tokenizer
_lowerCamelCase = [
'Summary of the text.',
'Another summary.',
]
_lowerCamelCase = tokenizer(
text_target=a__ , max_length=32 , padding='max_length' , truncation=a__ , return_tensors=a__ )
self.assertEqual(32 , targets['input_ids'].shape[1] )
def snake_case_ ( self ):
_lowerCamelCase = self.ta_base_tokenizer
_lowerCamelCase = ['A long paragraph for summarization. </s>']
_lowerCamelCase = ['Summary of the text. </s>']
# fmt: off
_lowerCamelCase = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 35, 1]
_lowerCamelCase = [86, 1_20, 1_12, 1_12, 1_00, 1_17, 1_24, 35, 1_14, 1_05, 35, 1_19, 1_07, 1_04, 35, 1_19, 1_04, 1_23, 1_19, 49, 35, 1]
# fmt: on
_lowerCamelCase = tokenizer(a__ , text_target=a__ )
self.assertEqual(a__ , batch['input_ids'][0] )
self.assertEqual(a__ , batch['labels'][0] )
def snake_case_ ( self ):
# safety check on max_len default value so we are sure the test works
_lowerCamelCase = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F'{tokenizer.__class__.__name__}' ):
self.assertNotEqual(tokenizer.model_max_length , 42 )
# Now let's start the test
_lowerCamelCase = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F'{tokenizer.__class__.__name__}' ):
# Isolate this from the other tests because we save additional tokens/etc
_lowerCamelCase = tempfile.mkdtemp()
_lowerCamelCase = ' He is very happy, UNwant\u00E9d,running'
_lowerCamelCase = tokenizer.encode(a__ , add_special_tokens=a__ )
tokenizer.save_pretrained(a__ )
_lowerCamelCase = tokenizer.__class__.from_pretrained(a__ )
_lowerCamelCase = after_tokenizer.encode(a__ , add_special_tokens=a__ )
self.assertListEqual(a__ , a__ )
shutil.rmtree(a__ )
_lowerCamelCase = self.get_tokenizers(model_max_length=42 )
for tokenizer in tokenizers:
with self.subTest(F'{tokenizer.__class__.__name__}' ):
# Isolate this from the other tests because we save additional tokens/etc
_lowerCamelCase = tempfile.mkdtemp()
_lowerCamelCase = ' He is very happy, UNwant\u00E9d,running'
tokenizer.add_tokens(['bim', 'bambam'] )
_lowerCamelCase = tokenizer.additional_special_tokens
additional_special_tokens.append('new_additional_special_token' )
tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} )
_lowerCamelCase = tokenizer.encode(a__ , add_special_tokens=a__ )
tokenizer.save_pretrained(a__ )
_lowerCamelCase = tokenizer.__class__.from_pretrained(a__ )
_lowerCamelCase = after_tokenizer.encode(a__ , add_special_tokens=a__ )
self.assertListEqual(a__ , a__ )
self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens )
self.assertEqual(after_tokenizer.model_max_length , 42 )
_lowerCamelCase = tokenizer.__class__.from_pretrained(a__ , model_max_length=43 )
self.assertEqual(tokenizer.model_max_length , 43 )
shutil.rmtree(a__ )
def snake_case_ ( self ):
_lowerCamelCase = []
if self.test_slow_tokenizer:
tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) )
if self.test_rust_tokenizer:
tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) )
for tokenizer_class, tokenizer_utils in tokenizer_list:
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer_utils.save_pretrained(a__ )
with open(os.path.join(a__ , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file:
_lowerCamelCase = json.load(a__ )
with open(os.path.join(a__ , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file:
_lowerCamelCase = json.load(a__ )
_lowerCamelCase = [F'<extra_id_{i}>' for i in range(1_25 )]
_lowerCamelCase = added_tokens_extra_ids + [
'an_additional_special_token'
]
_lowerCamelCase = added_tokens_extra_ids + [
'an_additional_special_token'
]
with open(os.path.join(a__ , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile:
json.dump(a__ , a__ )
with open(os.path.join(a__ , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile:
json.dump(a__ , a__ )
# the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
# into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
# "special_tokens_map.json" files
_lowerCamelCase = tokenizer_class.from_pretrained(
a__ , )
self.assertIn(
'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens )
# self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab
self.assertEqual(
['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens(
tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ) , )
# Now we test that we can change the value of additional_special_tokens in the from_pretrained
_lowerCamelCase = added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=a__ )]
_lowerCamelCase = tokenizer_class.from_pretrained(
a__ , additional_special_tokens=a__ , )
self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens )
self.assertEqual(
['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens(
tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ) , )
def snake_case_ ( self ):
_lowerCamelCase = []
if self.test_slow_tokenizer:
tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) )
if self.test_rust_tokenizer:
tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) )
for tokenizer_class, tokenizer_utils in tokenizer_list:
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer_utils.save_pretrained(a__ )
_lowerCamelCase = tokenizer_class.from_pretrained(a__ )
self.assertTrue(tokenizer.decode([2_55] ) == '' )
def snake_case_ ( self ):
pass
def snake_case_ ( self ):
pass
def snake_case_ ( self ):
pass
def snake_case_ ( self ):
pass
def snake_case_ ( self ):
# The default common tokenizer tests uses invalid tokens for ByT5 that can only accept one-character strings
# and special added tokens as tokens
_lowerCamelCase = self.get_tokenizers(fast=a__ , do_lower_case=a__ )
for tokenizer in tokenizers:
with self.subTest(F'{tokenizer.__class__.__name__}' ):
_lowerCamelCase = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>']
_lowerCamelCase = tokenizer.convert_tokens_to_string(a__ )
self.assertIsInstance(a__ , a__ )
def snake_case_ ( self ):
_lowerCamelCase = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F'{tokenizer.__class__.__name__}' ):
_lowerCamelCase = [
'bos_token',
'eos_token',
'unk_token',
'sep_token',
'pad_token',
'cls_token',
'mask_token',
]
_lowerCamelCase = 0
_lowerCamelCase = tokenizer.convert_ids_to_tokens(
a__ , skip_special_tokens=a__ )
for attr in attributes_list:
setattr(a__ , attr + '_id' , a__ )
self.assertEqual(getattr(a__ , a__ ) , a__ )
self.assertEqual(getattr(a__ , attr + '_id' ) , a__ )
setattr(a__ , attr + '_id' , a__ )
self.assertEqual(getattr(a__ , a__ ) , a__ )
self.assertEqual(getattr(a__ , attr + '_id' ) , a__ )
setattr(a__ , 'additional_special_tokens_ids' , [] )
self.assertListEqual(getattr(a__ , 'additional_special_tokens' ) , [] )
self.assertListEqual(getattr(a__ , 'additional_special_tokens_ids' ) , [] )
setattr(a__ , 'additional_special_tokens_ids' , [token_id_to_test_setters] )
self.assertListEqual(getattr(a__ , 'additional_special_tokens' ) , [token_to_test_setters] )
self.assertListEqual(getattr(a__ , 'additional_special_tokens_ids' ) , [token_id_to_test_setters] )
| 650 | 1 |
from __future__ import annotations
from typing import Any
class a__ ( UpperCamelCase_ ):
pass
class a__ :
def __init__( self : Union[str, Any] , A_ : Any ) -> Union[str, Any]:
"""simple docstring"""
lowerCamelCase_: Any = data
lowerCamelCase_: Node | None = None
def __iter__( self : Any ) -> int:
"""simple docstring"""
lowerCamelCase_: List[str] = self
lowerCamelCase_: Tuple = []
while node:
if node in visited:
raise ContainsLoopError
visited.append(UpperCamelCase__ )
yield node.data
lowerCamelCase_: Dict = node.next_node
@property
def lowerCAmelCase ( self : Optional[int] ) -> Union[str, Any]:
"""simple docstring"""
try:
list(self )
return False
except ContainsLoopError:
return True
if __name__ == "__main__":
lowercase : List[Any] = Node(1)
lowercase : str = Node(2)
lowercase : Dict = Node(3)
lowercase : List[Any] = Node(4)
print(root_node.has_loop) # False
lowercase : int = root_node.next_node
print(root_node.has_loop) # True
lowercase : Union[str, Any] = Node(5)
lowercase : Union[str, Any] = Node(6)
lowercase : List[Any] = Node(5)
lowercase : List[str] = Node(6)
print(root_node.has_loop) # False
lowercase : List[Any] = Node(1)
print(root_node.has_loop) # False
| 712 | from collections import defaultdict
from math import ceil, sqrt
def UpperCAmelCase_ ( _UpperCAmelCase = 1_0_0_0_0_0_0 , _UpperCAmelCase = 1_0 ):
lowerCamelCase_: defaultdict = defaultdict(_UpperCAmelCase )
for outer_width in range(3 , (t_limit // 4) + 2 ):
if outer_width * outer_width > t_limit:
lowerCamelCase_: Dict = max(
ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 )
else:
lowerCamelCase_: List[str] = 1
hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2
for hole_width in range(_UpperCAmelCase , outer_width - 1 , 2 ):
count[outer_width * outer_width - hole_width * hole_width] += 1
return sum(1 for n in count.values() if 1 <= n <= 1_0 )
if __name__ == "__main__":
print(F"{solution() = }")
| 584 | 0 |
import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union
# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...feature_extraction_utils import FeatureExtractionMixin
from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
CONFIG_MAPPING_NAMES,
AutoConfig,
model_type_to_module_name,
replace_list_option_in_docstrings,
)
lowerCAmelCase_ = logging.get_logger(__name__)
lowerCAmelCase_ = OrderedDict(
[
('''audio-spectrogram-transformer''', '''ASTFeatureExtractor'''),
('''beit''', '''BeitFeatureExtractor'''),
('''chinese_clip''', '''ChineseCLIPFeatureExtractor'''),
('''clap''', '''ClapFeatureExtractor'''),
('''clip''', '''CLIPFeatureExtractor'''),
('''clipseg''', '''ViTFeatureExtractor'''),
('''conditional_detr''', '''ConditionalDetrFeatureExtractor'''),
('''convnext''', '''ConvNextFeatureExtractor'''),
('''cvt''', '''ConvNextFeatureExtractor'''),
('''data2vec-audio''', '''Wav2Vec2FeatureExtractor'''),
('''data2vec-vision''', '''BeitFeatureExtractor'''),
('''deformable_detr''', '''DeformableDetrFeatureExtractor'''),
('''deit''', '''DeiTFeatureExtractor'''),
('''detr''', '''DetrFeatureExtractor'''),
('''dinat''', '''ViTFeatureExtractor'''),
('''donut-swin''', '''DonutFeatureExtractor'''),
('''dpt''', '''DPTFeatureExtractor'''),
('''encodec''', '''EncodecFeatureExtractor'''),
('''flava''', '''FlavaFeatureExtractor'''),
('''glpn''', '''GLPNFeatureExtractor'''),
('''groupvit''', '''CLIPFeatureExtractor'''),
('''hubert''', '''Wav2Vec2FeatureExtractor'''),
('''imagegpt''', '''ImageGPTFeatureExtractor'''),
('''layoutlmv2''', '''LayoutLMv2FeatureExtractor'''),
('''layoutlmv3''', '''LayoutLMv3FeatureExtractor'''),
('''levit''', '''LevitFeatureExtractor'''),
('''maskformer''', '''MaskFormerFeatureExtractor'''),
('''mctct''', '''MCTCTFeatureExtractor'''),
('''mobilenet_v1''', '''MobileNetV1FeatureExtractor'''),
('''mobilenet_v2''', '''MobileNetV2FeatureExtractor'''),
('''mobilevit''', '''MobileViTFeatureExtractor'''),
('''nat''', '''ViTFeatureExtractor'''),
('''owlvit''', '''OwlViTFeatureExtractor'''),
('''perceiver''', '''PerceiverFeatureExtractor'''),
('''poolformer''', '''PoolFormerFeatureExtractor'''),
('''regnet''', '''ConvNextFeatureExtractor'''),
('''resnet''', '''ConvNextFeatureExtractor'''),
('''segformer''', '''SegformerFeatureExtractor'''),
('''sew''', '''Wav2Vec2FeatureExtractor'''),
('''sew-d''', '''Wav2Vec2FeatureExtractor'''),
('''speech_to_text''', '''Speech2TextFeatureExtractor'''),
('''speecht5''', '''SpeechT5FeatureExtractor'''),
('''swiftformer''', '''ViTFeatureExtractor'''),
('''swin''', '''ViTFeatureExtractor'''),
('''swinv2''', '''ViTFeatureExtractor'''),
('''table-transformer''', '''DetrFeatureExtractor'''),
('''timesformer''', '''VideoMAEFeatureExtractor'''),
('''tvlt''', '''TvltFeatureExtractor'''),
('''unispeech''', '''Wav2Vec2FeatureExtractor'''),
('''unispeech-sat''', '''Wav2Vec2FeatureExtractor'''),
('''van''', '''ConvNextFeatureExtractor'''),
('''videomae''', '''VideoMAEFeatureExtractor'''),
('''vilt''', '''ViltFeatureExtractor'''),
('''vit''', '''ViTFeatureExtractor'''),
('''vit_mae''', '''ViTFeatureExtractor'''),
('''vit_msn''', '''ViTFeatureExtractor'''),
('''wav2vec2''', '''Wav2Vec2FeatureExtractor'''),
('''wav2vec2-conformer''', '''Wav2Vec2FeatureExtractor'''),
('''wavlm''', '''Wav2Vec2FeatureExtractor'''),
('''whisper''', '''WhisperFeatureExtractor'''),
('''xclip''', '''CLIPFeatureExtractor'''),
('''yolos''', '''YolosFeatureExtractor'''),
]
)
lowerCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ):
for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
if class_name in extractors:
snake_case_ = model_type_to_module_name(SCREAMING_SNAKE_CASE__ )
snake_case_ = importlib.import_module(F'''.{module_name}''' , '''transformers.models''' )
try:
return getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
except AttributeError:
continue
for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
if getattr(SCREAMING_SNAKE_CASE__ , '''__name__''' , SCREAMING_SNAKE_CASE__ ) == class_name:
return extractor
# We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
# init and we return the proper dummy to get an appropriate error message.
snake_case_ = importlib.import_module('''transformers''' )
if hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
return getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
return None
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , **SCREAMING_SNAKE_CASE__ , ):
snake_case_ = get_file_from_repo(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ , resume_download=SCREAMING_SNAKE_CASE__ , proxies=SCREAMING_SNAKE_CASE__ , use_auth_token=SCREAMING_SNAKE_CASE__ , revision=SCREAMING_SNAKE_CASE__ , local_files_only=SCREAMING_SNAKE_CASE__ , )
if resolved_config_file is None:
logger.info(
'''Could not locate the feature extractor configuration file, will try to use the model config instead.''' )
return {}
with open(SCREAMING_SNAKE_CASE__ , encoding='''utf-8''' ) as reader:
return json.load(SCREAMING_SNAKE_CASE__ )
class snake_case_ :
'''simple docstring'''
def __init__( self : str ) ->Optional[int]:
raise EnvironmentError(
'''AutoFeatureExtractor is designed to be instantiated '''
'''using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.''' )
@classmethod
@replace_list_option_in_docstrings(_UpperCamelCase )
def snake_case__( cls : str , _UpperCamelCase : List[Any] , **_UpperCamelCase : Optional[int] ) ->List[str]:
snake_case_ = kwargs.pop('''config''' , _UpperCamelCase )
snake_case_ = kwargs.pop('''trust_remote_code''' , _UpperCamelCase )
snake_case_ = True
snake_case_, snake_case_ = FeatureExtractionMixin.get_feature_extractor_dict(_UpperCamelCase , **_UpperCamelCase )
snake_case_ = config_dict.get('''feature_extractor_type''' , _UpperCamelCase )
snake_case_ = None
if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ):
snake_case_ = config_dict['''auto_map''']['''AutoFeatureExtractor''']
# If we don't find the feature extractor class in the feature extractor config, let's try the model config.
if feature_extractor_class is None and feature_extractor_auto_map is None:
if not isinstance(_UpperCamelCase , _UpperCamelCase ):
snake_case_ = AutoConfig.from_pretrained(_UpperCamelCase , **_UpperCamelCase )
# It could be in `config.feature_extractor_type``
snake_case_ = getattr(_UpperCamelCase , '''feature_extractor_type''' , _UpperCamelCase )
if hasattr(_UpperCamelCase , '''auto_map''' ) and "AutoFeatureExtractor" in config.auto_map:
snake_case_ = config.auto_map['''AutoFeatureExtractor''']
if feature_extractor_class is not None:
snake_case_ = feature_extractor_class_from_name(_UpperCamelCase )
snake_case_ = feature_extractor_auto_map is not None
snake_case_ = feature_extractor_class is not None or type(_UpperCamelCase ) in FEATURE_EXTRACTOR_MAPPING
snake_case_ = resolve_trust_remote_code(
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase )
if has_remote_code and trust_remote_code:
snake_case_ = get_class_from_dynamic_module(
_UpperCamelCase , _UpperCamelCase , **_UpperCamelCase )
snake_case_ = kwargs.pop('''code_revision''' , _UpperCamelCase )
if os.path.isdir(_UpperCamelCase ):
feature_extractor_class.register_for_auto_class()
return feature_extractor_class.from_dict(_UpperCamelCase , **_UpperCamelCase )
elif feature_extractor_class is not None:
return feature_extractor_class.from_dict(_UpperCamelCase , **_UpperCamelCase )
# Last try: we use the FEATURE_EXTRACTOR_MAPPING.
elif type(_UpperCamelCase ) in FEATURE_EXTRACTOR_MAPPING:
snake_case_ = FEATURE_EXTRACTOR_MAPPING[type(_UpperCamelCase )]
return feature_extractor_class.from_dict(_UpperCamelCase , **_UpperCamelCase )
raise ValueError(
f'''Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a '''
f'''`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following '''
f'''`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}''' )
@staticmethod
def snake_case__( _UpperCamelCase : Optional[int] , _UpperCamelCase : Optional[int] ) ->Dict:
FEATURE_EXTRACTOR_MAPPING.register(_UpperCamelCase , _UpperCamelCase ) | 39 |
'''simple docstring'''
import tempfile
import torch
from diffusers import IPNDMScheduler
from .test_schedulers import SchedulerCommonTest
class lowerCamelCase ( lowercase_ ):
'''simple docstring'''
__snake_case = (IPNDMScheduler,)
__snake_case = (('num_inference_steps', 50),)
def lowercase__ ( self : List[Any] , **lowerCAmelCase_ : int ) -> Tuple:
'''simple docstring'''
A__ : int ={"""num_train_timesteps""": 10_00}
config.update(**lowerCAmelCase_ )
return config
def lowercase__ ( self : Dict , lowerCAmelCase_ : Dict=0 , **lowerCAmelCase_ : Optional[Any] ) -> Dict:
'''simple docstring'''
A__ : str =dict(self.forward_default_kwargs )
A__ : List[str] =kwargs.pop("""num_inference_steps""" , lowerCAmelCase_ )
A__ : List[Any] =self.dummy_sample
A__ : Optional[int] =0.1 * sample
A__ : Optional[Any] =[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
for scheduler_class in self.scheduler_classes:
A__ : Tuple =self.get_scheduler_config(**lowerCAmelCase_ )
A__ : int =scheduler_class(**lowerCAmelCase_ )
scheduler.set_timesteps(lowerCAmelCase_ )
# copy over dummy past residuals
A__ : int =dummy_past_residuals[:]
if time_step is None:
A__ : List[Any] =scheduler.timesteps[len(scheduler.timesteps ) // 2]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(lowerCAmelCase_ )
A__ : Union[str, Any] =scheduler_class.from_pretrained(lowerCAmelCase_ )
new_scheduler.set_timesteps(lowerCAmelCase_ )
# copy over dummy past residuals
A__ : Dict =dummy_past_residuals[:]
A__ : Dict =scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample
A__ : int =new_scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
A__ : Optional[Any] =scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample
A__ : Union[str, Any] =new_scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def lowercase__ ( self : Union[str, Any] ) -> Optional[int]:
'''simple docstring'''
pass
def lowercase__ ( self : Any , lowerCAmelCase_ : List[str]=0 , **lowerCAmelCase_ : int ) -> int:
'''simple docstring'''
A__ : Any =dict(self.forward_default_kwargs )
A__ : int =kwargs.pop("""num_inference_steps""" , lowerCAmelCase_ )
A__ : Tuple =self.dummy_sample
A__ : Dict =0.1 * sample
A__ : List[Any] =[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
for scheduler_class in self.scheduler_classes:
A__ : Dict =self.get_scheduler_config()
A__ : Optional[int] =scheduler_class(**lowerCAmelCase_ )
scheduler.set_timesteps(lowerCAmelCase_ )
# copy over dummy past residuals (must be after setting timesteps)
A__ : str =dummy_past_residuals[:]
if time_step is None:
A__ : str =scheduler.timesteps[len(scheduler.timesteps ) // 2]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(lowerCAmelCase_ )
A__ : int =scheduler_class.from_pretrained(lowerCAmelCase_ )
# copy over dummy past residuals
new_scheduler.set_timesteps(lowerCAmelCase_ )
# copy over dummy past residual (must be after setting timesteps)
A__ : Optional[int] =dummy_past_residuals[:]
A__ : Any =scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample
A__ : Union[str, Any] =new_scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
A__ : Optional[int] =scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample
A__ : Optional[Any] =new_scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def lowercase__ ( self : Optional[Any] , **lowerCAmelCase_ : Tuple ) -> Any:
'''simple docstring'''
A__ : Union[str, Any] =self.scheduler_classes[0]
A__ : List[str] =self.get_scheduler_config(**lowerCAmelCase_ )
A__ : Optional[Any] =scheduler_class(**lowerCAmelCase_ )
A__ : Optional[int] =10
A__ : Tuple =self.dummy_model()
A__ : str =self.dummy_sample_deter
scheduler.set_timesteps(lowerCAmelCase_ )
for i, t in enumerate(scheduler.timesteps ):
A__ : List[str] =model(lowerCAmelCase_ , lowerCAmelCase_ )
A__ : List[Any] =scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ).prev_sample
for i, t in enumerate(scheduler.timesteps ):
A__ : int =model(lowerCAmelCase_ , lowerCAmelCase_ )
A__ : List[str] =scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ).prev_sample
return sample
def lowercase__ ( self : int ) -> Tuple:
'''simple docstring'''
A__ : Union[str, Any] =dict(self.forward_default_kwargs )
A__ : Any =kwargs.pop("""num_inference_steps""" , lowerCAmelCase_ )
for scheduler_class in self.scheduler_classes:
A__ : Optional[int] =self.get_scheduler_config()
A__ : Dict =scheduler_class(**lowerCAmelCase_ )
A__ : str =self.dummy_sample
A__ : int =0.1 * sample
if num_inference_steps is not None and hasattr(lowerCAmelCase_ , """set_timesteps""" ):
scheduler.set_timesteps(lowerCAmelCase_ )
elif num_inference_steps is not None and not hasattr(lowerCAmelCase_ , """set_timesteps""" ):
A__ : Optional[Any] =num_inference_steps
# copy over dummy past residuals (must be done after set_timesteps)
A__ : Tuple =[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
A__ : Optional[int] =dummy_past_residuals[:]
A__ : Dict =scheduler.timesteps[5]
A__ : str =scheduler.timesteps[6]
A__ : Dict =scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample
A__ : Dict =scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample
self.assertEqual(output_a.shape , sample.shape )
self.assertEqual(output_a.shape , output_a.shape )
A__ : Any =scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample
A__ : int =scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ).prev_sample
self.assertEqual(output_a.shape , sample.shape )
self.assertEqual(output_a.shape , output_a.shape )
def lowercase__ ( self : Any ) -> str:
'''simple docstring'''
for timesteps in [1_00, 10_00]:
self.check_over_configs(num_train_timesteps=lowerCAmelCase_ , time_step=lowerCAmelCase_ )
def lowercase__ ( self : str ) -> List[Any]:
'''simple docstring'''
for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 1_00] ):
self.check_over_forward(num_inference_steps=lowerCAmelCase_ , time_step=lowerCAmelCase_ )
def lowercase__ ( self : Union[str, Any] ) -> List[Any]:
'''simple docstring'''
A__ : List[str] =self.full_loop()
A__ : str =torch.mean(torch.abs(lowerCAmelCase_ ) )
assert abs(result_mean.item() - 2_54_05_29 ) < 10
| 215 | 0 |
"""simple docstring"""
from __future__ import annotations
def __A ( a_ : list )-> float:
'''simple docstring'''
if not nums:
raise ValueError('''List is empty''' )
return sum(a_ ) / len(a_ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 18 |
"""simple docstring"""
import math
class lowercase__:
'''simple docstring'''
def __init__( self :Union[str, Any] , lowerCamelCase_ :List[str]=0 ) -> List[Any]: # a graph with Node 0,1,...,N-1
'''simple docstring'''
SCREAMING_SNAKE_CASE : Tuple = n
SCREAMING_SNAKE_CASE : List[Any] = [
[math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ )
] # adjacency matrix for weight
SCREAMING_SNAKE_CASE : Any = [
[math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ )
] # dp[i][j] stores minimum distance from i to j
def __lowerCAmelCase ( self :Dict , lowerCamelCase_ :Optional[int] , lowerCamelCase_ :Union[str, Any] , lowerCamelCase_ :Union[str, Any] ) -> Tuple:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[Any] = w
def __lowerCAmelCase ( self :str ) -> Union[str, Any]:
'''simple docstring'''
for k in range(0 , self.n ):
for i in range(0 , self.n ):
for j in range(0 , self.n ):
SCREAMING_SNAKE_CASE : List[str] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] )
def __lowerCAmelCase ( self :int , lowerCamelCase_ :Union[str, Any] , lowerCamelCase_ :Optional[int] ) -> Optional[Any]:
'''simple docstring'''
return self.dp[u][v]
if __name__ == "__main__":
lowerCamelCase__ : Dict = Graph(5)
graph.add_edge(0, 2, 9)
graph.add_edge(0, 4, 10)
graph.add_edge(1, 3, 5)
graph.add_edge(2, 3, 7)
graph.add_edge(3, 0, 10)
graph.add_edge(3, 1, 2)
graph.add_edge(3, 2, 1)
graph.add_edge(3, 4, 6)
graph.add_edge(4, 1, 3)
graph.add_edge(4, 2, 4)
graph.add_edge(4, 3, 9)
graph.floyd_warshall()
graph.show_min(1, 4)
graph.show_min(0, 3)
| 18 | 1 |
from collections.abc import Generator
def lowerCamelCase__ ( ):
SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Dict = 0, 1
while True:
SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[Any] = b, a + b
yield b
def lowerCamelCase__ ( _a = 1000):
SCREAMING_SNAKE_CASE : Union[str, Any] = 1
SCREAMING_SNAKE_CASE : int = fibonacci_generator()
while len(str(next(_a))) < n:
answer += 1
return answer + 1
if __name__ == "__main__":
print(solution(int(str(input()).strip()))) | 25 |
from collections import defaultdict
from math import ceil, sqrt
def lowerCAmelCase_ ( _snake_case : int = 1000000 , _snake_case : int = 10 ) -> int:
'''simple docstring'''
__magic_name__ : defaultdict = defaultdict(_snake_case )
for outer_width in range(3 , (t_limit // 4) + 2 ):
if outer_width * outer_width > t_limit:
__magic_name__ : Optional[int] = max(
ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 )
else:
__magic_name__ : Optional[int] = 1
hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2
for hole_width in range(_snake_case , outer_width - 1 , 2 ):
count[outer_width * outer_width - hole_width * hole_width] += 1
return sum(1 for n in count.values() if 1 <= n <= 10 )
if __name__ == "__main__":
print(F"{solution() = }")
| 124 | 0 |
'''simple docstring'''
def UpperCAmelCase ( UpperCAmelCase__ : str , UpperCAmelCase__ : str):
lowerCamelCase : List[str] = len(UpperCAmelCase__) + 1
lowerCamelCase : Any = len(UpperCAmelCase__) + 1
# dp is a 2d matrix where dp[i][j] denotes whether prefix string of
# length i of input_string matches with prefix string of length j of
# given pattern.
# "dp" stands for dynamic programming.
lowerCamelCase : List[Any] = [[0 for i in range(UpperCAmelCase__)] for j in range(UpperCAmelCase__)]
# since string of zero length match pattern of zero length
lowerCamelCase : List[str] = 1
# since pattern of zero length will never match with string of non-zero length
for i in range(1 , UpperCAmelCase__):
lowerCamelCase : str = 0
# since string of zero length will match with pattern where there
# is at least one * alternatively
for j in range(1 , UpperCAmelCase__):
lowerCamelCase : List[str] = dp[0][j - 2] if pattern[j - 1] == '*' else 0
# now using bottom-up approach to find for all remaining lengths
for i in range(1 , UpperCAmelCase__):
for j in range(1 , UpperCAmelCase__):
if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".":
lowerCamelCase : Union[str, Any] = dp[i - 1][j - 1]
elif pattern[j - 1] == "*":
if dp[i][j - 2] == 1:
lowerCamelCase : Tuple = 1
elif pattern[j - 2] in (input_string[i - 1], "."):
lowerCamelCase : List[str] = dp[i - 1][j]
else:
lowerCamelCase : Tuple = 0
else:
lowerCamelCase : List[Any] = 0
return bool(dp[-1][-1])
if __name__ == "__main__":
import doctest
doctest.testmod()
# inputing the strings
# input_string = input("input a string :")
# pattern = input("input a pattern :")
A = 'aab'
A = 'c*a*b'
# using function to check whether given string matches the given pattern
if match_pattern(input_string, pattern):
print(f"""{input_string} matches the given pattern {pattern}""")
else:
print(f"""{input_string} does not match with the given pattern {pattern}""")
| 700 |
'''simple docstring'''
import requests
from bsa import BeautifulSoup
def UpperCAmelCase ( UpperCAmelCase__ : str = "AAPL"):
lowerCamelCase : List[Any] = F'''https://in.finance.yahoo.com/quote/{symbol}?s={symbol}'''
lowerCamelCase : Dict = BeautifulSoup(requests.get(UpperCAmelCase__).text , 'html.parser')
lowerCamelCase : Dict = 'My(6px) Pos(r) smartphone_Mt(6px)'
return soup.find('div' , class_=class_).find('span').text
if __name__ == "__main__":
for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split():
print(f"""Current {symbol:<4} stock price is {stock_price(symbol):>8}""")
| 449 | 0 |
import inspect
import os
import re
from transformers.configuration_utils import PretrainedConfig
from transformers.utils import direct_transformers_import
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
lowerCamelCase : Union[str, Any] = '''src/transformers'''
# This is to make sure the transformers module imported is the one in the repo.
lowerCamelCase : Optional[int] = direct_transformers_import(PATH_TO_TRANSFORMERS)
lowerCamelCase : List[str] = transformers.models.auto.configuration_auto.CONFIG_MAPPING
lowerCamelCase : Union[str, Any] = {
# used to compute the property `self.chunk_length`
'''EncodecConfig''': ['''overlap'''],
# used as `self.bert_model = BertModel(config, ...)`
'''DPRConfig''': True,
# not used in modeling files, but it's an important information
'''FSMTConfig''': ['''langs'''],
# used internally in the configuration class file
'''GPTNeoConfig''': ['''attention_types'''],
# used internally in the configuration class file
'''EsmConfig''': ['''is_folding_model'''],
# used during training (despite we don't have training script for these models yet)
'''Mask2FormerConfig''': ['''ignore_value'''],
# `ignore_value` used during training (despite we don't have training script for these models yet)
# `norm` used in conversion script (despite not using in the modeling file)
'''OneFormerConfig''': ['''ignore_value''', '''norm'''],
# used during preprocessing and collation, see `collating_graphormer.py`
'''GraphormerConfig''': ['''spatial_pos_max'''],
# used internally in the configuration class file
'''T5Config''': ['''feed_forward_proj'''],
# used internally in the configuration class file
# `tokenizer_class` get default value `T5Tokenizer` intentionally
'''MT5Config''': ['''feed_forward_proj''', '''tokenizer_class'''],
'''UMT5Config''': ['''feed_forward_proj''', '''tokenizer_class'''],
# used internally in the configuration class file
'''LongT5Config''': ['''feed_forward_proj'''],
# used internally in the configuration class file
'''SwitchTransformersConfig''': ['''feed_forward_proj'''],
# having default values other than `1e-5` - we can't fix them without breaking
'''BioGptConfig''': ['''layer_norm_eps'''],
# having default values other than `1e-5` - we can't fix them without breaking
'''GLPNConfig''': ['''layer_norm_eps'''],
# having default values other than `1e-5` - we can't fix them without breaking
'''SegformerConfig''': ['''layer_norm_eps'''],
# having default values other than `1e-5` - we can't fix them without breaking
'''CvtConfig''': ['''layer_norm_eps'''],
# having default values other than `1e-5` - we can't fix them without breaking
'''PerceiverConfig''': ['''layer_norm_eps'''],
# used internally to calculate the feature size
'''InformerConfig''': ['''num_static_real_features''', '''num_time_features'''],
# used internally to calculate the feature size
'''TimeSeriesTransformerConfig''': ['''num_static_real_features''', '''num_time_features'''],
# used internally to calculate the feature size
'''AutoformerConfig''': ['''num_static_real_features''', '''num_time_features'''],
# used internally to calculate `mlp_dim`
'''SamVisionConfig''': ['''mlp_ratio'''],
# For (head) training, but so far not implemented
'''ClapAudioConfig''': ['''num_classes'''],
# Not used, but providing useful information to users
'''SpeechT5HifiGanConfig''': ['''sampling_rate'''],
}
# TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure
SPECIAL_CASES_TO_ALLOW.update(
{
'''CLIPSegConfig''': True,
'''DeformableDetrConfig''': True,
'''DetaConfig''': True,
'''DinatConfig''': True,
'''DonutSwinConfig''': True,
'''EfficientFormerConfig''': True,
'''FSMTConfig''': True,
'''JukeboxConfig''': True,
'''LayoutLMv2Config''': True,
'''MaskFormerSwinConfig''': True,
'''MT5Config''': True,
'''NatConfig''': True,
'''OneFormerConfig''': True,
'''PerceiverConfig''': True,
'''RagConfig''': True,
'''SpeechT5Config''': True,
'''SwinConfig''': True,
'''Swin2SRConfig''': True,
'''Swinv2Config''': True,
'''SwitchTransformersConfig''': True,
'''TableTransformerConfig''': True,
'''TapasConfig''': True,
'''TransfoXLConfig''': True,
'''UniSpeechConfig''': True,
'''UniSpeechSatConfig''': True,
'''WavLMConfig''': True,
'''WhisperConfig''': True,
# TODO: @Arthur (for `alignment_head` and `alignment_layer`)
'''JukeboxPriorConfig''': True,
# TODO: @Younes (for `is_decoder`)
'''Pix2StructTextConfig''': True,
}
)
def snake_case_ ( lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[Any] ):
__lowercase : List[Any] = False
for attribute in attributes:
for modeling_source in source_strings:
# check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)`
if (
F"config.{attribute}" in modeling_source
or F"getattr(config, \"{attribute}\"" in modeling_source
or F"getattr(self.config, \"{attribute}\"" in modeling_source
):
__lowercase : int = True
# Deal with multi-line cases
elif (
re.search(
rF"getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*\"{attribute}\"" , _lowerCAmelCase , )
is not None
):
__lowercase : Union[str, Any] = True
# `SequenceSummary` is called with `SequenceSummary(config)`
elif attribute in [
"summary_type",
"summary_use_proj",
"summary_activation",
"summary_last_dropout",
"summary_proj_to_labels",
"summary_first_dropout",
]:
if "SequenceSummary" in modeling_source:
__lowercase : List[str] = True
if attribute_used:
break
if attribute_used:
break
# common and important attributes, even if they do not always appear in the modeling files
__lowercase : int = [
"""bos_index""",
"""eos_index""",
"""pad_index""",
"""unk_index""",
"""mask_index""",
"""image_size""",
"""use_cache""",
"""out_features""",
"""out_indices""",
]
__lowercase : Optional[Any] = ["""encoder_no_repeat_ngram_size"""]
# Special cases to be allowed
__lowercase : Dict = True
if not attribute_used:
__lowercase : Tuple = False
for attribute in attributes:
# Allow if the default value in the configuration class is different from the one in `PretrainedConfig`
if attribute in ["is_encoder_decoder"] and default_value is True:
__lowercase : Dict = True
elif attribute in ["tie_word_embeddings"] and default_value is False:
__lowercase : List[str] = True
# Allow cases without checking the default value in the configuration class
elif attribute in attributes_to_allow + attributes_used_in_generation:
__lowercase : Tuple = True
elif attribute.endswith("""_token_id""" ):
__lowercase : Any = True
# configuration class specific cases
if not case_allowed:
__lowercase : List[Any] = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] )
__lowercase : List[Any] = allowed_cases is True or attribute in allowed_cases
return attribute_used or case_allowed
def snake_case_ ( lowerCAmelCase_ : Union[str, Any] ):
__lowercase : int = dict(inspect.signature(config_class.__init__ ).parameters )
__lowercase : int = [x for x in list(signature.keys() ) if x not in ["""self""", """kwargs"""]]
__lowercase : List[Any] = [signature[param].default for param in parameter_names]
# If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long
# as one variant is used, the test should pass
__lowercase : Optional[Any] = {}
if len(config_class.attribute_map ) > 0:
__lowercase : str = {v: k for k, v in config_class.attribute_map.items()}
# Get the path to modeling source files
__lowercase : List[str] = inspect.getsourcefile(_lowerCAmelCase )
__lowercase : Tuple = os.path.dirname(_lowerCAmelCase )
# Let's check against all frameworks: as long as one framework uses an attribute, we are good.
__lowercase : List[Any] = [os.path.join(_lowerCAmelCase , _lowerCAmelCase ) for fn in os.listdir(_lowerCAmelCase ) if fn.startswith("""modeling_""" )]
# Get the source code strings
__lowercase : List[Any] = []
for path in modeling_paths:
if os.path.isfile(_lowerCAmelCase ):
with open(_lowerCAmelCase ) as fp:
modeling_sources.append(fp.read() )
__lowercase : List[str] = []
for config_param, default_value in zip(_lowerCAmelCase , _lowerCAmelCase ):
# `attributes` here is all the variant names for `config_param`
__lowercase : Optional[Any] = [config_param]
# some configuration classes have non-empty `attribute_map`, and both names could be used in the
# corresponding modeling files. As long as one of them appears, it is fine.
if config_param in reversed_attribute_map:
attributes.append(reversed_attribute_map[config_param] )
if not check_attribute_being_used(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ):
unused_attributes.append(attributes[0] )
return sorted(_lowerCAmelCase )
def snake_case_ ( ):
__lowercase : Any = {}
for _config_class in list(CONFIG_MAPPING.values() ):
# Skip deprecated models
if "models.deprecated" in _config_class.__module__:
continue
# Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.)
__lowercase : int = [
cls
for name, cls in inspect.getmembers(
inspect.getmodule(_config_class ) , lambda lowerCAmelCase_ : inspect.isclass(_lowerCAmelCase )
and issubclass(_lowerCAmelCase , _lowerCAmelCase )
and inspect.getmodule(_lowerCAmelCase ) == inspect.getmodule(_config_class ) , )
]
for config_class in config_classes_in_module:
__lowercase : Union[str, Any] = check_config_attributes_being_used(_lowerCAmelCase )
if len(_lowerCAmelCase ) > 0:
__lowercase : int = unused_attributes
if len(_lowerCAmelCase ) > 0:
__lowercase : Dict = """The following configuration classes contain unused attributes in the corresponding modeling files:\n"""
for name, attributes in configs_with_unused_attributes.items():
error += F"{name}: {attributes}\n"
raise ValueError(_lowerCAmelCase )
if __name__ == "__main__":
check_config_attributes() | 149 |
import numpy
# List of input, output pairs
snake_case__ : Optional[Any] = (
((5, 2, 3), 1_5),
((6, 5, 9), 2_5),
((1_1, 1_2, 1_3), 4_1),
((1, 1, 1), 8),
((1_1, 1_2, 1_3), 4_1),
)
snake_case__ : str = (((5_1_5, 2_2, 1_3), 5_5_5), ((6_1, 3_5, 4_9), 1_5_0))
snake_case__ : List[Any] = [2, 4, 1, 5]
snake_case__ : int = len(train_data)
snake_case__ : List[Any] = 0.0_09
def lowercase ( _lowerCAmelCase , _lowerCAmelCase="train" ):
return calculate_hypothesis_value(_lowerCAmelCase , _lowerCAmelCase ) - output(
_lowerCAmelCase , _lowerCAmelCase )
def lowercase ( _lowerCAmelCase ):
UpperCAmelCase__ = 0
for i in range(len(_lowerCAmelCase ) - 1 ):
hyp_val += data_input_tuple[i] * parameter_vector[i + 1]
hyp_val += parameter_vector[0]
return hyp_val
def lowercase ( _lowerCAmelCase , _lowerCAmelCase ):
if data_set == "train":
return train_data[example_no][1]
elif data_set == "test":
return test_data[example_no][1]
return None
def lowercase ( _lowerCAmelCase , _lowerCAmelCase ):
if data_set == "train":
return _hypothesis_value(train_data[example_no][0] )
elif data_set == "test":
return _hypothesis_value(test_data[example_no][0] )
return None
def lowercase ( _lowerCAmelCase , _lowerCAmelCase=m ):
UpperCAmelCase__ = 0
for i in range(_lowerCAmelCase ):
if index == -1:
summation_value += _error(_lowerCAmelCase )
else:
summation_value += _error(_lowerCAmelCase ) * train_data[i][0][index]
return summation_value
def lowercase ( _lowerCAmelCase ):
UpperCAmelCase__ = summation_of_cost_derivative(_lowerCAmelCase , _lowerCAmelCase ) / m
return cost_derivative_value
def lowercase ( ):
global parameter_vector
# Tune these values to set a tolerance value for predicted output
UpperCAmelCase__ = 0.000002
UpperCAmelCase__ = 0
UpperCAmelCase__ = 0
while True:
j += 1
UpperCAmelCase__ = [0, 0, 0, 0]
for i in range(0 , len(_lowerCAmelCase ) ):
UpperCAmelCase__ = get_cost_derivative(i - 1 )
UpperCAmelCase__ = (
parameter_vector[i] - LEARNING_RATE * cost_derivative
)
if numpy.allclose(
_lowerCAmelCase , _lowerCAmelCase , atol=_lowerCAmelCase , rtol=_lowerCAmelCase , ):
break
UpperCAmelCase__ = temp_parameter_vector
print(("""Number of iterations:""", j) )
def lowercase ( ):
for i in range(len(_lowerCAmelCase ) ):
print(("""Actual output value:""", output(_lowerCAmelCase , """test""" )) )
print(("""Hypothesis output:""", calculate_hypothesis_value(_lowerCAmelCase , """test""" )) )
if __name__ == "__main__":
run_gradient_descent()
print('''\nTesting gradient descent for a linear hypothesis function.\n''')
test_gradient_descent()
| 392 | 0 |
'''simple docstring'''
from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration
a_ : List[Any] = "facebook/wmt19-en-de"
a_ : int = FSMTTokenizer.from_pretrained(mname)
# get the correct vocab sizes, etc. from the master model
a_ : int = FSMTConfig.from_pretrained(mname)
config.update(
dict(
d_model=4,
encoder_layers=1,
decoder_layers=1,
encoder_ffn_dim=4,
decoder_ffn_dim=4,
encoder_attention_heads=1,
decoder_attention_heads=1,
)
)
a_ : Optional[int] = FSMTForConditionalGeneration(config)
print(F"""num of params {tiny_model.num_parameters()}""")
# Test
a_ : Union[str, Any] = tokenizer(['Making tiny model'], return_tensors='pt')
a_ : Optional[int] = tiny_model(**batch)
print('test output:', len(outputs.logits[0]))
# Save
a_ : str = "tiny-wmt19-en-de"
tiny_model.half() # makes it smaller
tiny_model.save_pretrained(mname_tiny)
tokenizer.save_pretrained(mname_tiny)
print(F"""Generated {mname_tiny}""")
# Upload
# transformers-cli upload tiny-wmt19-en-de | 705 |
import re
def _SCREAMING_SNAKE_CASE ( snake_case_ : str ):
__magic_name__ = re.compile(
r'''^(?:0|94|\+94|0{2}94)''' r'''7(0|1|2|4|5|6|7|8)''' r'''(-| |)''' r'''\d{7}$''' )
return bool(re.search(snake_case_ , snake_case_ ) )
if __name__ == "__main__":
a_ : Optional[int] = '0094702343221'
print(is_sri_lankan_phone_number(phone)) | 678 | 0 |
# using dfs for finding eulerian path traversal
def _lowerCAmelCase ( A__ , A__ , A__ , A__=None ):
lowercase__ = (path or []) + [u]
for v in graph[u]:
if visited_edge[u][v] is False:
lowercase__, lowercase__ = True, True
lowercase__ = dfs(A__ , A__ , A__ , A__ )
return path
def _lowerCAmelCase ( A__ , A__ ):
lowercase__ = 0
lowercase__ = -1
for i in range(A__ ):
if i not in graph.keys():
continue
if len(graph[i] ) % 2 == 1:
odd_degree_nodes += 1
lowercase__ = i
if odd_degree_nodes == 0:
return 1, odd_node
if odd_degree_nodes == 2:
return 2, odd_node
return 3, odd_node
def _lowerCAmelCase ( A__ , A__ ):
lowercase__ = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )]
lowercase__, lowercase__ = check_circuit_or_path(A__ , A__ )
if check == 3:
print('graph is not Eulerian' )
print('no path' )
return
lowercase__ = 1
if check == 2:
lowercase__ = odd_node
print('graph has a Euler path' )
if check == 1:
print('graph has a Euler cycle' )
lowercase__ = dfs(A__ , A__ , A__ )
print(A__ )
def _lowerCAmelCase ( ):
lowercase__ = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]}
lowercase__ = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]}
lowercase__ = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]}
lowercase__ = {1: [2, 3], 2: [1, 3], 3: [1, 2]}
lowercase__ = {
1: [],
2: []
# all degree is zero
}
lowercase__ = 10
check_euler(A__ , A__ )
check_euler(A__ , A__ )
check_euler(A__ , A__ )
check_euler(A__ , A__ )
check_euler(A__ , A__ )
if __name__ == "__main__":
main()
| 622 |
import argparse
import torch
from transformers import (
EncodecConfig,
EncodecFeatureExtractor,
EncodecModel,
logging,
)
# checkpoints downloaded from:
# https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th
# https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin
# https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th
logging.set_verbosity_info()
a__ : List[str] = logging.get_logger("transformers.models.encodec")
a__ : Optional[Any] = {
"quantizer.vq.layers.*._codebook.inited": "quantizer.layers.*.codebook.inited",
"quantizer.vq.layers.*._codebook.cluster_size": "quantizer.layers.*.codebook.cluster_size",
"quantizer.vq.layers.*._codebook.embed": "quantizer.layers.*.codebook.embed",
"quantizer.vq.layers.*._codebook.embed_avg": "quantizer.layers.*.codebook.embed_avg",
}
a__ : int = {
"encoder.model.0.conv.conv": "encoder.layers.0.conv",
"encoder.model.1.block.1.conv.conv": "encoder.layers.1.block.1.conv",
"encoder.model.1.block.3.conv.conv": "encoder.layers.1.block.3.conv",
"encoder.model.1.shortcut.conv.conv": "encoder.layers.1.shortcut.conv",
"encoder.model.3.conv.conv": "encoder.layers.3.conv",
"encoder.model.4.block.1.conv.conv": "encoder.layers.4.block.1.conv",
"encoder.model.4.block.3.conv.conv": "encoder.layers.4.block.3.conv",
"encoder.model.4.shortcut.conv.conv": "encoder.layers.4.shortcut.conv",
"encoder.model.6.conv.conv": "encoder.layers.6.conv",
"encoder.model.7.block.1.conv.conv": "encoder.layers.7.block.1.conv",
"encoder.model.7.block.3.conv.conv": "encoder.layers.7.block.3.conv",
"encoder.model.7.shortcut.conv.conv": "encoder.layers.7.shortcut.conv",
"encoder.model.9.conv.conv": "encoder.layers.9.conv",
"encoder.model.10.block.1.conv.conv": "encoder.layers.10.block.1.conv",
"encoder.model.10.block.3.conv.conv": "encoder.layers.10.block.3.conv",
"encoder.model.10.shortcut.conv.conv": "encoder.layers.10.shortcut.conv",
"encoder.model.12.conv.conv": "encoder.layers.12.conv",
"encoder.model.13.lstm": "encoder.layers.13.lstm",
"encoder.model.15.conv.conv": "encoder.layers.15.conv",
}
a__ : int = {
"encoder.model.0.conv.norm": "encoder.layers.0.norm",
"encoder.model.1.block.1.conv.norm": "encoder.layers.1.block.1.norm",
"encoder.model.1.block.3.conv.norm": "encoder.layers.1.block.3.norm",
"encoder.model.1.shortcut.conv.norm": "encoder.layers.1.shortcut.norm",
"encoder.model.3.conv.norm": "encoder.layers.3.norm",
"encoder.model.4.block.1.conv.norm": "encoder.layers.4.block.1.norm",
"encoder.model.4.block.3.conv.norm": "encoder.layers.4.block.3.norm",
"encoder.model.4.shortcut.conv.norm": "encoder.layers.4.shortcut.norm",
"encoder.model.6.conv.norm": "encoder.layers.6.norm",
"encoder.model.7.block.1.conv.norm": "encoder.layers.7.block.1.norm",
"encoder.model.7.block.3.conv.norm": "encoder.layers.7.block.3.norm",
"encoder.model.7.shortcut.conv.norm": "encoder.layers.7.shortcut.norm",
"encoder.model.9.conv.norm": "encoder.layers.9.norm",
"encoder.model.10.block.1.conv.norm": "encoder.layers.10.block.1.norm",
"encoder.model.10.block.3.conv.norm": "encoder.layers.10.block.3.norm",
"encoder.model.10.shortcut.conv.norm": "encoder.layers.10.shortcut.norm",
"encoder.model.12.conv.norm": "encoder.layers.12.norm",
"encoder.model.15.conv.norm": "encoder.layers.15.norm",
}
a__ : Dict = {
"decoder.model.0.conv.conv": "decoder.layers.0.conv",
"decoder.model.1.lstm": "decoder.layers.1.lstm",
"decoder.model.3.convtr.convtr": "decoder.layers.3.conv",
"decoder.model.4.block.1.conv.conv": "decoder.layers.4.block.1.conv",
"decoder.model.4.block.3.conv.conv": "decoder.layers.4.block.3.conv",
"decoder.model.4.shortcut.conv.conv": "decoder.layers.4.shortcut.conv",
"decoder.model.6.convtr.convtr": "decoder.layers.6.conv",
"decoder.model.7.block.1.conv.conv": "decoder.layers.7.block.1.conv",
"decoder.model.7.block.3.conv.conv": "decoder.layers.7.block.3.conv",
"decoder.model.7.shortcut.conv.conv": "decoder.layers.7.shortcut.conv",
"decoder.model.9.convtr.convtr": "decoder.layers.9.conv",
"decoder.model.10.block.1.conv.conv": "decoder.layers.10.block.1.conv",
"decoder.model.10.block.3.conv.conv": "decoder.layers.10.block.3.conv",
"decoder.model.10.shortcut.conv.conv": "decoder.layers.10.shortcut.conv",
"decoder.model.12.convtr.convtr": "decoder.layers.12.conv",
"decoder.model.13.block.1.conv.conv": "decoder.layers.13.block.1.conv",
"decoder.model.13.block.3.conv.conv": "decoder.layers.13.block.3.conv",
"decoder.model.13.shortcut.conv.conv": "decoder.layers.13.shortcut.conv",
"decoder.model.15.conv.conv": "decoder.layers.15.conv",
}
a__ : Any = {
"decoder.model.0.conv.norm": "decoder.layers.0.norm",
"decoder.model.3.convtr.norm": "decoder.layers.3.norm",
"decoder.model.4.block.1.conv.norm": "decoder.layers.4.block.1.norm",
"decoder.model.4.block.3.conv.norm": "decoder.layers.4.block.3.norm",
"decoder.model.4.shortcut.conv.norm": "decoder.layers.4.shortcut.norm",
"decoder.model.6.convtr.norm": "decoder.layers.6.norm",
"decoder.model.7.block.1.conv.norm": "decoder.layers.7.block.1.norm",
"decoder.model.7.block.3.conv.norm": "decoder.layers.7.block.3.norm",
"decoder.model.7.shortcut.conv.norm": "decoder.layers.7.shortcut.norm",
"decoder.model.9.convtr.norm": "decoder.layers.9.norm",
"decoder.model.10.block.1.conv.norm": "decoder.layers.10.block.1.norm",
"decoder.model.10.block.3.conv.norm": "decoder.layers.10.block.3.norm",
"decoder.model.10.shortcut.conv.norm": "decoder.layers.10.shortcut.norm",
"decoder.model.12.convtr.norm": "decoder.layers.12.norm",
"decoder.model.13.block.1.conv.norm": "decoder.layers.13.block.1.norm",
"decoder.model.13.block.3.conv.norm": "decoder.layers.13.block.3.norm",
"decoder.model.13.shortcut.conv.norm": "decoder.layers.13.shortcut.norm",
"decoder.model.15.conv.norm": "decoder.layers.15.norm",
}
a__ : Tuple = {
**MAPPING_QUANTIZER,
**MAPPING_ENCODER,
**MAPPING_DECODER,
}
a__ : List[str] = {
**MAPPING_QUANTIZER,
**MAPPING_ENCODER,
**MAPPING_ENCODER_48K,
**MAPPING_DECODER,
**MAPPING_DECODER_48K,
}
a__ : str = []
a__ : str = []
def _lowerCAmelCase ( A__ , A__ , A__ , A__ , A__ ):
for attribute in key.split('.' ):
lowercase__ = getattr(A__ , A__ )
if weight_type is not None:
lowercase__ = getattr(A__ , A__ ).shape
else:
lowercase__ = 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":
lowercase__ = value
elif weight_type == "weight_g":
lowercase__ = value
elif weight_type == "weight_v":
lowercase__ = value
elif weight_type == "bias":
lowercase__ = value
elif weight_type == "running_mean":
lowercase__ = value
elif weight_type == "running_var":
lowercase__ = value
elif weight_type == "num_batches_tracked":
lowercase__ = value
elif weight_type == "weight_ih_l0":
lowercase__ = value
elif weight_type == "weight_hh_l0":
lowercase__ = value
elif weight_type == "bias_ih_l0":
lowercase__ = value
elif weight_type == "bias_hh_l0":
lowercase__ = value
elif weight_type == "weight_ih_l1":
lowercase__ = value
elif weight_type == "weight_hh_l1":
lowercase__ = value
elif weight_type == "bias_ih_l1":
lowercase__ = value
elif weight_type == "bias_hh_l1":
lowercase__ = value
else:
lowercase__ = value
logger.info(F'''{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.''' )
def _lowerCAmelCase ( A__ , A__ ):
for key in ignore_keys:
if key.endswith('.*' ):
if name.startswith(key[:-1] ):
return True
elif ".*." in key:
lowercase__, lowercase__ = key.split('.*.' )
if prefix in name and suffix in name:
return True
elif key in name:
return True
return False
def _lowerCAmelCase ( A__ , A__ , A__ ):
lowercase__ = []
if model_name == "encodec_24khz" or "encodec_32khz":
lowercase__ = MAPPING_24K
elif model_name == "encodec_48khz":
lowercase__ = MAPPING_48K
else:
raise ValueError(F'''Unsupported model: {model_name}''' )
for name, value in orig_dict.items():
if should_ignore(A__ , A__ ):
logger.info(F'''{name} was ignored''' )
continue
lowercase__ = False
for key, mapped_key in MAPPING.items():
if "*" in key:
lowercase__, lowercase__ = key.split('.*.' )
if prefix in name and suffix in name:
lowercase__ = suffix
if key in name:
# HACK otherwise .embed gets initialized with .embed_avg too
if key.endswith('embed' ) and name.endswith('embed_avg' ):
continue
lowercase__ = True
if "*" in mapped_key:
lowercase__ = name.split(A__ )[0].split('.' )[-2]
lowercase__ = mapped_key.replace('*' , A__ )
if "weight_g" in name:
lowercase__ = 'weight_g'
elif "weight_v" in name:
lowercase__ = 'weight_v'
elif "weight_ih_l0" in name:
lowercase__ = 'weight_ih_l0'
elif "weight_hh_l0" in name:
lowercase__ = 'weight_hh_l0'
elif "bias_ih_l0" in name:
lowercase__ = 'bias_ih_l0'
elif "bias_hh_l0" in name:
lowercase__ = 'bias_hh_l0'
elif "weight_ih_l1" in name:
lowercase__ = 'weight_ih_l1'
elif "weight_hh_l1" in name:
lowercase__ = 'weight_hh_l1'
elif "bias_ih_l1" in name:
lowercase__ = 'bias_ih_l1'
elif "bias_hh_l1" in name:
lowercase__ = 'bias_hh_l1'
elif "bias" in name:
lowercase__ = 'bias'
elif "weight" in name:
lowercase__ = 'weight'
elif "running_mean" in name:
lowercase__ = 'running_mean'
elif "running_var" in name:
lowercase__ = 'running_var'
elif "num_batches_tracked" in name:
lowercase__ = 'num_batches_tracked'
else:
lowercase__ = None
set_recursively(A__ , A__ , A__ , A__ , A__ )
continue
if not is_used:
unused_weights.append(A__ )
logger.warning(F'''Unused weights: {unused_weights}''' )
@torch.no_grad()
def _lowerCAmelCase ( A__ , A__ , A__ , A__=None , A__=None , ):
if config_path is not None:
lowercase__ = EncodecConfig.from_pretrained(A__ )
else:
lowercase__ = EncodecConfig()
if model_name == "encodec_24khz":
pass # config is already correct
elif model_name == "encodec_32khz":
lowercase__ = [8, 5, 4, 4]
lowercase__ = [2.2]
lowercase__ = 64
lowercase__ = 32_000
lowercase__ = 2_048
lowercase__ = False
lowercase__ = False
lowercase__ = False
elif model_name == "encodec_48khz":
lowercase__ = [8, 5, 4, 2]
lowercase__ = [3.0, 6.0, 12.0, 24.0]
lowercase__ = 48_000
lowercase__ = 2
lowercase__ = False
lowercase__ = 'time_group_norm'
lowercase__ = True
lowercase__ = 1.0
lowercase__ = 0.01
else:
raise ValueError(F'''Unknown model name: {model_name}''' )
lowercase__ = EncodecModel(A__ )
lowercase__ = EncodecFeatureExtractor(
feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , )
feature_extractor.save_pretrained(A__ )
lowercase__ = torch.load(A__ )
if "best_state" in original_checkpoint:
# we might have a training state saved, in which case discard the yaml results and just retain the weights
lowercase__ = original_checkpoint['best_state']
recursively_load_weights(A__ , A__ , A__ )
model.save_pretrained(A__ )
if repo_id:
print('Pushing to the hub...' )
feature_extractor.push_to_hub(A__ )
model.push_to_hub(A__ )
if __name__ == "__main__":
a__ : Optional[int] = argparse.ArgumentParser()
parser.add_argument(
"--model",
default="encodec_24khz",
type=str,
help="The model to convert. Should be one of 'encodec_24khz', 'encodec_32khz', 'encodec_48khz'.",
)
parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint")
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
parser.add_argument(
"--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model."
)
parser.add_argument(
"--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub."
)
a__ : Optional[int] = parser.parse_args()
convert_checkpoint(
args.model,
args.checkpoint_path,
args.pytorch_dump_folder_path,
args.config_path,
args.push_to_hub,
)
| 622 | 1 |
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class lowerCamelCase__ :
__lowerCamelCase = 42
__lowerCamelCase = None
__lowerCamelCase = None
def __lowerCAmelCase ( _UpperCamelCase ) -> bool:
'''simple docstring'''
def is_valid_tree(_UpperCamelCase ) -> bool:
if node is None:
return True
if not isinstance(_UpperCamelCase , _UpperCamelCase ):
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(_UpperCamelCase ):
raise ValueError(
"""Each node should be type of TreeNode and data should be float.""" )
def is_binary_search_tree_recursive_check(
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> bool:
if node is None:
return True
return (
left_bound < node.data < right_bound
and is_binary_search_tree_recursive_check(node.left , _UpperCamelCase , node.data )
and is_binary_search_tree_recursive_check(
node.right , node.data , _UpperCamelCase )
)
return is_binary_search_tree_recursive_check(_UpperCamelCase , -float("""inf""" ) , float("""inf""" ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 242 |
import inspect
import os
import torch
from transformers import AutoModel
from transformers.testing_utils import mockenv_context
from transformers.trainer_utils import set_seed
import accelerate
from accelerate.accelerator import Accelerator
from accelerate.state import AcceleratorState
from accelerate.test_utils.testing import (
AccelerateTestCase,
TempDirTestCase,
execute_subprocess_async,
require_cuda,
require_fsdp,
require_multi_gpu,
slow,
)
from accelerate.utils.constants import (
FSDP_AUTO_WRAP_POLICY,
FSDP_BACKWARD_PREFETCH,
FSDP_SHARDING_STRATEGY,
FSDP_STATE_DICT_TYPE,
)
from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin
from accelerate.utils.other import patch_environment
set_seed(42)
_lowercase = 'bert-base-cased'
_lowercase = 'fp16'
_lowercase = 'bf16'
_lowercase = [FPaa, BFaa]
@require_fsdp
@require_cuda
class lowerCamelCase__ ( A__ ):
def lowerCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
super().setUp()
lowerCamelCase__: List[str] = dict(
ACCELERATE_USE_FSDP="""true""" , MASTER_ADDR="""localhost""" , MASTER_PORT="""10999""" , RANK="""0""" , LOCAL_RANK="""0""" , WORLD_SIZE="""1""" , )
def lowerCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy
for i, strategy in enumerate(__a ):
lowerCamelCase__: Union[str, Any] = self.dist_env.copy()
lowerCamelCase__: int = f"""{i + 1}"""
lowerCamelCase__: Any = strategy
with mockenv_context(**__a ):
lowerCamelCase__: Optional[int] = FullyShardedDataParallelPlugin()
self.assertEqual(fsdp_plugin.sharding_strategy , ShardingStrategy(i + 1 ) )
def lowerCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch
for i, prefetch_policy in enumerate(__a ):
lowerCamelCase__: List[str] = self.dist_env.copy()
lowerCamelCase__: List[str] = prefetch_policy
with mockenv_context(**__a ):
lowerCamelCase__: Dict = FullyShardedDataParallelPlugin()
if prefetch_policy == "NO_PREFETCH":
self.assertIsNone(fsdp_plugin.backward_prefetch )
else:
self.assertEqual(fsdp_plugin.backward_prefetch , BackwardPrefetch(i + 1 ) )
def lowerCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType
for i, state_dict_type in enumerate(__a ):
lowerCamelCase__: str = self.dist_env.copy()
lowerCamelCase__: Tuple = state_dict_type
with mockenv_context(**__a ):
lowerCamelCase__: int = FullyShardedDataParallelPlugin()
self.assertEqual(fsdp_plugin.state_dict_type , StateDictType(i + 1 ) )
if state_dict_type == "FULL_STATE_DICT":
self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu )
self.assertTrue(fsdp_plugin.state_dict_config.ranka_only )
def lowerCamelCase_ ( self : Tuple ):
'''simple docstring'''
lowerCamelCase__: str = AutoModel.from_pretrained(__a )
for policy in FSDP_AUTO_WRAP_POLICY:
lowerCamelCase__: str = self.dist_env.copy()
lowerCamelCase__: Union[str, Any] = policy
if policy == "TRANSFORMER_BASED_WRAP":
lowerCamelCase__: Union[str, Any] = """BertLayer"""
elif policy == "SIZE_BASED_WRAP":
lowerCamelCase__: Optional[Any] = """2000"""
with mockenv_context(**__a ):
lowerCamelCase__: Union[str, Any] = FullyShardedDataParallelPlugin()
fsdp_plugin.set_auto_wrap_policy(__a )
if policy == "NO_WRAP":
self.assertIsNone(fsdp_plugin.auto_wrap_policy )
else:
self.assertIsNotNone(fsdp_plugin.auto_wrap_policy )
lowerCamelCase__: Optional[Any] = self.dist_env.copy()
lowerCamelCase__: str = """TRANSFORMER_BASED_WRAP"""
lowerCamelCase__: str = """T5Layer"""
with mockenv_context(**__a ):
lowerCamelCase__: Dict = FullyShardedDataParallelPlugin()
with self.assertRaises(__a ) as cm:
fsdp_plugin.set_auto_wrap_policy(__a )
self.assertTrue("""Could not find the transformer layer class to wrap in the model.""" in str(cm.exception ) )
lowerCamelCase__: Union[str, Any] = self.dist_env.copy()
lowerCamelCase__: int = """SIZE_BASED_WRAP"""
lowerCamelCase__: str = """0"""
with mockenv_context(**__a ):
lowerCamelCase__: Any = FullyShardedDataParallelPlugin()
fsdp_plugin.set_auto_wrap_policy(__a )
self.assertIsNone(fsdp_plugin.auto_wrap_policy )
def lowerCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision
from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler
for mp_dtype in dtypes:
lowerCamelCase__: Dict = self.dist_env.copy()
lowerCamelCase__: Union[str, Any] = mp_dtype
with mockenv_context(**__a ):
lowerCamelCase__: List[str] = Accelerator()
if mp_dtype == "fp16":
lowerCamelCase__: Any = torch.floataa
elif mp_dtype == "bf16":
lowerCamelCase__: Dict = torch.bfloataa
lowerCamelCase__: str = MixedPrecision(param_dtype=__a , reduce_dtype=__a , buffer_dtype=__a )
self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy , __a )
if mp_dtype == FPaa:
self.assertTrue(isinstance(accelerator.scaler , __a ) )
elif mp_dtype == BFaa:
self.assertIsNone(accelerator.scaler )
AcceleratorState._reset_state(__a )
def lowerCamelCase_ ( self : str ):
'''simple docstring'''
from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload
for flag in [True, False]:
lowerCamelCase__: List[Any] = self.dist_env.copy()
lowerCamelCase__: int = str(__a ).lower()
with mockenv_context(**__a ):
lowerCamelCase__: int = FullyShardedDataParallelPlugin()
self.assertEqual(fsdp_plugin.cpu_offload , CPUOffload(offload_params=__a ) )
@require_fsdp
@require_multi_gpu
@slow
class lowerCamelCase__ ( A__ ):
def lowerCamelCase_ ( self : Tuple ):
'''simple docstring'''
super().setUp()
lowerCamelCase__: List[Any] = 0.82
lowerCamelCase__: List[str] = [
"""fsdp_shard_grad_op_transformer_based_wrap""",
"""fsdp_full_shard_transformer_based_wrap""",
]
lowerCamelCase__: List[str] = {
"""multi_gpu_fp16""": 3200,
"""fsdp_shard_grad_op_transformer_based_wrap_fp16""": 2000,
"""fsdp_full_shard_transformer_based_wrap_fp16""": 1900,
# Disabling below test as it overwhelms the RAM memory usage
# on CI self-hosted runner leading to tests getting killed.
# "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang
}
lowerCamelCase__: List[str] = 160
lowerCamelCase__: Optional[int] = 160
lowerCamelCase__: Optional[int] = inspect.getfile(accelerate.test_utils )
lowerCamelCase__: Any = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps"""] )
def lowerCamelCase_ ( self : Dict ):
'''simple docstring'''
lowerCamelCase__: List[str] = os.path.join(self.test_scripts_folder , """test_performance.py""" )
lowerCamelCase__: Dict = ["""accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp"""]
for config in self.performance_configs:
lowerCamelCase__: Dict = cmd.copy()
for i, strategy in enumerate(__a ):
if strategy.lower() in config:
cmd_config.append(f"""--fsdp_sharding_strategy={i+1}""" )
break
if "fp32" in config:
cmd_config.append("""--mixed_precision=no""" )
else:
cmd_config.append("""--mixed_precision=fp16""" )
if "cpu_offload" in config:
cmd_config.append("""--fsdp_offload_params=True""" )
for policy in FSDP_AUTO_WRAP_POLICY:
if policy.lower() in config:
cmd_config.append(f"""--fsdp_auto_wrap_policy={policy}""" )
break
if policy == "TRANSFORMER_BASED_WRAP":
cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" )
elif policy == "SIZE_BASED_WRAP":
cmd_config.append("""--fsdp_min_num_params=2000""" )
cmd_config.extend(
[
self.test_file_path,
f"""--output_dir={self.tmpdir}""",
f"""--performance_lower_bound={self.performance_lower_bound}""",
] )
with patch_environment(omp_num_threads=1 ):
execute_subprocess_async(__a , env=os.environ.copy() )
def lowerCamelCase_ ( self : int ):
'''simple docstring'''
lowerCamelCase__: str = os.path.join(self.test_scripts_folder , """test_checkpointing.py""" )
lowerCamelCase__: Optional[Any] = [
"""accelerate""",
"""launch""",
"""--num_processes=2""",
"""--num_machines=1""",
"""--machine_rank=0""",
"""--use_fsdp""",
"""--mixed_precision=fp16""",
"""--fsdp_transformer_layer_cls_to_wrap=BertLayer""",
]
for i, strategy in enumerate(__a ):
lowerCamelCase__: Optional[Any] = cmd.copy()
cmd_config.append(f"""--fsdp_sharding_strategy={i+1}""" )
if strategy != "FULL_SHARD":
continue
lowerCamelCase__: Union[str, Any] = len(__a )
for state_dict_type in FSDP_STATE_DICT_TYPE:
lowerCamelCase__: Dict = cmd_config[:state_dict_config_index]
cmd_config.append(f"""--fsdp_state_dict_type={state_dict_type}""" )
cmd_config.extend(
[
self.test_file_path,
f"""--output_dir={self.tmpdir}""",
"""--partial_train_epoch=1""",
] )
with patch_environment(omp_num_threads=1 ):
execute_subprocess_async(__a , env=os.environ.copy() )
lowerCamelCase__: Union[str, Any] = cmd_config[:-1]
lowerCamelCase__: List[Any] = os.path.join(self.tmpdir , """epoch_0""" )
cmd_config.extend(
[
f"""--resume_from_checkpoint={resume_from_checkpoint}""",
] )
with patch_environment(omp_num_threads=1 ):
execute_subprocess_async(__a , env=os.environ.copy() )
def lowerCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
lowerCamelCase__: str = os.path.join(self.test_scripts_folder , """test_peak_memory_usage.py""" )
lowerCamelCase__: int = [
"""accelerate""",
"""launch""",
"""--num_processes=2""",
"""--num_machines=1""",
"""--machine_rank=0""",
]
for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items():
lowerCamelCase__: str = cmd.copy()
if "fp16" in spec:
cmd_config.extend(["""--mixed_precision=fp16"""] )
else:
cmd_config.extend(["""--mixed_precision=no"""] )
if "multi_gpu" in spec:
continue
else:
cmd_config.extend(["""--use_fsdp"""] )
for i, strategy in enumerate(__a ):
if strategy.lower() in spec:
cmd_config.append(f"""--fsdp_sharding_strategy={i+1}""" )
break
if "cpu_offload" in spec:
cmd_config.append("""--fsdp_offload_params=True""" )
for policy in FSDP_AUTO_WRAP_POLICY:
if policy.lower() in spec:
cmd_config.append(f"""--fsdp_auto_wrap_policy={policy}""" )
break
if policy == "TRANSFORMER_BASED_WRAP":
cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" )
elif policy == "SIZE_BASED_WRAP":
cmd_config.append("""--fsdp_min_num_params=2000""" )
cmd_config.extend(
[
self.test_file_path,
f"""--output_dir={self.tmpdir}""",
f"""--peak_memory_upper_bound={peak_mem_upper_bound}""",
f"""--n_train={self.n_train}""",
f"""--n_val={self.n_val}""",
] )
with patch_environment(omp_num_threads=1 ):
execute_subprocess_async(__a , env=os.environ.copy() )
| 242 | 1 |
import unittest
from transformers.testing_utils import require_bsa
from transformers.utils import is_bsa_available
from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin
if is_bsa_available():
from transformers import MarkupLMFeatureExtractor
class snake_case_ ( unittest.TestCase ):
"""simple docstring"""
def __init__(self: Optional[Any] , __UpperCAmelCase: Dict ) -> Optional[Any]:
'''simple docstring'''
__a : List[Any] = parent
def UpperCAmelCase__ (self: str ) -> List[Any]:
'''simple docstring'''
return {}
def a_ () -> str:
"""simple docstring"""
__a : List[str] = "<HTML>\n\n <HEAD>\n <TITLE>sample document</TITLE>\n </HEAD>\n\n <BODY BGCOLOR=\"FFFFFF\">\n <HR>\n <a href=\"http://google.com\">Goog</a>\n <H1>This is one header</H1>\n <H2>This is a another Header</H2>\n <P>Travel from\n <P>\n <B>SFO to JFK</B>\n <BR>\n <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B>\n <HR>\n <div style=\"color:#0000FF\">\n <h3>Traveler <b> name </b> is\n <p> John Doe </p>\n </div>"
__a : Dict = "\n <!DOCTYPE html>\n <html>\n <body>\n\n <h1>My First Heading</h1>\n <p>My first paragraph.</p>\n\n </body>\n </html>\n "
return [html_string_a, html_string_a]
@require_bsa
class snake_case_ ( __UpperCamelCase , unittest.TestCase ):
"""simple docstring"""
snake_case__ = MarkupLMFeatureExtractor if is_bsa_available() else None
def UpperCAmelCase__ (self: Union[str, Any] ) -> Optional[Any]:
'''simple docstring'''
__a : int = MarkupLMFeatureExtractionTester(self )
@property
def UpperCAmelCase__ (self: str ) -> List[Any]:
'''simple docstring'''
return self.feature_extract_tester.prepare_feat_extract_dict()
def UpperCAmelCase__ (self: Optional[Any] ) -> Union[str, Any]:
'''simple docstring'''
__a : Dict = self.feature_extraction_class()
# Test not batched input
__a : Any = get_html_strings()[0]
__a : List[str] = feature_extractor(__UpperCAmelCase )
# fmt: off
__a : int = [["sample document", "Goog", "This is one header", "This is a another Header", "Travel from", "SFO to JFK", "on May 2, 2015 at 2:00 pm. For details go to confirm.com", "Traveler", "name", "is", "John Doe"]]
__a : List[Any] = [["/html/head/title", "/html/body/a", "/html/body/h1", "/html/body/h2", "/html/body/p", "/html/body/p/p/b[1]", "/html/body/p/p/b[2]/i", "/html/body/p/p/div/h3", "/html/body/p/p/div/h3/b", "/html/body/p/p/div/h3", "/html/body/p/p/div/h3/p"]]
# fmt: on
self.assertEqual(encoding.nodes , __UpperCAmelCase )
self.assertEqual(encoding.xpaths , __UpperCAmelCase )
# Test batched
__a : Optional[Any] = get_html_strings()
__a : List[Any] = feature_extractor(__UpperCAmelCase )
# fmt: off
__a : str = expected_nodes + [["My First Heading", "My first paragraph."]]
__a : Optional[Any] = expected_xpaths + [["/html/body/h1", "/html/body/p"]]
self.assertEqual(len(encoding.nodes ) , 2 )
self.assertEqual(len(encoding.xpaths ) , 2 )
self.assertEqual(encoding.nodes , __UpperCAmelCase )
self.assertEqual(encoding.xpaths , __UpperCAmelCase )
| 351 |
UpperCAmelCase__ = '''Input must be a string of 8 numbers plus letter'''
UpperCAmelCase__ = '''TRWAGMYFPDXBNJZSQVHLCKE'''
def a_ (__A ) -> bool:
"""simple docstring"""
if not isinstance(__A , __A ):
__a : Any = f'Expected string as input, found {type(__A ).__name__}'
raise TypeError(__A )
__a : int = spanish_id.replace("-" , "" ).upper()
if len(__A ) != 9:
raise ValueError(__A )
try:
__a : Tuple = int(spanish_id_clean[0:8] )
__a : Optional[int] = 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()
| 351 | 1 |
import warnings
from ...utils import logging
from .image_processing_beit import BeitImageProcessor
lowercase__ =logging.get_logger(__name__)
class UpperCamelCase__ ( __lowercase ):
def __init__(self : Optional[Any] , *snake_case_ : Optional[int] , **snake_case_ : List[Any] ):
warnings.warn(
'''The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'''
''' use BeitImageProcessor instead.''' , snake_case_ , )
super().__init__(*snake_case_ , **snake_case_ )
| 326 |
import contextlib
import copy
import random
from typing import Any, Dict, Iterable, Optional, Union
import numpy as np
import torch
from .utils import deprecate, is_transformers_available
if is_transformers_available():
import transformers
def __UpperCamelCase ( lowerCAmelCase__ : int ):
random.seed(lowerCAmelCase__ )
np.random.seed(lowerCAmelCase__ )
torch.manual_seed(lowerCAmelCase__ )
torch.cuda.manual_seed_all(lowerCAmelCase__ )
# ^^ safe to call this function even if cuda is not available
class UpperCamelCase__ :
def __init__(self : Any , snake_case_ : Iterable[torch.nn.Parameter] , snake_case_ : float = 0.9999 , snake_case_ : float = 0.0 , snake_case_ : int = 0 , snake_case_ : bool = False , snake_case_ : Union[float, int] = 1.0 , snake_case_ : Union[float, int] = 2 / 3 , snake_case_ : Optional[Any] = None , snake_case_ : Dict[str, Any] = None , **snake_case_ : int , ):
if isinstance(snake_case_ , torch.nn.Module ):
__a : Optional[Any] = (
'''Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. '''
'''Please pass the parameters of the module instead.'''
)
deprecate(
'''passing a `torch.nn.Module` to `ExponentialMovingAverage`''' , '''1.0.0''' , snake_case_ , standard_warn=snake_case_ , )
__a : Optional[int] = parameters.parameters()
# set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility
__a : str = True
if kwargs.get('''max_value''' , snake_case_ ) is not None:
__a : List[Any] = '''The `max_value` argument is deprecated. Please use `decay` instead.'''
deprecate('''max_value''' , '''1.0.0''' , snake_case_ , standard_warn=snake_case_ )
__a : Optional[Any] = kwargs['''max_value''']
if kwargs.get('''min_value''' , snake_case_ ) is not None:
__a : Optional[int] = '''The `min_value` argument is deprecated. Please use `min_decay` instead.'''
deprecate('''min_value''' , '''1.0.0''' , snake_case_ , standard_warn=snake_case_ )
__a : int = kwargs['''min_value''']
__a : Any = list(snake_case_ )
__a : Optional[int] = [p.clone().detach() for p in parameters]
if kwargs.get('''device''' , snake_case_ ) is not None:
__a : Optional[Any] = '''The `device` argument is deprecated. Please use `to` instead.'''
deprecate('''device''' , '''1.0.0''' , snake_case_ , standard_warn=snake_case_ )
self.to(device=kwargs['''device'''] )
__a : List[str] = None
__a : Tuple = decay
__a : str = min_decay
__a : Any = update_after_step
__a : List[str] = use_ema_warmup
__a : Any = inv_gamma
__a : Any = power
__a : Union[str, Any] = 0
__a : Dict = None # set in `step()`
__a : Any = model_cls
__a : Any = model_config
@classmethod
def lowerCAmelCase (cls : List[str] , snake_case_ : Dict , snake_case_ : Dict ):
__a , __a : Optional[int] = model_cls.load_config(snake_case_ , return_unused_kwargs=snake_case_ )
__a : Dict = model_cls.from_pretrained(snake_case_ )
__a : List[Any] = cls(model.parameters() , model_cls=snake_case_ , model_config=model.config )
ema_model.load_state_dict(snake_case_ )
return ema_model
def lowerCAmelCase (self : Optional[Any] , snake_case_ : Dict ):
if self.model_cls is None:
raise ValueError('''`save_pretrained` can only be used if `model_cls` was defined at __init__.''' )
if self.model_config is None:
raise ValueError('''`save_pretrained` can only be used if `model_config` was defined at __init__.''' )
__a : int = self.model_cls.from_config(self.model_config )
__a : List[Any] = self.state_dict()
state_dict.pop('''shadow_params''' , snake_case_ )
model.register_to_config(**snake_case_ )
self.copy_to(model.parameters() )
model.save_pretrained(snake_case_ )
def lowerCAmelCase (self : Optional[int] , snake_case_ : int ):
__a : Tuple = max(0 , optimization_step - self.update_after_step - 1 )
if step <= 0:
return 0.0
if self.use_ema_warmup:
__a : Tuple = 1 - (1 + step / self.inv_gamma) ** -self.power
else:
__a : List[str] = (1 + step) / (1_0 + step)
__a : Dict = min(snake_case_ , self.decay )
# make sure decay is not smaller than min_decay
__a : int = max(snake_case_ , self.min_decay )
return cur_decay_value
@torch.no_grad()
def lowerCAmelCase (self : Optional[int] , snake_case_ : Iterable[torch.nn.Parameter] ):
if isinstance(snake_case_ , torch.nn.Module ):
__a : List[Any] = (
'''Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. '''
'''Please pass the parameters of the module instead.'''
)
deprecate(
'''passing a `torch.nn.Module` to `ExponentialMovingAverage.step`''' , '''1.0.0''' , snake_case_ , standard_warn=snake_case_ , )
__a : Union[str, Any] = parameters.parameters()
__a : Optional[Any] = list(snake_case_ )
self.optimization_step += 1
# Compute the decay factor for the exponential moving average.
__a : str = self.get_decay(self.optimization_step )
__a : List[str] = decay
__a : Dict = 1 - decay
__a : Optional[int] = contextlib.nullcontext
if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
import deepspeed
for s_param, param in zip(self.shadow_params , snake_case_ ):
if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
__a : Dict = deepspeed.zero.GatheredParameters(snake_case_ , modifier_rank=snake_case_ )
with context_manager():
if param.requires_grad:
s_param.sub_(one_minus_decay * (s_param - param) )
else:
s_param.copy_(snake_case_ )
def lowerCAmelCase (self : int , snake_case_ : Iterable[torch.nn.Parameter] ):
__a : str = list(snake_case_ )
for s_param, param in zip(self.shadow_params , snake_case_ ):
param.data.copy_(s_param.to(param.device ).data )
def lowerCAmelCase (self : int , snake_case_ : int=None , snake_case_ : int=None ):
__a : str = [
p.to(device=snake_case_ , dtype=snake_case_ ) if p.is_floating_point() else p.to(device=snake_case_ )
for p in self.shadow_params
]
def lowerCAmelCase (self : Dict ):
return {
"decay": self.decay,
"min_decay": self.min_decay,
"optimization_step": self.optimization_step,
"update_after_step": self.update_after_step,
"use_ema_warmup": self.use_ema_warmup,
"inv_gamma": self.inv_gamma,
"power": self.power,
"shadow_params": self.shadow_params,
}
def lowerCAmelCase (self : Tuple , snake_case_ : Iterable[torch.nn.Parameter] ):
__a : str = [param.detach().cpu().clone() for param in parameters]
def lowerCAmelCase (self : Optional[int] , snake_case_ : Iterable[torch.nn.Parameter] ):
if self.temp_stored_params is None:
raise RuntimeError('''This ExponentialMovingAverage has no `store()`ed weights ''' '''to `restore()`''' )
for c_param, param in zip(self.temp_stored_params , snake_case_ ):
param.data.copy_(c_param.data )
# Better memory-wise.
__a : Optional[Any] = None
def lowerCAmelCase (self : Optional[int] , snake_case_ : dict ):
__a : Dict = copy.deepcopy(snake_case_ )
__a : int = state_dict.get('''decay''' , self.decay )
if self.decay < 0.0 or self.decay > 1.0:
raise ValueError('''Decay must be between 0 and 1''' )
__a : List[str] = state_dict.get('''min_decay''' , self.min_decay )
if not isinstance(self.min_decay , snake_case_ ):
raise ValueError('''Invalid min_decay''' )
__a : Dict = state_dict.get('''optimization_step''' , self.optimization_step )
if not isinstance(self.optimization_step , snake_case_ ):
raise ValueError('''Invalid optimization_step''' )
__a : Optional[int] = state_dict.get('''update_after_step''' , self.update_after_step )
if not isinstance(self.update_after_step , snake_case_ ):
raise ValueError('''Invalid update_after_step''' )
__a : Any = state_dict.get('''use_ema_warmup''' , self.use_ema_warmup )
if not isinstance(self.use_ema_warmup , snake_case_ ):
raise ValueError('''Invalid use_ema_warmup''' )
__a : Any = state_dict.get('''inv_gamma''' , self.inv_gamma )
if not isinstance(self.inv_gamma , (float, int) ):
raise ValueError('''Invalid inv_gamma''' )
__a : Tuple = state_dict.get('''power''' , self.power )
if not isinstance(self.power , (float, int) ):
raise ValueError('''Invalid power''' )
__a : Dict = state_dict.get('''shadow_params''' , snake_case_ )
if shadow_params is not None:
__a : Tuple = shadow_params
if not isinstance(self.shadow_params , snake_case_ ):
raise ValueError('''shadow_params must be a list''' )
if not all(isinstance(snake_case_ , torch.Tensor ) for p in self.shadow_params ):
raise ValueError('''shadow_params must all be Tensors''' )
| 326 | 1 |
import unittest
from transformers import XLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
XLMForMultipleChoice,
XLMForQuestionAnswering,
XLMForQuestionAnsweringSimple,
XLMForSequenceClassification,
XLMForTokenClassification,
XLMModel,
XLMWithLMHeadModel,
)
from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST
class UpperCAmelCase_ :
def __init__( self ,__snake_case ,__snake_case=1_3 ,__snake_case=7 ,__snake_case=True ,__snake_case=True ,__snake_case=True ,__snake_case=True ,__snake_case=True ,__snake_case=False ,__snake_case=False ,__snake_case=False ,__snake_case=2 ,__snake_case=9_9 ,__snake_case=0 ,__snake_case=3_2 ,__snake_case=5 ,__snake_case=4 ,__snake_case=0.1 ,__snake_case=0.1 ,__snake_case=5_1_2 ,__snake_case=2 ,__snake_case=0.02 ,__snake_case=2 ,__snake_case=4 ,__snake_case="last" ,__snake_case=True ,__snake_case=None ,__snake_case=0 ,):
"""simple docstring"""
A_ = parent
A_ = batch_size
A_ = seq_length
A_ = is_training
A_ = use_input_lengths
A_ = use_token_type_ids
A_ = use_labels
A_ = gelu_activation
A_ = sinusoidal_embeddings
A_ = causal
A_ = asm
A_ = n_langs
A_ = vocab_size
A_ = n_special
A_ = hidden_size
A_ = num_hidden_layers
A_ = num_attention_heads
A_ = hidden_dropout_prob
A_ = attention_probs_dropout_prob
A_ = max_position_embeddings
A_ = type_sequence_label_size
A_ = initializer_range
A_ = num_labels
A_ = num_choices
A_ = summary_type
A_ = use_proj
A_ = scope
A_ = bos_token_id
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size )
A_ = random_attention_mask([self.batch_size, self.seq_length] )
A_ = None
if self.use_input_lengths:
A_ = (
ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2
) # small variation of seq_length
A_ = None
if self.use_token_type_ids:
A_ = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs )
A_ = None
A_ = None
A_ = None
if self.use_labels:
A_ = ids_tensor([self.batch_size] ,self.type_sequence_label_size )
A_ = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels )
A_ = ids_tensor([self.batch_size] ,2 ).float()
A_ = ids_tensor([self.batch_size] ,self.num_choices )
A_ = self.get_config()
return (
config,
input_ids,
token_type_ids,
input_lengths,
sequence_labels,
token_labels,
is_impossible_labels,
choice_labels,
input_mask,
)
def __UpperCAmelCase ( self ):
"""simple docstring"""
return XLMConfig(
vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,num_labels=self.num_labels ,bos_token_id=self.bos_token_id ,)
def __UpperCAmelCase ( self ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,):
"""simple docstring"""
A_ = XLMModel(config=__snake_case )
model.to(__snake_case )
model.eval()
A_ = model(__snake_case ,lengths=__snake_case ,langs=__snake_case )
A_ = model(__snake_case ,langs=__snake_case )
A_ = model(__snake_case )
self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) )
def __UpperCAmelCase ( self ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,):
"""simple docstring"""
A_ = XLMWithLMHeadModel(__snake_case )
model.to(__snake_case )
model.eval()
A_ = model(__snake_case ,token_type_ids=__snake_case ,labels=__snake_case )
self.parent.assertEqual(result.loss.shape ,() )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) )
def __UpperCAmelCase ( self ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,):
"""simple docstring"""
A_ = XLMForQuestionAnsweringSimple(__snake_case )
model.to(__snake_case )
model.eval()
A_ = model(__snake_case )
A_ = model(__snake_case ,start_positions=__snake_case ,end_positions=__snake_case )
A_ = outputs
self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) )
def __UpperCAmelCase ( self ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,):
"""simple docstring"""
A_ = XLMForQuestionAnswering(__snake_case )
model.to(__snake_case )
model.eval()
A_ = model(__snake_case )
A_ = model(
__snake_case ,start_positions=__snake_case ,end_positions=__snake_case ,cls_index=__snake_case ,is_impossible=__snake_case ,p_mask=__snake_case ,)
A_ = model(
__snake_case ,start_positions=__snake_case ,end_positions=__snake_case ,cls_index=__snake_case ,is_impossible=__snake_case ,)
((A_) , ) = result_with_labels.to_tuple()
A_ = model(__snake_case ,start_positions=__snake_case ,end_positions=__snake_case )
((A_) , ) = result_with_labels.to_tuple()
self.parent.assertEqual(result_with_labels.loss.shape ,() )
self.parent.assertEqual(result.start_top_log_probs.shape ,(self.batch_size, model.config.start_n_top) )
self.parent.assertEqual(result.start_top_index.shape ,(self.batch_size, model.config.start_n_top) )
self.parent.assertEqual(
result.end_top_log_probs.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) )
self.parent.assertEqual(
result.end_top_index.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) )
self.parent.assertEqual(result.cls_logits.shape ,(self.batch_size,) )
def __UpperCAmelCase ( self ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,):
"""simple docstring"""
A_ = XLMForSequenceClassification(__snake_case )
model.to(__snake_case )
model.eval()
A_ = model(__snake_case )
A_ = model(__snake_case ,labels=__snake_case )
self.parent.assertEqual(result.loss.shape ,() )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) )
def __UpperCAmelCase ( self ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,):
"""simple docstring"""
A_ = self.num_labels
A_ = XLMForTokenClassification(__snake_case )
model.to(__snake_case )
model.eval()
A_ = model(__snake_case ,attention_mask=__snake_case ,labels=__snake_case )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) )
def __UpperCAmelCase ( self ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,):
"""simple docstring"""
A_ = self.num_choices
A_ = XLMForMultipleChoice(config=__snake_case )
model.to(__snake_case )
model.eval()
A_ = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous()
A_ = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous()
A_ = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous()
A_ = model(
__snake_case ,attention_mask=__snake_case ,token_type_ids=__snake_case ,labels=__snake_case ,)
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.prepare_config_and_inputs()
(
(
A_
) , (
A_
) , (
A_
) , (
A_
) , (
A_
) , (
A_
) , (
A_
) , (
A_
) , (
A_
) ,
) = config_and_inputs
A_ = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''lengths''': input_lengths}
return config, inputs_dict
@require_torch
class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ):
__lowerCAmelCase : Any = (
(
XLMModel,
XLMWithLMHeadModel,
XLMForQuestionAnswering,
XLMForSequenceClassification,
XLMForQuestionAnsweringSimple,
XLMForTokenClassification,
XLMForMultipleChoice,
)
if is_torch_available()
else ()
)
__lowerCAmelCase : Optional[int] = (
(XLMWithLMHeadModel,) if is_torch_available() else ()
) # TODO (PVP): Check other models whether language generation is also applicable
__lowerCAmelCase : int = (
{
"""feature-extraction""": XLMModel,
"""fill-mask""": XLMWithLMHeadModel,
"""question-answering""": XLMForQuestionAnsweringSimple,
"""text-classification""": XLMForSequenceClassification,
"""text-generation""": XLMWithLMHeadModel,
"""token-classification""": XLMForTokenClassification,
"""zero-shot""": XLMForSequenceClassification,
}
if is_torch_available()
else {}
)
def __UpperCAmelCase ( self ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ):
"""simple docstring"""
if (
pipeline_test_casse_name == "QAPipelineTests"
and tokenizer_name is not None
and not tokenizer_name.endswith('''Fast''' )
):
# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
return True
return False
def __UpperCAmelCase ( self ,__snake_case ,__snake_case ,__snake_case=False ):
"""simple docstring"""
A_ = super()._prepare_for_class(__snake_case ,__snake_case ,return_labels=__snake_case )
if return_labels:
if model_class.__name__ == "XLMForQuestionAnswering":
A_ = torch.zeros(
self.model_tester.batch_size ,dtype=torch.long ,device=__snake_case )
A_ = torch.zeros(
self.model_tester.batch_size ,dtype=torch.long ,device=__snake_case )
return inputs_dict
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = XLMModelTester(self )
A_ = ConfigTester(self ,config_class=__snake_case ,emb_dim=3_7 )
def __UpperCAmelCase ( self ):
"""simple docstring"""
self.config_tester.run_common_tests()
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_model(*__snake_case )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_lm_head(*__snake_case )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_simple_qa(*__snake_case )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_qa(*__snake_case )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_sequence_classif(*__snake_case )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_token_classif(*__snake_case )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_for_multiple_choice(*__snake_case )
def __UpperCAmelCase ( self ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case=False ,__snake_case=1 ):
"""simple docstring"""
self.assertIsInstance(__snake_case ,__snake_case )
self.assertListEqual(
[isinstance(__snake_case ,__snake_case ) for iter_attentions in attentions] ,[True] * len(__snake_case ) )
self.assertEqual(len(__snake_case ) ,(max_length - min_length) * num_beam_groups )
for idx, iter_attentions in enumerate(__snake_case ):
# adds PAD dummy token
A_ = min_length + idx + 1
A_ = min_length + idx + 1
A_ = (
batch_size * num_beam_groups,
config.num_attention_heads,
tgt_len,
src_len,
)
# check attn size
self.assertListEqual(
[layer_attention.shape for layer_attention in iter_attentions] ,[expected_shape] * len(__snake_case ) )
def __UpperCAmelCase ( self ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case=False ,__snake_case=1 ):
"""simple docstring"""
self.assertIsInstance(__snake_case ,__snake_case )
self.assertListEqual(
[isinstance(__snake_case ,__snake_case ) for iter_hidden_states in hidden_states] ,[True] * len(__snake_case ) ,)
self.assertEqual(len(__snake_case ) ,(max_length - min_length) * num_beam_groups )
for idx, iter_hidden_states in enumerate(__snake_case ):
# adds PAD dummy token
A_ = min_length + idx + 1
A_ = (batch_size * num_beam_groups, seq_len, config.hidden_size)
# check hidden size
self.assertListEqual(
[layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] ,[expected_shape] * len(__snake_case ) ,)
pass
@slow
def __UpperCAmelCase ( self ):
"""simple docstring"""
for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
A_ = XLMModel.from_pretrained(__snake_case )
self.assertIsNotNone(__snake_case )
@require_torch
class UpperCAmelCase_ ( unittest.TestCase ):
@slow
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = XLMWithLMHeadModel.from_pretrained('''xlm-mlm-en-2048''' )
model.to(__snake_case )
A_ = torch.tensor([[1_4, 4_4_7]] ,dtype=torch.long ,device=__snake_case ) # the president
A_ = [
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
1_4,
4_4_7,
] # the president the president the president the president the president the president the president the president the president the president
# TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
A_ = model.generate(__snake_case ,do_sample=__snake_case )
self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,__snake_case )
| 188 |
def UpperCAmelCase_ ( _UpperCAmelCase :list ) -> list:
'''simple docstring'''
if len(_UpperCAmelCase ) < 2:
return collection
def circle_sort_util(_UpperCAmelCase :list , _UpperCAmelCase :int , _UpperCAmelCase :int ) -> bool:
A_ = False
if low == high:
return swapped
A_ = low
A_ = high
while left < right:
if collection[left] > collection[right]:
A_ , A_ = (
collection[right],
collection[left],
)
A_ = True
left += 1
right -= 1
if left == right and collection[left] > collection[right + 1]:
A_ , A_ = (
collection[right + 1],
collection[left],
)
A_ = True
A_ = low + int((high - low) / 2 )
A_ = circle_sort_util(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
A_ = circle_sort_util(_UpperCAmelCase , mid + 1 , _UpperCAmelCase )
return swapped or left_swap or right_swap
A_ = True
while is_not_sorted is True:
A_ = circle_sort_util(_UpperCAmelCase , 0 , len(_UpperCAmelCase ) - 1 )
return collection
if __name__ == "__main__":
a__ : Optional[Any] = input('Enter numbers separated by a comma:\n').strip()
a__ : List[str] = [int(item) for item in user_input.split(',')]
print(circle_sort(unsorted))
| 188 | 1 |
'''simple docstring'''
from collections import defaultdict
class lowerCamelCase :
'''simple docstring'''
def __init__( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Union[str, Any] ) ->Tuple:
UpperCAmelCase_ = total # total no of tasks (N)
# DP table will have a dimension of (2^M)*N
# initially all values are set to -1
UpperCAmelCase_ = [
[-1 for i in range(total + 1 )] for j in range(2 ** len(UpperCAmelCase__ ) )
]
UpperCAmelCase_ = defaultdict(UpperCAmelCase__ ) # stores the list of persons for each task
# final_mask is used to check if all persons are included by setting all bits
# to 1
UpperCAmelCase_ = (1 << len(UpperCAmelCase__ )) - 1
def lowerCAmelCase__ ( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : Tuple ) ->List[Any]:
# if mask == self.finalmask all persons are distributed tasks, return 1
if mask == self.final_mask:
return 1
# if not everyone gets the task and no more tasks are available, return 0
if task_no > self.total_tasks:
return 0
# if case already considered
if self.dp[mask][task_no] != -1:
return self.dp[mask][task_no]
# Number of ways when we don't this task in the arrangement
UpperCAmelCase_ = self.count_ways_until(UpperCAmelCase__ , task_no + 1 )
# now assign the tasks one by one to all possible persons and recursively
# assign for the remaining tasks.
if task_no in self.task:
for p in self.task[task_no]:
# if p is already given a task
if mask & (1 << p):
continue
# assign this task to p and change the mask value. And recursively
# assign tasks with the new mask value.
total_ways_util += self.count_ways_until(mask | (1 << p) , task_no + 1 )
# save the value.
UpperCAmelCase_ = total_ways_util
return self.dp[mask][task_no]
def lowerCAmelCase__ ( self : List[str] , UpperCAmelCase__ : List[Any] ) ->Any:
# Store the list of persons for each task
for i in range(len(UpperCAmelCase__ ) ):
for j in task_performed[i]:
self.task[j].append(UpperCAmelCase__ )
# call the function to fill the DP table, final answer is stored in dp[0][1]
return self.count_ways_until(0 , 1 )
if __name__ == "__main__":
lowercase__ : int = 5 # total no of tasks (the value of N)
# the list of tasks that can be done by M persons.
lowercase__ : List[str] = [[1, 3, 4], [1, 2, 5], [3, 4]]
print(
AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways(
task_performed
)
)
| 43 | '''simple docstring'''
import math
from typing import Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
get_image_size,
is_torch_available,
is_torch_tensor,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_torch_available():
import torch
if is_vision_available():
import PIL
lowercase__ : Optional[int] = logging.get_logger(__name__)
def __lowerCamelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : Union[int, Iterable[int]] , _UpperCamelCase : bool , _UpperCamelCase : int ):
'''simple docstring'''
def constraint_to_multiple_of(_UpperCamelCase : int , _UpperCamelCase : Tuple , _UpperCamelCase : Optional[int]=0 , _UpperCamelCase : str=None ):
UpperCAmelCase_ = round(val / multiple ) * multiple
if max_val is not None and x > max_val:
UpperCAmelCase_ = math.floor(val / multiple ) * multiple
if x < min_val:
UpperCAmelCase_ = math.ceil(val / multiple ) * multiple
return x
UpperCAmelCase_ = (output_size, output_size) if isinstance(_UpperCamelCase , _UpperCamelCase ) else output_size
UpperCAmelCase_ , UpperCAmelCase_ = get_image_size(_UpperCamelCase )
UpperCAmelCase_ , UpperCAmelCase_ = output_size
# determine new height and width
UpperCAmelCase_ = output_height / input_height
UpperCAmelCase_ = output_width / input_width
if keep_aspect_ratio:
# scale as little as possible
if abs(1 - scale_width ) < abs(1 - scale_height ):
# fit width
UpperCAmelCase_ = scale_width
else:
# fit height
UpperCAmelCase_ = scale_height
UpperCAmelCase_ = constraint_to_multiple_of(scale_height * input_height , multiple=_UpperCamelCase )
UpperCAmelCase_ = constraint_to_multiple_of(scale_width * input_width , multiple=_UpperCamelCase )
return (new_height, new_width)
class lowerCamelCase ( lowerCamelCase ):
'''simple docstring'''
lowerCAmelCase__ = ['''pixel_values''']
def __init__( self : Any , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Union[int, float] = 1 / 255 , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , **UpperCAmelCase__ : str , ) ->None:
super().__init__(**UpperCAmelCase__ )
UpperCAmelCase_ = size if size is not None else {'''height''': 384, '''width''': 384}
UpperCAmelCase_ = get_size_dict(UpperCAmelCase__ )
UpperCAmelCase_ = do_resize
UpperCAmelCase_ = size
UpperCAmelCase_ = keep_aspect_ratio
UpperCAmelCase_ = ensure_multiple_of
UpperCAmelCase_ = resample
UpperCAmelCase_ = do_rescale
UpperCAmelCase_ = rescale_factor
UpperCAmelCase_ = do_normalize
UpperCAmelCase_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
UpperCAmelCase_ = image_std if image_std is not None else IMAGENET_STANDARD_STD
def lowerCAmelCase__ ( self : Union[str, Any] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Dict[str, int] , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : List[str] , ) ->np.ndarray:
UpperCAmelCase_ = get_size_dict(UpperCAmelCase__ )
if "height" not in size or "width" not in size:
raise ValueError(f"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}""" )
UpperCAmelCase_ = get_resize_output_image_size(
UpperCAmelCase__ , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=UpperCAmelCase__ , multiple=UpperCAmelCase__ , )
return resize(UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ )
def lowerCAmelCase__ ( self : int , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Union[int, float] , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Optional[Any] , ) ->Any:
return rescale(UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ )
def lowerCAmelCase__ ( self : List[Any] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Union[float, List[float]] , UpperCAmelCase__ : Union[float, List[float]] , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Optional[int] , ) ->np.ndarray:
return normalize(UpperCAmelCase__ , mean=UpperCAmelCase__ , std=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ )
def lowerCAmelCase__ ( self : str , UpperCAmelCase__ : ImageInput , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : int = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : int = None , UpperCAmelCase__ : PILImageResampling = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : float = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , UpperCAmelCase__ : Optional[Union[float, List[float]]] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : Any , ) ->PIL.Image.Image:
UpperCAmelCase_ = do_resize if do_resize is not None else self.do_resize
UpperCAmelCase_ = size if size is not None else self.size
UpperCAmelCase_ = get_size_dict(UpperCAmelCase__ )
UpperCAmelCase_ = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
UpperCAmelCase_ = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
UpperCAmelCase_ = resample if resample is not None else self.resample
UpperCAmelCase_ = do_rescale if do_rescale is not None else self.do_rescale
UpperCAmelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor
UpperCAmelCase_ = do_normalize if do_normalize is not None else self.do_normalize
UpperCAmelCase_ = image_mean if image_mean is not None else self.image_mean
UpperCAmelCase_ = image_std if image_std is not None else self.image_std
UpperCAmelCase_ = make_list_of_images(UpperCAmelCase__ )
if not valid_images(UpperCAmelCase__ ):
raise ValueError(
'''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
'''torch.Tensor, tf.Tensor or jax.ndarray.''' )
if do_resize and size is None or resample is None:
raise ValueError('''Size and resample must be specified if do_resize is True.''' )
if do_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.
UpperCAmelCase_ = [to_numpy_array(UpperCAmelCase__ ) for image in images]
if do_resize:
UpperCAmelCase_ = [self.resize(image=UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images]
if do_rescale:
UpperCAmelCase_ = [self.rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ ) for image in images]
if do_normalize:
UpperCAmelCase_ = [self.normalize(image=UpperCAmelCase__ , mean=UpperCAmelCase__ , std=UpperCAmelCase__ ) for image in images]
UpperCAmelCase_ = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images]
UpperCAmelCase_ = {'''pixel_values''': images}
return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ )
def lowerCAmelCase__ ( self : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Tuple] = None ) ->Optional[Any]:
UpperCAmelCase_ = outputs.logits
# Resize logits and compute semantic segmentation maps
if target_sizes is not None:
if len(UpperCAmelCase__ ) != len(UpperCAmelCase__ ):
raise ValueError(
'''Make sure that you pass in as many target sizes as the batch dimension of the logits''' )
if is_torch_tensor(UpperCAmelCase__ ):
UpperCAmelCase_ = target_sizes.numpy()
UpperCAmelCase_ = []
for idx in range(len(UpperCAmelCase__ ) ):
UpperCAmelCase_ = torch.nn.functional.interpolate(
logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=UpperCAmelCase__ )
UpperCAmelCase_ = resized_logits[0].argmax(dim=0 )
semantic_segmentation.append(UpperCAmelCase__ )
else:
UpperCAmelCase_ = logits.argmax(dim=1 )
UpperCAmelCase_ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )]
return semantic_segmentation
| 43 | 1 |
'''simple docstring'''
import numpy as np
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel
from ...utils import logging
SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__)
class lowerCAmelCase_ ( snake_case__ ):
"""simple docstring"""
a_ :Optional[Any] =CLIPConfig
a_ :Optional[Any] =["""CLIPEncoderLayer"""]
def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : CLIPConfig ):
'''simple docstring'''
super().__init__(SCREAMING_SNAKE_CASE__ )
__a = CLIPVisionModelWithProjection(config.vision_config )
__a = nn.Linear(config.vision_config.projection_dim , 1 )
__a = nn.Linear(config.vision_config.projection_dim , 1 )
@torch.no_grad()
def __a ( self : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any]=0.5 , SCREAMING_SNAKE_CASE__ : str=0.5 ):
'''simple docstring'''
__a = self.vision_model(SCREAMING_SNAKE_CASE__ )[0]
__a = self.p_head(SCREAMING_SNAKE_CASE__ )
__a = nsfw_detected.flatten()
__a = nsfw_detected > p_threshold
__a = nsfw_detected.tolist()
if any(SCREAMING_SNAKE_CASE__ ):
logger.warning(
"""Potential NSFW content was detected in one or more images. A black image will be returned instead."""
""" Try again with a different prompt and/or seed.""" )
for idx, nsfw_detected_ in enumerate(SCREAMING_SNAKE_CASE__ ):
if nsfw_detected_:
__a = np.zeros(images[idx].shape )
__a = self.w_head(SCREAMING_SNAKE_CASE__ )
__a = watermark_detected.flatten()
__a = watermark_detected > w_threshold
__a = watermark_detected.tolist()
if any(SCREAMING_SNAKE_CASE__ ):
logger.warning(
"""Potential watermarked content was detected in one or more images. A black image will be returned instead."""
""" Try again with a different prompt and/or seed.""" )
for idx, watermark_detected_ in enumerate(SCREAMING_SNAKE_CASE__ ):
if watermark_detected_:
__a = np.zeros(images[idx].shape )
return images, nsfw_detected, watermark_detected
| 582 |
'''simple docstring'''
import inspect
import unittest
from transformers import MobileViTConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import MobileViTImageProcessor
class lowerCAmelCase_ ( snake_case__ ):
"""simple docstring"""
def __a ( self : Any ):
'''simple docstring'''
__a = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , """hidden_sizes""" ) )
self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , """neck_hidden_sizes""" ) )
self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , """num_attention_heads""" ) )
class lowerCAmelCase_ :
"""simple docstring"""
def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple=1_3 , SCREAMING_SNAKE_CASE__ : List[str]=3_2 , SCREAMING_SNAKE_CASE__ : int=2 , SCREAMING_SNAKE_CASE__ : int=3 , SCREAMING_SNAKE_CASE__ : Optional[int]=6_4_0 , SCREAMING_SNAKE_CASE__ : Tuple=4 , SCREAMING_SNAKE_CASE__ : Tuple="silu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=3 , SCREAMING_SNAKE_CASE__ : List[str]=3_2 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.0_2 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE__ : str=None , ):
'''simple docstring'''
__a = parent
__a = batch_size
__a = image_size
__a = patch_size
__a = num_channels
__a = last_hidden_size
__a = num_attention_heads
__a = hidden_act
__a = conv_kernel_size
__a = output_stride
__a = hidden_dropout_prob
__a = attention_probs_dropout_prob
__a = classifier_dropout_prob
__a = use_labels
__a = is_training
__a = num_labels
__a = initializer_range
__a = scope
def __a ( self : Optional[int] ):
'''simple docstring'''
__a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__a = None
__a = None
if self.use_labels:
__a = ids_tensor([self.batch_size] , self.num_labels )
__a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
__a = self.get_config()
return config, pixel_values, labels, pixel_labels
def __a ( self : Any ):
'''simple docstring'''
return MobileViTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , )
def __a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int ):
'''simple docstring'''
__a = MobileViTModel(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.last_hidden_size,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
def __a ( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] ):
'''simple docstring'''
__a = self.num_labels
__a = MobileViTForImageClassification(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.num_labels) )
def __a ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ):
'''simple docstring'''
__a = self.num_labels
__a = MobileViTForSemanticSegmentation(SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
__a = model(SCREAMING_SNAKE_CASE__ )
self.parent.assertEqual(
result.logits.shape , (
self.batch_size,
self.num_labels,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
__a = model(SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ )
self.parent.assertEqual(
result.logits.shape , (
self.batch_size,
self.num_labels,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
def __a ( self : Optional[Any] ):
'''simple docstring'''
__a = self.prepare_config_and_inputs()
__a , __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_ :List[str] =(
(MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
if is_torch_available()
else ()
)
a_ :str =(
{
"""feature-extraction""": MobileViTModel,
"""image-classification""": MobileViTForImageClassification,
"""image-segmentation""": MobileViTForSemanticSegmentation,
}
if is_torch_available()
else {}
)
a_ :Tuple =False
a_ :Dict =False
a_ :int =False
a_ :Optional[int] =False
def __a ( self : List[str] ):
'''simple docstring'''
__a = MobileViTModelTester(self )
__a = MobileViTConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ )
def __a ( self : List[Any] ):
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason="""MobileViT does not use inputs_embeds""" )
def __a ( self : int ):
'''simple docstring'''
pass
@unittest.skip(reason="""MobileViT does not support input and output embeddings""" )
def __a ( self : Optional[Any] ):
'''simple docstring'''
pass
@unittest.skip(reason="""MobileViT does not output attentions""" )
def __a ( self : int ):
'''simple docstring'''
pass
def __a ( self : Dict ):
'''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__ )
@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" )
def __a ( self : Tuple ):
'''simple docstring'''
pass
def __a ( self : List[Any] ):
'''simple docstring'''
__a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ )
def __a ( self : Tuple ):
'''simple docstring'''
def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple ):
__a = model_class(SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
with torch.no_grad():
__a = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
__a = outputs.hidden_states
__a = 5
self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ )
# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
# with the width and height being successively divided by 2.
__a = 2
for i in range(len(SCREAMING_SNAKE_CASE__ ) ):
self.assertListEqual(
list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , )
divisor *= 2
self.assertEqual(self.model_tester.output_stride , divisor // 2 )
__a , __a = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__a = True
check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__a = True
check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def __a ( self : List[str] ):
'''simple docstring'''
__a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ )
def __a ( self : Optional[int] ):
'''simple docstring'''
__a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE__ )
@slow
def __a ( self : Optional[Any] ):
'''simple docstring'''
for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__a = MobileViTModel.from_pretrained(SCREAMING_SNAKE_CASE__ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
def __lowercase ( ) -> Union[str, Any]:
"""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 : List[str] ):
'''simple docstring'''
return MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small""" ) if is_vision_available() else None
@slow
def __a ( self : List[Any] ):
'''simple docstring'''
__a = MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small""" ).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([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3] ).to(SCREAMING_SNAKE_CASE__ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) )
@slow
def __a ( self : Any ):
'''simple docstring'''
__a = MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" )
__a = model.to(SCREAMING_SNAKE_CASE__ )
__a = MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" )
__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__ )
__a = outputs.logits
# verify the logits
__a = torch.Size((1, 2_1, 3_2, 3_2) )
self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE__ )
__a = torch.tensor(
[
[[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]],
[[-1_0.6_8_6_9, -1_0.3_2_5_0, -1_0.3_4_7_1], [-1_0.4_2_2_8, -9.9_8_6_8, -9.7_1_3_2], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]],
[[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]],
] , device=SCREAMING_SNAKE_CASE__ , )
self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) )
@slow
def __a ( self : Optional[int] ):
'''simple docstring'''
__a = MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" )
__a = model.to(SCREAMING_SNAKE_CASE__ )
__a = MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" )
__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__ )
__a = outputs.logits.detach().cpu()
__a = image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE__ , target_sizes=[(5_0, 6_0)] )
__a = torch.Size((5_0, 6_0) )
self.assertEqual(segmentation[0].shape , SCREAMING_SNAKE_CASE__ )
__a = image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE__ )
__a = torch.Size((3_2, 3_2) )
self.assertEqual(segmentation[0].shape , SCREAMING_SNAKE_CASE__ )
| 582 | 1 |
"""simple docstring"""
def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase = 1000000 ):
_lowercase : Tuple = 1
_lowercase : Optional[int] = 1
_lowercase : Tuple = {1: 1}
for inputa in range(2 , __UpperCAmelCase ):
_lowercase : Dict = 0
_lowercase : Dict = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
_lowercase : Tuple = (3 * number) + 1
counter += 1
if inputa not in counters:
_lowercase : List[Any] = counter
if counter > pre_counter:
_lowercase : Optional[Any] = inputa
_lowercase : Union[str, Any] = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 600 |
"""simple docstring"""
def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ):
global f # a global dp table for knapsack
if f[i][j] < 0:
if j < wt[i - 1]:
_lowercase : Union[str, Any] = mf_knapsack(i - 1 , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
else:
_lowercase : Tuple = max(
mf_knapsack(i - 1 , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) , mf_knapsack(i - 1 , __UpperCAmelCase , __UpperCAmelCase , j - wt[i - 1] ) + val[i - 1] , )
_lowercase : int = val
return f[i][j]
def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ):
_lowercase : Any = [[0] * (w + 1) for _ in range(n + 1 )]
for i in range(1 , n + 1 ):
for w_ in range(1 , w + 1 ):
if wt[i - 1] <= w_:
_lowercase : Optional[Any] = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] )
else:
_lowercase : Union[str, Any] = dp[i - 1][w_]
return dp[n][w_], dp
def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ):
if not (isinstance(__UpperCAmelCase , (list, tuple) ) and isinstance(__UpperCAmelCase , (list, tuple) )):
raise ValueError(
"""Both the weights and values vectors must be either lists or tuples""" )
_lowercase : List[str] = len(__UpperCAmelCase )
if num_items != len(__UpperCAmelCase ):
_lowercase : Union[str, Any] = (
"""The number of weights must be the same as the number of values.\n"""
F"""But got {num_items} weights and {len(__UpperCAmelCase )} values"""
)
raise ValueError(__UpperCAmelCase )
for i in range(__UpperCAmelCase ):
if not isinstance(wt[i] , __UpperCAmelCase ):
_lowercase : List[str] = (
"""All weights must be integers but got weight of """
F"""type {type(wt[i] )} at index {i}"""
)
raise TypeError(__UpperCAmelCase )
_lowercase , _lowercase : Dict = knapsack(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
_lowercase : set = set()
_construct_solution(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
return optimal_val, example_optional_set
def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ):
# for the current item i at a maximum weight j to be part of an optimal subset,
# the optimal value at (i, j) must be greater than the optimal value at (i-1, j).
# where i - 1 means considering only the previous items at the given maximum weight
if i > 0 and j > 0:
if dp[i - 1][j] == dp[i][j]:
_construct_solution(__UpperCAmelCase , __UpperCAmelCase , i - 1 , __UpperCAmelCase , __UpperCAmelCase )
else:
optimal_set.add(__UpperCAmelCase )
_construct_solution(__UpperCAmelCase , __UpperCAmelCase , i - 1 , j - wt[i - 1] , __UpperCAmelCase )
if __name__ == "__main__":
UpperCAmelCase: str = [3, 2, 4, 4]
UpperCAmelCase: Dict = [4, 3, 2, 3]
UpperCAmelCase: Optional[int] = 4
UpperCAmelCase: Optional[int] = 6
UpperCAmelCase: Union[str, Any] = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)]
UpperCAmelCase , UpperCAmelCase: List[Any] = knapsack(w, wt, val, n)
print(optimal_solution)
print(mf_knapsack(n, wt, val, w)) # switched the n and w
# testing the dynamic programming problem with example
# the optimal subset for the above example are items 3 and 4
UpperCAmelCase , UpperCAmelCase: Union[str, Any] = knapsack_with_example_solution(w, wt, val)
assert optimal_solution == 8
assert optimal_subset == {3, 4}
print("""optimal_value = """, optimal_solution)
print("""An optimal subset corresponding to the optimal value""", optimal_subset)
| 600 | 1 |
from __future__ import annotations
import numpy as np
def __UpperCamelCase ( _lowerCAmelCase ) -> tuple[np.ndarray, np.ndarray]:
"""simple docstring"""
A , A : int = np.shape(_lowerCAmelCase )
if rows != columns:
A : Union[str, Any] = (
"""'table' has to be of square shaped array but got a """
f'''{rows}x{columns} array:\n{table}'''
)
raise ValueError(_lowerCAmelCase )
A : Union[str, Any] = np.zeros((rows, columns) )
A : Dict = np.zeros((rows, columns) )
for i in range(_lowerCAmelCase ):
for j in range(_lowerCAmelCase ):
A : Any = sum(lower[i][k] * upper[k][j] for k in range(_lowerCAmelCase ) )
if upper[j][j] == 0:
raise ArithmeticError("""No LU decomposition exists""" )
A : Any = (table[i][j] - total) / upper[j][j]
A : Union[str, Any] = 1
for j in range(_lowerCAmelCase , _lowerCAmelCase ):
A : Any = sum(lower[i][k] * upper[k][j] for k in range(_lowerCAmelCase ) )
A : str = table[i][j] - total
return lower, upper
if __name__ == "__main__":
import doctest
doctest.testmod()
| 662 |
def __UpperCamelCase ( _lowerCAmelCase = 1000 ) -> int:
"""simple docstring"""
A , A : str = 1, 1
A : List[Any] = []
for i in range(1 , n + 1 ):
A : Optional[int] = prev_numerator + 2 * prev_denominator
A : Any = prev_numerator + prev_denominator
if len(str(_lowerCAmelCase ) ) > len(str(_lowerCAmelCase ) ):
result.append(_lowerCAmelCase )
A : int = numerator
A : int = denominator
return len(_lowerCAmelCase )
if __name__ == "__main__":
print(F"""{solution() = }""")
| 662 | 1 |
'''simple docstring'''
from .glue import GlueDataset, GlueDataTrainingArguments
from .language_modeling import (
LineByLineTextDataset,
LineByLineWithRefDataset,
LineByLineWithSOPTextDataset,
TextDataset,
TextDatasetForNextSentencePrediction,
)
from .squad import SquadDataset, SquadDataTrainingArguments
| 720 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available
lowercase__ = {}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase__ = ['''MLukeTokenizer''']
if TYPE_CHECKING:
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mluke import MLukeTokenizer
else:
import sys
lowercase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 420 | 0 |
'''simple docstring'''
import random
import timeit
from functools import wraps
from typing import Callable, Optional
from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
Benchmark,
Memory,
MemorySummary,
measure_peak_memory_cpu,
start_memory_tracing,
stop_memory_tracing,
)
if is_tf_available():
import tensorflow as tf
from tensorflow.python.framework.errors_impl import ResourceExhaustedError
from .benchmark_args_tf import TensorFlowBenchmarkArguments
if is_pyanvml_available():
import pyanvml.pyanvml as nvml
__UpperCamelCase = logging.get_logger(__name__)
def _a ( _lowerCamelCase , _lowerCamelCase ) -> Union[str, Any]:
"""simple docstring"""
def run_func(_lowerCamelCase ):
@wraps(_lowerCamelCase )
def run_in_eager_mode(*_lowerCamelCase , **_lowerCamelCase ):
return func(*_lowerCamelCase , **_lowerCamelCase )
@wraps(_lowerCamelCase )
@tf.function(experimental_compile=_lowerCamelCase )
def run_in_graph_mode(*_lowerCamelCase , **_lowerCamelCase ):
return func(*_lowerCamelCase , **_lowerCamelCase )
if do_eager_mode is True:
if use_xla is not False:
raise ValueError(
"""Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.""" )
return run_in_eager_mode
else:
return run_in_graph_mode
return run_func
def _a ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> ["tf.Tensor"]:
"""simple docstring"""
__snake_case : Dict = random.Random()
__snake_case : str = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )]
return tf.constant(_lowerCamelCase , shape=(batch_size, sequence_length) , dtype=tf.intaa )
class _A ( __lowercase ):
lowercase__: TensorFlowBenchmarkArguments
lowercase__: PretrainedConfig
lowercase__: str = "TensorFlow"
@property
def lowercase__ ( self : Tuple ) -> Dict:
"""simple docstring"""
return tf.__version__
def lowercase__ ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : int , __magic_name__ : int ) -> float:
"""simple docstring"""
__snake_case : Tuple = self.args.strategy
if strategy is None:
raise ValueError("""A device strategy has to be initialized before using TensorFlow.""" )
__snake_case : Any = self._prepare_inference_func(__magic_name__ , __magic_name__ , __magic_name__ )
return self._measure_speed(_inference )
def lowercase__ ( self : Tuple , __magic_name__ : str , __magic_name__ : int , __magic_name__ : int ) -> float:
"""simple docstring"""
__snake_case : Tuple = self.args.strategy
if strategy is None:
raise ValueError("""A device strategy has to be initialized before using TensorFlow.""" )
__snake_case : List[Any] = self._prepare_train_func(__magic_name__ , __magic_name__ , __magic_name__ )
return self._measure_speed(_train )
def lowercase__ ( self : int , __magic_name__ : str , __magic_name__ : int , __magic_name__ : int ) -> [Memory, Optional[MemorySummary]]:
"""simple docstring"""
if self.args.is_gpu:
tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , __magic_name__ )
__snake_case : List[Any] = self.args.strategy
if strategy is None:
raise ValueError("""A device strategy has to be initialized before using TensorFlow.""" )
__snake_case : Optional[Any] = self._prepare_inference_func(__magic_name__ , __magic_name__ , __magic_name__ )
return self._measure_memory(_inference )
def lowercase__ ( self : List[Any] , __magic_name__ : str , __magic_name__ : int , __magic_name__ : int ) -> [Memory, Optional[MemorySummary]]:
"""simple docstring"""
if self.args.is_gpu:
tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , __magic_name__ )
__snake_case : Tuple = self.args.strategy
if strategy is None:
raise ValueError("""A device strategy has to be initialized before using TensorFlow.""" )
__snake_case : List[str] = self._prepare_train_func(__magic_name__ , __magic_name__ , __magic_name__ )
return self._measure_memory(_train )
def lowercase__ ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : int , __magic_name__ : int ) -> Callable[[], None]:
"""simple docstring"""
__snake_case : List[Any] = self.config_dict[model_name]
if self.args.fpaa:
raise NotImplementedError("""Mixed precision is currently not supported.""" )
__snake_case : str = (
hasattr(__magic_name__ , """architectures""" )
and isinstance(config.architectures , __magic_name__ )
and len(config.architectures ) > 0
)
if not self.args.only_pretrain_model and has_model_class_in_config:
try:
__snake_case : List[Any] = """TF""" + config.architectures[0] # prepend 'TF' for tensorflow model
__snake_case : Any = __import__("""transformers""" , fromlist=[model_class] )
__snake_case : Union[str, Any] = getattr(__magic_name__ , __magic_name__ )
__snake_case : Dict = model_cls(__magic_name__ )
except ImportError:
raise ImportError(
f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
""" set `--only_pretrain_model` or `args.only_pretrain_model=True`.""" )
else:
__snake_case : int = TF_MODEL_MAPPING[config.__class__](__magic_name__ )
# encoder-decoder has vocab size saved differently
__snake_case : Optional[int] = config.vocab_size if hasattr(__magic_name__ , """vocab_size""" ) else config.encoder.vocab_size
__snake_case : str = random_input_ids(__magic_name__ , __magic_name__ , __magic_name__ )
@run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla )
def encoder_decoder_forward():
return model(__magic_name__ , decoder_input_ids=__magic_name__ , training=__magic_name__ )
@run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla )
def encoder_forward():
return model(__magic_name__ , training=__magic_name__ )
__snake_case : Any = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward
return _inference
def lowercase__ ( self : Optional[int] , __magic_name__ : str , __magic_name__ : int , __magic_name__ : int ) -> Callable[[], None]:
"""simple docstring"""
__snake_case : Tuple = self.config_dict[model_name]
if self.args.eager_mode is not False:
raise ValueError("""Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.""" )
if self.args.fpaa:
raise NotImplementedError("""Mixed precision is currently not supported.""" )
__snake_case : Optional[int] = (
hasattr(__magic_name__ , """architectures""" )
and isinstance(config.architectures , __magic_name__ )
and len(config.architectures ) > 0
)
if not self.args.only_pretrain_model and has_model_class_in_config:
try:
__snake_case : Optional[int] = """TF""" + config.architectures[0] # prepend 'TF' for tensorflow model
__snake_case : Dict = __import__("""transformers""" , fromlist=[model_class] )
__snake_case : List[Any] = getattr(__magic_name__ , __magic_name__ )
__snake_case : Tuple = model_cls(__magic_name__ )
except ImportError:
raise ImportError(
f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
""" set `--only_pretrain_model` or `args.only_pretrain_model=True`.""" )
else:
__snake_case : Union[str, Any] = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](__magic_name__ )
# encoder-decoder has vocab size saved differently
__snake_case : Optional[Any] = config.vocab_size if hasattr(__magic_name__ , """vocab_size""" ) else config.encoder.vocab_size
__snake_case : List[str] = random_input_ids(__magic_name__ , __magic_name__ , __magic_name__ )
@run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla )
def encoder_decoder_train():
__snake_case : Tuple = model(__magic_name__ , decoder_input_ids=__magic_name__ , labels=__magic_name__ , training=__magic_name__ )[0]
__snake_case : Dict = tf.gradients(__magic_name__ , model.trainable_variables )
return gradients
@run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla )
def encoder_train():
__snake_case : Optional[Any] = model(__magic_name__ , labels=__magic_name__ , training=__magic_name__ )[0]
__snake_case : Optional[int] = tf.gradients(__magic_name__ , model.trainable_variables )
return gradients
__snake_case : str = encoder_decoder_train if config.is_encoder_decoder else encoder_train
return _train
def lowercase__ ( self : str , __magic_name__ : Tuple ) -> float:
"""simple docstring"""
with self.args.strategy.scope():
try:
if self.args.is_tpu or self.args.use_xla:
# run additional 10 times to stabilize compilation for tpu
logger.info("""Do inference on TPU. Running model 5 times to stabilize compilation""" )
timeit.repeat(__magic_name__ , repeat=1 , number=5 )
# as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
__snake_case : Optional[int] = timeit.repeat(
__magic_name__ , repeat=self.args.repeat , number=10 , )
return min(__magic_name__ ) / 10.0
except ResourceExhaustedError as e:
self.print_fn(f'''Doesn\'t fit on GPU. {e}''' )
def lowercase__ ( self : Tuple , __magic_name__ : Callable[[], None] ) -> [Memory, MemorySummary]:
"""simple docstring"""
logger.info(
"""Note that TensorFlow allocates more memory than """
"""it might need to speed up computation. """
"""The memory reported here corresponds to the memory """
"""reported by `nvidia-smi`, which can vary depending """
"""on total available memory on the GPU that is used.""" )
with self.args.strategy.scope():
try:
if self.args.trace_memory_line_by_line:
if not self.args.eager_mode:
raise ValueError(
"""`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory"""
""" consumption line by line.""" )
__snake_case : Dict = start_memory_tracing("""transformers""" )
if self.args.is_tpu:
# tpu
raise NotImplementedError(
"""Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking"""
""" with `args.memory=False`""" )
elif self.args.is_gpu:
# gpu
if not is_pyanvml_available():
logger.warning(
"""py3nvml not installed, we won't log GPU memory usage. """
"""Install py3nvml (pip install py3nvml) to log information about GPU.""" )
__snake_case : int = """N/A"""
else:
logger.info(
"""Measuring total GPU usage on GPU device. Make sure to not have additional processes"""
""" running on the same GPU.""" )
# init nvml
nvml.nvmlInit()
func()
__snake_case : Any = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx )
__snake_case : Union[str, Any] = nvml.nvmlDeviceGetMemoryInfo(__magic_name__ )
__snake_case : Union[str, Any] = meminfo.used
__snake_case : List[Any] = Memory(__magic_name__ )
# shutdown nvml
nvml.nvmlShutdown()
else:
# cpu
if self.args.trace_memory_line_by_line:
logger.info(
"""When enabling line by line tracing, the max peak memory for CPU is inaccurate in"""
""" TensorFlow.""" )
__snake_case : int = None
else:
__snake_case : Dict = measure_peak_memory_cpu(__magic_name__ )
__snake_case : Union[str, Any] = Memory(__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else memory_bytes
if self.args.trace_memory_line_by_line:
__snake_case : Tuple = stop_memory_tracing(__magic_name__ )
if memory is None:
__snake_case : Any = summary.total
else:
__snake_case : Any = None
return memory, summary
except ResourceExhaustedError as e:
self.print_fn(f'''Doesn\'t fit on GPU. {e}''' )
return "N/A", None
| 26 |
'''simple docstring'''
import collections
import inspect
import unittest
from transformers import SwinvaConfig
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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel
from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class __snake_case :
def __init__( self, A, A=13, A=32, A=2, A=3, A=16, A=[1, 2, 1], A=[2, 2, 4], A=2, A=2.0, A=True, A=0.0, A=0.0, A=0.1, A="gelu", A=False, A=True, A=0.02, A=1e-5, A=True, A=None, A=True, A=10, A=8, ):
"""simple docstring"""
lowerCamelCase : int = parent
lowerCamelCase : Optional[Any] = batch_size
lowerCamelCase : List[Any] = image_size
lowerCamelCase : List[Any] = patch_size
lowerCamelCase : List[Any] = num_channels
lowerCamelCase : Tuple = embed_dim
lowerCamelCase : Dict = depths
lowerCamelCase : Optional[Any] = num_heads
lowerCamelCase : Tuple = window_size
lowerCamelCase : str = mlp_ratio
lowerCamelCase : List[str] = qkv_bias
lowerCamelCase : Optional[Any] = hidden_dropout_prob
lowerCamelCase : Any = attention_probs_dropout_prob
lowerCamelCase : Dict = drop_path_rate
lowerCamelCase : Dict = hidden_act
lowerCamelCase : Optional[int] = use_absolute_embeddings
lowerCamelCase : Dict = patch_norm
lowerCamelCase : Union[str, Any] = layer_norm_eps
lowerCamelCase : Optional[int] = initializer_range
lowerCamelCase : Tuple = is_training
lowerCamelCase : Optional[int] = scope
lowerCamelCase : Any = use_labels
lowerCamelCase : List[str] = type_sequence_label_size
lowerCamelCase : Optional[Any] = encoder_stride
def UpperCAmelCase_ ( self ):
"""simple docstring"""
lowerCamelCase : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowerCamelCase : Union[str, Any] = None
if self.use_labels:
lowerCamelCase : str = ids_tensor([self.batch_size], self.type_sequence_label_size )
lowerCamelCase : Union[str, Any] = self.get_config()
return config, pixel_values, labels
def UpperCAmelCase_ ( self ):
"""simple docstring"""
return SwinvaConfig(
image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, embed_dim=self.embed_dim, depths=self.depths, num_heads=self.num_heads, window_size=self.window_size, mlp_ratio=self.mlp_ratio, qkv_bias=self.qkv_bias, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, drop_path_rate=self.drop_path_rate, hidden_act=self.hidden_act, use_absolute_embeddings=self.use_absolute_embeddings, path_norm=self.patch_norm, layer_norm_eps=self.layer_norm_eps, initializer_range=self.initializer_range, encoder_stride=self.encoder_stride, )
def UpperCAmelCase_ ( self, A, A, A ):
"""simple docstring"""
lowerCamelCase : int = SwinvaModel(config=A )
model.to(A )
model.eval()
lowerCamelCase : str = model(A )
lowerCamelCase : List[str] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
lowerCamelCase : List[Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) )
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim) )
def UpperCAmelCase_ ( self, A, A, A ):
"""simple docstring"""
lowerCamelCase : Tuple = SwinvaForMaskedImageModeling(config=A )
model.to(A )
model.eval()
lowerCamelCase : Tuple = model(A )
self.parent.assertEqual(
result.logits.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size) )
# test greyscale images
lowerCamelCase : int = 1
lowerCamelCase : List[str] = SwinvaForMaskedImageModeling(A )
model.to(A )
model.eval()
lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
lowerCamelCase : List[Any] = model(A )
self.parent.assertEqual(result.logits.shape, (self.batch_size, 1, self.image_size, self.image_size) )
def UpperCAmelCase_ ( self, A, A, A ):
"""simple docstring"""
lowerCamelCase : List[str] = self.type_sequence_label_size
lowerCamelCase : int = SwinvaForImageClassification(A )
model.to(A )
model.eval()
lowerCamelCase : List[str] = model(A, labels=A )
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) )
def UpperCAmelCase_ ( self ):
"""simple docstring"""
lowerCamelCase : str = self.prepare_config_and_inputs()
lowerCamelCase , lowerCamelCase , lowerCamelCase : Optional[int] = config_and_inputs
lowerCamelCase : Dict = {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
class __snake_case ( a__ , a__ , unittest.TestCase):
_lowerCAmelCase = (
(SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
)
_lowerCAmelCase = (
{'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification}
if is_torch_available()
else {}
)
_lowerCAmelCase = False
_lowerCAmelCase = False
_lowerCAmelCase = False
_lowerCAmelCase = False
def UpperCAmelCase_ ( self ):
"""simple docstring"""
lowerCamelCase : Union[str, Any] = SwinvaModelTester(self )
lowerCamelCase : Union[str, Any] = ConfigTester(self, config_class=A, embed_dim=37 )
def UpperCAmelCase_ ( self ):
"""simple docstring"""
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def UpperCAmelCase_ ( self ):
"""simple docstring"""
lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*A )
@unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.' )
def UpperCAmelCase_ ( self ):
"""simple docstring"""
pass
@unittest.skip(reason='Swinv2 does not use inputs_embeds' )
def UpperCAmelCase_ ( self ):
"""simple docstring"""
pass
def UpperCAmelCase_ ( self ):
"""simple docstring"""
lowerCamelCase , lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCamelCase : Any = model_class(A )
self.assertIsInstance(model.get_input_embeddings(), (nn.Module) )
lowerCamelCase : Optional[Any] = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(A, nn.Linear ) )
def UpperCAmelCase_ ( self ):
"""simple docstring"""
lowerCamelCase , lowerCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCamelCase : List[Any] = model_class(A )
lowerCamelCase : Any = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowerCamelCase : Dict = [*signature.parameters.keys()]
lowerCamelCase : Tuple = ['pixel_values']
self.assertListEqual(arg_names[:1], A )
def UpperCAmelCase_ ( self ):
"""simple docstring"""
lowerCamelCase , lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase : int = True
for model_class in self.all_model_classes:
lowerCamelCase : Optional[int] = True
lowerCamelCase : List[Any] = False
lowerCamelCase : str = True
lowerCamelCase : Union[str, Any] = model_class(A )
model.to(A )
model.eval()
with torch.no_grad():
lowerCamelCase : Tuple = model(**self._prepare_for_class(A, A ) )
lowerCamelCase : Tuple = outputs.attentions
lowerCamelCase : Union[str, Any] = len(self.model_tester.depths )
self.assertEqual(len(A ), A )
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
lowerCamelCase : List[str] = True
lowerCamelCase : int = config.window_size**2
lowerCamelCase : str = model_class(A )
model.to(A )
model.eval()
with torch.no_grad():
lowerCamelCase : Any = model(**self._prepare_for_class(A, A ) )
lowerCamelCase : str = outputs.attentions
self.assertEqual(len(A ), A )
self.assertListEqual(
list(attentions[0].shape[-3:] ), [self.model_tester.num_heads[0], window_size_squared, window_size_squared], )
lowerCamelCase : Optional[Any] = len(A )
# Check attention is always last and order is fine
lowerCamelCase : List[str] = True
lowerCamelCase : Any = True
lowerCamelCase : Tuple = model_class(A )
model.to(A )
model.eval()
with torch.no_grad():
lowerCamelCase : Optional[Any] = model(**self._prepare_for_class(A, A ) )
if hasattr(self.model_tester, 'num_hidden_states_types' ):
lowerCamelCase : Optional[int] = self.model_tester.num_hidden_states_types
else:
# also another +1 for reshaped_hidden_states
lowerCamelCase : Tuple = 2
self.assertEqual(out_len + added_hidden_states, len(A ) )
lowerCamelCase : int = outputs.attentions
self.assertEqual(len(A ), A )
self.assertListEqual(
list(self_attentions[0].shape[-3:] ), [self.model_tester.num_heads[0], window_size_squared, window_size_squared], )
def UpperCAmelCase_ ( self, A, A, A, A ):
"""simple docstring"""
lowerCamelCase : int = model_class(A )
model.to(A )
model.eval()
with torch.no_grad():
lowerCamelCase : Optional[int] = model(**self._prepare_for_class(A, A ) )
lowerCamelCase : Dict = outputs.hidden_states
lowerCamelCase : List[Any] = getattr(
self.model_tester, 'expected_num_hidden_layers', len(self.model_tester.depths ) + 1 )
self.assertEqual(len(A ), A )
# Swinv2 has a different seq_length
lowerCamelCase : Any = (
config.patch_size
if isinstance(config.patch_size, collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
lowerCamelCase : Union[str, Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.assertListEqual(
list(hidden_states[0].shape[-2:] ), [num_patches, self.model_tester.embed_dim], )
lowerCamelCase : List[Any] = outputs.reshaped_hidden_states
self.assertEqual(len(A ), A )
lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase : Tuple = reshaped_hidden_states[0].shape
lowerCamelCase : Union[str, Any] = (
reshaped_hidden_states[0].view(A, A, height * width ).permute(0, 2, 1 )
)
self.assertListEqual(
list(reshaped_hidden_states.shape[-2:] ), [num_patches, self.model_tester.embed_dim], )
def UpperCAmelCase_ ( self ):
"""simple docstring"""
lowerCamelCase , lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase : int = (
self.model_tester.image_size
if isinstance(self.model_tester.image_size, collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
for model_class in self.all_model_classes:
lowerCamelCase : str = True
self.check_hidden_states_output(A, A, A, A )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowerCamelCase : Dict = True
self.check_hidden_states_output(A, A, A, A )
def UpperCAmelCase_ ( self ):
"""simple docstring"""
lowerCamelCase , lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase : List[Any] = 3
lowerCamelCase : List[str] = (
self.model_tester.image_size
if isinstance(self.model_tester.image_size, collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
lowerCamelCase : str = (
config.patch_size
if isinstance(config.patch_size, collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
lowerCamelCase : Union[str, Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
lowerCamelCase : Union[str, Any] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
for model_class in self.all_model_classes:
lowerCamelCase : Tuple = True
self.check_hidden_states_output(A, A, A, (padded_height, padded_width) )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowerCamelCase : List[str] = True
self.check_hidden_states_output(A, A, A, (padded_height, padded_width) )
def UpperCAmelCase_ ( self ):
"""simple docstring"""
lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*A )
def UpperCAmelCase_ ( self ):
"""simple docstring"""
lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*A )
@slow
def UpperCAmelCase_ ( self ):
"""simple docstring"""
for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCamelCase : Any = SwinvaModel.from_pretrained(A )
self.assertIsNotNone(A )
def UpperCAmelCase_ ( self ):
"""simple docstring"""
lowerCamelCase , lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase : Tuple = _config_zero_init(A )
for model_class in self.all_model_classes:
lowerCamelCase : Any = model_class(config=A )
for name, param in model.named_parameters():
if "embeddings" not in name and "logit_scale" not in name and param.requires_grad:
self.assertIn(
((param.data.mean() * 1e9).round() / 1e9).item(), [0.0, 1.0], msg=F'''Parameter {name} of model {model_class} seems not properly initialized''', )
@require_vision
@require_torch
class __snake_case ( unittest.TestCase):
@cached_property
def UpperCAmelCase_ ( self ):
"""simple docstring"""
return (
AutoImageProcessor.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' )
if is_vision_available()
else None
)
@slow
def UpperCAmelCase_ ( self ):
"""simple docstring"""
lowerCamelCase : Tuple = SwinvaForImageClassification.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ).to(
A )
lowerCamelCase : Union[str, Any] = self.default_image_processor
lowerCamelCase : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
lowerCamelCase : Any = image_processor(images=A, return_tensors='pt' ).to(A )
# forward pass
with torch.no_grad():
lowerCamelCase : Any = model(**A )
# verify the logits
lowerCamelCase : Optional[Any] = torch.Size((1, 1000) )
self.assertEqual(outputs.logits.shape, A )
lowerCamelCase : List[Any] = torch.tensor([-0.3947, -0.4306, 0.0026] ).to(A )
self.assertTrue(torch.allclose(outputs.logits[0, :3], A, atol=1e-4 ) )
| 320 | 0 |
# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
# and https://github.com/hojonathanho/diffusion
import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.schedulers.scheduling_utils import SchedulerMixin
from diffusers.utils import BaseOutput, deprecate
@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
class A__ ( __SCREAMING_SNAKE_CASE ):
lowerCamelCase__ : torch.FloatTensor
lowerCamelCase__ : Optional[torch.FloatTensor] =None
def lowerCAmelCase ( UpperCAmelCase, UpperCAmelCase=0.9_99, UpperCAmelCase="cosine", ) ->Optional[Any]:
"""simple docstring"""
if alpha_transform_type == "cosine":
def alpha_bar_fn(UpperCAmelCase ):
return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2
elif alpha_transform_type == "exp":
def alpha_bar_fn(UpperCAmelCase ):
return math.exp(t * -12.0 )
else:
raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' )
__magic_name__ : List[Any] = []
for i in range(UpperCAmelCase ):
__magic_name__ : Tuple = i / num_diffusion_timesteps
__magic_name__ : Optional[Any] = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar_fn(UpperCAmelCase ) / alpha_bar_fn(UpperCAmelCase ), UpperCAmelCase ) )
return torch.tensor(UpperCAmelCase, dtype=torch.floataa )
class A__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
lowerCamelCase__ : Union[str, Any] =1
@register_to_config
def __init__( self , lowerCamelCase = 1000 , lowerCamelCase = 0.0_0_0_1 , lowerCamelCase = 0.0_2 , lowerCamelCase = "linear" , lowerCamelCase = None , lowerCamelCase = True , lowerCamelCase = True , lowerCamelCase = 0 , lowerCamelCase = "epsilon" , lowerCamelCase = 1.0 , **lowerCamelCase , ) -> Optional[Any]:
"""simple docstring"""
if kwargs.get('''set_alpha_to_one''' , lowerCamelCase ) is not None:
__magic_name__ : Any = (
'''The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.'''
)
deprecate('''set_alpha_to_one''' , '''1.0.0''' , lowerCamelCase , standard_warn=lowerCamelCase )
__magic_name__ : Tuple = kwargs['''set_alpha_to_one''']
if trained_betas is not None:
__magic_name__ : Any = torch.tensor(lowerCamelCase , dtype=torch.floataa )
elif beta_schedule == "linear":
__magic_name__ : Union[str, Any] = torch.linspace(lowerCamelCase , lowerCamelCase , lowerCamelCase , dtype=torch.floataa )
elif beta_schedule == "scaled_linear":
# this schedule is very specific to the latent diffusion model.
__magic_name__ : str = (
torch.linspace(beta_start**0.5 , beta_end**0.5 , lowerCamelCase , dtype=torch.floataa ) ** 2
)
elif beta_schedule == "squaredcos_cap_v2":
# Glide cosine schedule
__magic_name__ : List[str] = betas_for_alpha_bar(lowerCamelCase )
else:
raise NotImplementedError(F'''{beta_schedule} does is not implemented for {self.__class__}''' )
__magic_name__ : Dict = 1.0 - self.betas
__magic_name__ : List[str] = torch.cumprod(self.alphas , dim=0 )
# At every step in inverted ddim, we are looking into the next alphas_cumprod
# For the final step, there is no next alphas_cumprod, and the index is out of bounds
# `set_alpha_to_zero` decides whether we set this parameter simply to zero
# in this case, self.step() just output the predicted noise
# or whether we use the final alpha of the "non-previous" one.
__magic_name__ : str = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1]
# standard deviation of the initial noise distribution
__magic_name__ : int = 1.0
# setable values
__magic_name__ : List[str] = None
__magic_name__ : Dict = torch.from_numpy(np.arange(0 , lowerCamelCase ).copy().astype(np.intaa ) )
def lowercase ( self , lowerCamelCase , lowerCamelCase = None ) -> torch.FloatTensor:
"""simple docstring"""
return sample
def lowercase ( self , lowerCamelCase , lowerCamelCase = None ) -> Tuple:
"""simple docstring"""
if num_inference_steps > self.config.num_train_timesteps:
raise ValueError(
F'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:'''
F''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle'''
F''' maximal {self.config.num_train_timesteps} timesteps.''' )
__magic_name__ : int = num_inference_steps
__magic_name__ : Tuple = self.config.num_train_timesteps // self.num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
__magic_name__ : Any = (np.arange(0 , lowerCamelCase ) * step_ratio).round().copy().astype(np.intaa )
__magic_name__ : Optional[int] = torch.from_numpy(lowerCamelCase ).to(lowerCamelCase )
self.timesteps += self.config.steps_offset
def lowercase ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = 0.0 , lowerCamelCase = False , lowerCamelCase = None , lowerCamelCase = True , ) -> Union[DDIMSchedulerOutput, Tuple]:
"""simple docstring"""
__magic_name__ : Dict = timestep + self.config.num_train_timesteps // self.num_inference_steps
# 2. compute alphas, betas
# change original implementation to exactly match noise levels for analogous forward process
__magic_name__ : List[Any] = self.alphas_cumprod[timestep]
__magic_name__ : str = (
self.alphas_cumprod[prev_timestep]
if prev_timestep < self.config.num_train_timesteps
else self.final_alpha_cumprod
)
__magic_name__ : Any = 1 - alpha_prod_t
# 3. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
if self.config.prediction_type == "epsilon":
__magic_name__ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
__magic_name__ : Union[str, Any] = model_output
elif self.config.prediction_type == "sample":
__magic_name__ : Dict = model_output
__magic_name__ : Optional[int] = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5
elif self.config.prediction_type == "v_prediction":
__magic_name__ : Optional[int] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
__magic_name__ : Optional[int] = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
else:
raise ValueError(
F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or'''
''' `v_prediction`''' )
# 4. Clip or threshold "predicted x_0"
if self.config.clip_sample:
__magic_name__ : Any = pred_original_sample.clamp(
-self.config.clip_sample_range , self.config.clip_sample_range )
# 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
__magic_name__ : Union[str, Any] = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon
# 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
__magic_name__ : Optional[Any] = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction
if not return_dict:
return (prev_sample, pred_original_sample)
return DDIMSchedulerOutput(prev_sample=lowerCamelCase , pred_original_sample=lowerCamelCase )
def __len__( self ) -> int:
"""simple docstring"""
return self.config.num_train_timesteps
| 336 |
def lowerCAmelCase ( UpperCAmelCase ) ->list[int]:
"""simple docstring"""
if num <= 0:
raise ValueError('''Input must be a positive integer''' )
__magic_name__ : List[str] = [True] * (num + 1)
__magic_name__ : List[Any] = 2
while p * p <= num:
if primes[p]:
for i in range(p * p, num + 1, UpperCAmelCase ):
__magic_name__ : Any = False
p += 1
return [prime for prime in range(2, num + 1 ) if primes[prime]]
if __name__ == "__main__":
import doctest
doctest.testmod()
lowercase_ = int(input('''Enter a positive integer: ''').strip())
print(prime_sieve_eratosthenes(user_num))
| 336 | 1 |
'''simple docstring'''
import math
def __lowercase (_lowercase ) -> bool:
"""simple docstring"""
assert isinstance(_lowercase, _lowercase ) and (
number >= 0
), "'number' must been an int and positive"
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or not number % 2:
# Negatives, 0, 1 and all even numbers are not primes
return False
__lowerCamelCase : List[str] = range(3, int(math.sqrt(_lowercase ) + 1 ), 2 )
return not any(not number % i for i in odd_numbers )
def __lowercase (_lowercase, _lowercase=1, **_lowercase ) -> Tuple:
"""simple docstring"""
__lowerCamelCase : Optional[int] = factor * value
__lowerCamelCase : str = value
while not is_prime(_lowercase ):
value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1
if value == first_value_val:
return next_prime(value + 1, **_lowercase )
return value
| 150 |
'''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
UpperCAmelCase__ :Union[str, Any] = {
"""configuration_mgp_str""": ["""MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MgpstrConfig"""],
"""processing_mgp_str""": ["""MgpstrProcessor"""],
"""tokenization_mgp_str""": ["""MgpstrTokenizer"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase__ :int = [
"""MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""MgpstrModel""",
"""MgpstrPreTrainedModel""",
"""MgpstrForSceneTextRecognition""",
]
if TYPE_CHECKING:
from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig
from .processing_mgp_str import MgpstrProcessor
from .tokenization_mgp_str import MgpstrTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mgp_str import (
MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST,
MgpstrForSceneTextRecognition,
MgpstrModel,
MgpstrPreTrainedModel,
)
else:
import sys
UpperCAmelCase__ :Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 150 | 1 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCamelCase = {
"""configuration_bigbird_pegasus""": [
"""BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""BigBirdPegasusConfig""",
"""BigBirdPegasusOnnxConfig""",
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase = [
"""BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""BigBirdPegasusForCausalLM""",
"""BigBirdPegasusForConditionalGeneration""",
"""BigBirdPegasusForQuestionAnswering""",
"""BigBirdPegasusForSequenceClassification""",
"""BigBirdPegasusModel""",
"""BigBirdPegasusPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_bigbird_pegasus import (
BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP,
BigBirdPegasusConfig,
BigBirdPegasusOnnxConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_bigbird_pegasus import (
BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST,
BigBirdPegasusForCausalLM,
BigBirdPegasusForConditionalGeneration,
BigBirdPegasusForQuestionAnswering,
BigBirdPegasusForSequenceClassification,
BigBirdPegasusModel,
BigBirdPegasusPreTrainedModel,
)
else:
import sys
UpperCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 120 |
"""simple docstring"""
from math import factorial
def A( snake_case_ = 20 ):
"""simple docstring"""
lowercase__: Tuple = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1,
# 2, 3,...
lowercase__: int = n // 2
return int(factorial(snake_case_ ) / (factorial(snake_case_ ) * factorial(n - k )) )
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
print(solution(20))
else:
try:
UpperCamelCase = int(sys.argv[1])
print(solution(n))
except ValueError:
print("""Invalid entry - please enter a number.""")
| 120 | 1 |
'''simple docstring'''
import argparse
import json
from pathlib import Path
import requests
import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
_SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
def __a(SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Union[str, Any]=False ):
'''simple docstring'''
_lowerCAmelCase = []
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'''deit.encoder.layer.{i}.layernorm_before.weight''') )
rename_keys.append((F'''blocks.{i}.norm1.bias''', F'''deit.encoder.layer.{i}.layernorm_before.bias''') )
rename_keys.append((F'''blocks.{i}.attn.proj.weight''', F'''deit.encoder.layer.{i}.attention.output.dense.weight''') )
rename_keys.append((F'''blocks.{i}.attn.proj.bias''', F'''deit.encoder.layer.{i}.attention.output.dense.bias''') )
rename_keys.append((F'''blocks.{i}.norm2.weight''', F'''deit.encoder.layer.{i}.layernorm_after.weight''') )
rename_keys.append((F'''blocks.{i}.norm2.bias''', F'''deit.encoder.layer.{i}.layernorm_after.bias''') )
rename_keys.append((F'''blocks.{i}.mlp.fc1.weight''', F'''deit.encoder.layer.{i}.intermediate.dense.weight''') )
rename_keys.append((F'''blocks.{i}.mlp.fc1.bias''', F'''deit.encoder.layer.{i}.intermediate.dense.bias''') )
rename_keys.append((F'''blocks.{i}.mlp.fc2.weight''', F'''deit.encoder.layer.{i}.output.dense.weight''') )
rename_keys.append((F'''blocks.{i}.mlp.fc2.bias''', F'''deit.encoder.layer.{i}.output.dense.bias''') )
# projection layer + position embeddings
rename_keys.extend(
[
("cls_token", "deit.embeddings.cls_token"),
("dist_token", "deit.embeddings.distillation_token"),
("patch_embed.proj.weight", "deit.embeddings.patch_embeddings.projection.weight"),
("patch_embed.proj.bias", "deit.embeddings.patch_embeddings.projection.bias"),
("pos_embed", "deit.embeddings.position_embeddings"),
] )
if base_model:
# layernorm + pooler
rename_keys.extend(
[
("norm.weight", "layernorm.weight"),
("norm.bias", "layernorm.bias"),
("pre_logits.fc.weight", "pooler.dense.weight"),
("pre_logits.fc.bias", "pooler.dense.bias"),
] )
# if just the base model, we should remove "deit" from all keys that start with "deit"
_lowerCAmelCase = [(pair[0], pair[1][4:]) if pair[1].startswith("deit" ) else pair for pair in rename_keys]
else:
# layernorm + classification heads
rename_keys.extend(
[
("norm.weight", "deit.layernorm.weight"),
("norm.bias", "deit.layernorm.bias"),
("head.weight", "cls_classifier.weight"),
("head.bias", "cls_classifier.bias"),
("head_dist.weight", "distillation_classifier.weight"),
("head_dist.bias", "distillation_classifier.bias"),
] )
return rename_keys
def __a(SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : int=False ):
'''simple docstring'''
for i in range(config.num_hidden_layers ):
if base_model:
_lowerCAmelCase = ""
else:
_lowerCAmelCase = "deit."
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
_lowerCAmelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' )
_lowerCAmelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' )
# next, add query, keys and values (in that order) to the state dict
_lowerCAmelCase = in_proj_weight[
: config.hidden_size, :
]
_lowerCAmelCase = in_proj_bias[: config.hidden_size]
_lowerCAmelCase = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
_lowerCAmelCase = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
_lowerCAmelCase = in_proj_weight[
-config.hidden_size :, :
]
_lowerCAmelCase = in_proj_bias[-config.hidden_size :]
def __a(SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : int ):
'''simple docstring'''
_lowerCAmelCase = dct.pop(SCREAMING_SNAKE_CASE_ )
_lowerCAmelCase = val
def __a():
'''simple docstring'''
_lowerCAmelCase = "http://images.cocodataset.org/val2017/000000039769.jpg"
_lowerCAmelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw )
return im
@torch.no_grad()
def __a(SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : int ):
'''simple docstring'''
_lowerCAmelCase = DeiTConfig()
# all deit models have fine-tuned heads
_lowerCAmelCase = False
# dataset (fine-tuned on ImageNet 2012), patch_size and image_size
_lowerCAmelCase = 1000
_lowerCAmelCase = "huggingface/label-files"
_lowerCAmelCase = "imagenet-1k-id2label.json"
_lowerCAmelCase = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type="dataset" ) , "r" ) )
_lowerCAmelCase = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()}
_lowerCAmelCase = idalabel
_lowerCAmelCase = {v: k for k, v in idalabel.items()}
_lowerCAmelCase = int(deit_name[-6:-4] )
_lowerCAmelCase = int(deit_name[-3:] )
# size of the architecture
if deit_name[9:].startswith("tiny" ):
_lowerCAmelCase = 192
_lowerCAmelCase = 768
_lowerCAmelCase = 12
_lowerCAmelCase = 3
elif deit_name[9:].startswith("small" ):
_lowerCAmelCase = 384
_lowerCAmelCase = 1536
_lowerCAmelCase = 12
_lowerCAmelCase = 6
if deit_name[9:].startswith("base" ):
pass
elif deit_name[4:].startswith("large" ):
_lowerCAmelCase = 1024
_lowerCAmelCase = 4096
_lowerCAmelCase = 24
_lowerCAmelCase = 16
# load original model from timm
_lowerCAmelCase = timm.create_model(SCREAMING_SNAKE_CASE_ , pretrained=SCREAMING_SNAKE_CASE_ )
timm_model.eval()
# load state_dict of original model, remove and rename some keys
_lowerCAmelCase = timm_model.state_dict()
_lowerCAmelCase = create_rename_keys(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
for src, dest in rename_keys:
rename_key(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
read_in_q_k_v(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# load HuggingFace model
_lowerCAmelCase = DeiTForImageClassificationWithTeacher(SCREAMING_SNAKE_CASE_ ).eval()
model.load_state_dict(SCREAMING_SNAKE_CASE_ )
# Check outputs on an image, prepared by DeiTImageProcessor
_lowerCAmelCase = int(
(256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103
_lowerCAmelCase = DeiTImageProcessor(size=SCREAMING_SNAKE_CASE_ , crop_size=config.image_size )
_lowerCAmelCase = image_processor(images=prepare_img() , return_tensors="pt" )
_lowerCAmelCase = encoding["pixel_values"]
_lowerCAmelCase = model(SCREAMING_SNAKE_CASE_ )
_lowerCAmelCase = timm_model(SCREAMING_SNAKE_CASE_ )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(SCREAMING_SNAKE_CASE_ , outputs.logits , atol=1e-3 )
Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ )
print(F'''Saving model {deit_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(SCREAMING_SNAKE_CASE_ )
print(F'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(SCREAMING_SNAKE_CASE_ )
if __name__ == "__main__":
_SCREAMING_SNAKE_CASE = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--deit_name",
default="vit_deit_base_distilled_patch16_224",
type=str,
help="Name of the DeiT timm model you'd like to convert.",
)
parser.add_argument(
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
)
_SCREAMING_SNAKE_CASE = parser.parse_args()
convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
| 18 |
'''simple docstring'''
import re
import string
import numpy as np
import datasets
_SCREAMING_SNAKE_CASE = "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n"
_SCREAMING_SNAKE_CASE = "\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results[\"exact_match\"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 33.3\n\n"
_SCREAMING_SNAKE_CASE = "\n"
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION )
class lowerCAmelCase_ ( datasets.Metric ):
def _snake_case ( self ) -> List[str]:
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"predictions": datasets.Value("string" , id="sequence" ),
"references": datasets.Value("string" , id="sequence" ),
} ) , reference_urls=[] , )
def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=None , _lowerCAmelCase=False , _lowerCAmelCase=False , _lowerCAmelCase=False , ) -> str:
if regexes_to_ignore is not None:
for s in regexes_to_ignore:
_lowerCAmelCase = np.array([re.sub(_lowerCAmelCase , "" , _lowerCAmelCase ) for x in predictions] )
_lowerCAmelCase = np.array([re.sub(_lowerCAmelCase , "" , _lowerCAmelCase ) for x in references] )
else:
_lowerCAmelCase = np.asarray(_lowerCAmelCase )
_lowerCAmelCase = np.asarray(_lowerCAmelCase )
if ignore_case:
_lowerCAmelCase = np.char.lower(_lowerCAmelCase )
_lowerCAmelCase = np.char.lower(_lowerCAmelCase )
if ignore_punctuation:
_lowerCAmelCase = string.punctuation.maketrans("" , "" , string.punctuation )
_lowerCAmelCase = np.char.translate(_lowerCAmelCase , table=_lowerCAmelCase )
_lowerCAmelCase = np.char.translate(_lowerCAmelCase , table=_lowerCAmelCase )
if ignore_numbers:
_lowerCAmelCase = string.digits.maketrans("" , "" , string.digits )
_lowerCAmelCase = np.char.translate(_lowerCAmelCase , table=_lowerCAmelCase )
_lowerCAmelCase = np.char.translate(_lowerCAmelCase , table=_lowerCAmelCase )
_lowerCAmelCase = predictions == references
return {"exact_match": np.mean(_lowerCAmelCase ) * 100}
| 18 | 1 |
'''simple docstring'''
import logging
import os
from .state import PartialState
class a__ ( logging.LoggerAdapter ):
'''simple docstring'''
@staticmethod
def __SCREAMING_SNAKE_CASE ( lowerCamelCase_ ) -> Tuple:
lowerCAmelCase__ = PartialState()
return not main_process_only or (main_process_only and state.is_main_process)
def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , *lowerCamelCase_ , **lowerCamelCase_ ) -> int:
if PartialState._shared_state == {}:
raise RuntimeError(
'''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' )
lowerCAmelCase__ = kwargs.pop('''main_process_only''' , lowerCamelCase_ )
lowerCAmelCase__ = kwargs.pop('''in_order''' , lowerCamelCase_ )
if self.isEnabledFor(lowerCamelCase_ ):
if self._should_log(lowerCamelCase_ ):
lowerCAmelCase__ , lowerCAmelCase__ = self.process(lowerCamelCase_ , lowerCamelCase_ )
self.logger.log(lowerCamelCase_ , lowerCamelCase_ , *lowerCamelCase_ , **lowerCamelCase_ )
elif in_order:
lowerCAmelCase__ = PartialState()
for i in range(state.num_processes ):
if i == state.process_index:
lowerCAmelCase__ , lowerCAmelCase__ = self.process(lowerCamelCase_ , lowerCamelCase_ )
self.logger.log(lowerCamelCase_ , lowerCamelCase_ , *lowerCamelCase_ , **lowerCamelCase_ )
state.wait_for_everyone()
def _snake_case ( A , A = None ) -> Any:
if log_level is None:
lowerCAmelCase__ = os.environ.get('''ACCELERATE_LOG_LEVEL''' , A )
lowerCAmelCase__ = logging.getLogger(A )
if log_level is not None:
logger.setLevel(log_level.upper() )
logger.root.setLevel(log_level.upper() )
return MultiProcessAdapter(A , {} ) | 710 |
'''simple docstring'''
def _snake_case ( A ) -> int:
return 1 if digit in (0, 1) else (digit * factorial(digit - 1 ))
def _snake_case ( A ) -> bool:
lowerCAmelCase__ = 0
lowerCAmelCase__ = number
while duplicate > 0:
lowerCAmelCase__ , lowerCAmelCase__ = divmod(A , 10 )
fact_sum += factorial(A )
return fact_sum == number
if __name__ == "__main__":
print('''Program to check whether a number is a Krisnamurthy Number or not.''')
__UpperCAmelCase = int(input('''Enter number: ''').strip())
print(
f"""{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number."""
) | 98 | 0 |
"""simple docstring"""
import json
import os
from typing import Optional, Tuple
import regex as re
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
a__ : Optional[int] = logging.get_logger(__name__)
a__ : str = {
"vocab_file": "vocab.json",
"merges_file": "merges.txt",
}
a__ : str = {
"vocab_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json"},
"merges_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt"},
}
a__ : List[str] = {
"ctrl": 2_5_6,
}
a__ : int = {
"Pregnancy": 1_6_8_6_2_9,
"Christianity": 7_6_7_5,
"Explain": 1_0_6_4_2_3,
"Fitness": 6_3_4_4_0,
"Saving": 6_3_1_6_3,
"Ask": 2_7_1_7_1,
"Ass": 9_5_9_8_5,
"Joke": 1_6_3_5_0_9,
"Questions": 4_5_6_2_2,
"Thoughts": 4_9_6_0_5,
"Retail": 5_2_3_4_2,
"Feminism": 1_6_4_3_3_8,
"Writing": 1_1_9_9_2,
"Atheism": 1_9_2_2_6_3,
"Netflix": 4_8_6_1_6,
"Computing": 3_9_6_3_9,
"Opinion": 4_3_2_1_3,
"Alone": 4_4_9_6_7,
"Funny": 5_8_9_1_7,
"Gaming": 4_0_3_5_8,
"Human": 4_0_8_8,
"India": 1_3_3_1,
"Joker": 7_7_1_3_8,
"Diet": 3_6_2_0_6,
"Legal": 1_1_8_5_9,
"Norman": 4_9_3_9,
"Tip": 7_2_6_8_9,
"Weight": 5_2_3_4_3,
"Movies": 4_6_2_7_3,
"Running": 2_3_4_2_5,
"Science": 2_0_9_0,
"Horror": 3_7_7_9_3,
"Confession": 6_0_5_7_2,
"Finance": 1_2_2_5_0,
"Politics": 1_6_3_6_0,
"Scary": 1_9_1_9_8_5,
"Support": 1_2_6_5_4,
"Technologies": 3_2_5_1_6,
"Teenage": 6_6_1_6_0,
"Event": 3_2_7_6_9,
"Learned": 6_7_4_6_0,
"Notion": 1_8_2_7_7_0,
"Wikipedia": 3_7_5_8_3,
"Books": 6_6_6_5,
"Extract": 7_6_0_5_0,
"Confessions": 1_0_2_7_0_1,
"Conspiracy": 7_5_9_3_2,
"Links": 6_3_6_7_4,
"Narcissus": 1_5_0_4_2_5,
"Relationship": 5_4_7_6_6,
"Relationships": 1_3_4_7_9_6,
"Reviews": 4_1_6_7_1,
"News": 4_2_5_6,
"Translation": 2_6_8_2_0,
"multilingual": 1_2_8_4_0_6,
}
def UpperCAmelCase__ (lowerCAmelCase_ ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = set()
__SCREAMING_SNAKE_CASE = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
__SCREAMING_SNAKE_CASE = char
__SCREAMING_SNAKE_CASE = set(lowercase__ )
return pairs
class UpperCamelCase_ ( snake_case__):
"""simple docstring"""
snake_case__ : int = VOCAB_FILES_NAMES
snake_case__ : str = PRETRAINED_VOCAB_FILES_MAP
snake_case__ : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case__ : Optional[int] = CONTROL_CODES
def __init__( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any]="<unk>" , **UpperCAmelCase__ : Tuple ) -> Any:
super().__init__(unk_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
with open(SCREAMING_SNAKE_CASE_ , encoding="utf-8" ) as vocab_handle:
__SCREAMING_SNAKE_CASE = json.load(SCREAMING_SNAKE_CASE_ )
__SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()}
with open(SCREAMING_SNAKE_CASE_ , 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 merges]
__SCREAMING_SNAKE_CASE = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) )
__SCREAMING_SNAKE_CASE = {}
@property
def UpperCAmelCase_ ( self : List[str] ) -> Dict:
return len(self.encoder )
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Dict:
return dict(self.encoder , **self.added_tokens_encoder )
def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Any ) -> Optional[Any]:
if token in self.cache:
return self.cache[token]
__SCREAMING_SNAKE_CASE = tuple(SCREAMING_SNAKE_CASE_ )
__SCREAMING_SNAKE_CASE = tuple(list(word[:-1] ) + [word[-1] + "</w>"] )
__SCREAMING_SNAKE_CASE = get_pairs(SCREAMING_SNAKE_CASE_ )
if not pairs:
return token
while True:
__SCREAMING_SNAKE_CASE = min(SCREAMING_SNAKE_CASE_ , key=lambda UpperCAmelCase__ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE_ , 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(SCREAMING_SNAKE_CASE_ ):
try:
__SCREAMING_SNAKE_CASE = word.index(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
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(SCREAMING_SNAKE_CASE_ ) - 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(SCREAMING_SNAKE_CASE_ )
__SCREAMING_SNAKE_CASE = new_word
if len(SCREAMING_SNAKE_CASE_ ) == 1:
break
else:
__SCREAMING_SNAKE_CASE = get_pairs(SCREAMING_SNAKE_CASE_ )
__SCREAMING_SNAKE_CASE = "@@ ".join(SCREAMING_SNAKE_CASE_ )
__SCREAMING_SNAKE_CASE = word[:-4]
__SCREAMING_SNAKE_CASE = word
return word
def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]:
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = re.findall(R"\S+\n?" , SCREAMING_SNAKE_CASE_ )
for token in words:
split_tokens.extend(list(self.bpe(SCREAMING_SNAKE_CASE_ ).split(" " ) ) )
return split_tokens
def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Any ) -> int:
return self.encoder.get(SCREAMING_SNAKE_CASE_ , self.encoder.get(self.unk_token ) )
def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : List[Any] ) -> Dict:
return self.decoder.get(SCREAMING_SNAKE_CASE_ , self.unk_token )
def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : str ) -> List[Any]:
__SCREAMING_SNAKE_CASE = " ".join(SCREAMING_SNAKE_CASE_ ).replace("@@ " , "" ).strip()
return out_string
def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> str:
if not os.path.isdir(SCREAMING_SNAKE_CASE_ ):
logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" )
return
__SCREAMING_SNAKE_CASE = os.path.join(
SCREAMING_SNAKE_CASE_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
__SCREAMING_SNAKE_CASE = os.path.join(
SCREAMING_SNAKE_CASE_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] )
with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) + "\n" )
__SCREAMING_SNAKE_CASE = 0
with open(SCREAMING_SNAKE_CASE_ , "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 UpperCAmelCase__ : 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(SCREAMING_SNAKE_CASE_ ) + "\n" )
index += 1
return vocab_file, merge_file
# def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
# filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
# tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
# tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
# return ''.join(tokens_generated_so_far)
| 682 |
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run
import doctest
import sys
import warnings
from os.path import abspath, dirname, join
import _pytest
from transformers.testing_utils import HfDoctestModule, HfDocTestParser
# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
_UpperCAmelCase : Optional[Any] = abspath(join(dirname(__file__), "src"))
sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action="ignore", category=FutureWarning)
def lowerCAmelCase_ (lowercase__ : Union[str, Any] ) -> List[str]:
'''simple docstring'''
config.addinivalue_line(
'''markers''' , '''is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested''' )
config.addinivalue_line(
'''markers''' , '''is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested''' )
config.addinivalue_line('''markers''' , '''is_pipeline_test: mark test to run only when pipelines are tested''' )
config.addinivalue_line('''markers''' , '''is_staging_test: mark test to run only in the staging environment''' )
config.addinivalue_line('''markers''' , '''accelerate_tests: mark test that require accelerate''' )
config.addinivalue_line('''markers''' , '''tool_tests: mark the tool tests that are run on their specific schedule''' )
def lowerCAmelCase_ (lowercase__ : Optional[Any] ) -> Optional[int]:
'''simple docstring'''
from transformers.testing_utils import pytest_addoption_shared
pytest_addoption_shared(lowercase__ )
def lowerCAmelCase_ (lowercase__ : Any ) -> Optional[int]:
'''simple docstring'''
from transformers.testing_utils import pytest_terminal_summary_main
lowerCAmelCase__ = terminalreporter.config.getoption('''--make-reports''' )
if make_reports:
pytest_terminal_summary_main(lowercase__ , id=lowercase__ )
def lowerCAmelCase_ (lowercase__ : List[Any] , lowercase__ : int ) -> int:
'''simple docstring'''
if exitstatus == 5:
lowerCAmelCase__ = 0
# Doctest custom flag to ignore output.
_UpperCAmelCase : Any = doctest.register_optionflag("IGNORE_RESULT")
_UpperCAmelCase : Dict = doctest.OutputChecker
class lowerCAmelCase_ ( snake_case__ ):
def __snake_case ( self : Dict , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ):
if IGNORE_RESULT & optionflags:
return True
return OutputChecker.check_output(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase : Union[str, Any] = CustomOutputChecker
_UpperCAmelCase : Dict = HfDoctestModule
_UpperCAmelCase : List[str] = HfDocTestParser
| 668 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCamelCase__: Union[str, Any] = {
"configuration_lilt": ["LILT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LiltConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__: List[str] = [
"LILT_PRETRAINED_MODEL_ARCHIVE_LIST",
"LiltForQuestionAnswering",
"LiltForSequenceClassification",
"LiltForTokenClassification",
"LiltModel",
"LiltPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_lilt import (
LILT_PRETRAINED_MODEL_ARCHIVE_LIST,
LiltForQuestionAnswering,
LiltForSequenceClassification,
LiltForTokenClassification,
LiltModel,
LiltPreTrainedModel,
)
else:
import sys
UpperCamelCase__: Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 528 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCamelCase__: Union[str, Any] = {
"configuration_lilt": ["LILT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LiltConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__: List[str] = [
"LILT_PRETRAINED_MODEL_ARCHIVE_LIST",
"LiltForQuestionAnswering",
"LiltForSequenceClassification",
"LiltForTokenClassification",
"LiltModel",
"LiltPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_lilt import (
LILT_PRETRAINED_MODEL_ARCHIVE_LIST,
LiltForQuestionAnswering,
LiltForSequenceClassification,
LiltForTokenClassification,
LiltModel,
LiltPreTrainedModel,
)
else:
import sys
UpperCamelCase__: Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 528 | 1 |
import inspect
import re
from hashlib import shaaaa
from typing import Dict, List
from .arrow import arrow
from .audiofolder import audiofolder
from .csv import csv
from .imagefolder import imagefolder
from .json import json
from .pandas import pandas
from .parquet import parquet
from .sql import sql # noqa F401
from .text import text
def UpperCAmelCase__ ( lowerCamelCase_ : List[str] ):
__a : List[Any] = []
for line in lines:
__a : Optional[Any] = re.sub(R'#.*' , '' , lowerCamelCase_ ) # remove comments
if line:
filtered_lines.append(lowerCamelCase_ )
__a : Optional[Any] = '\n'.join(lowerCamelCase_ )
# Make a hash from all this code
__a : Optional[Any] = full_str.encode('utf-8' )
return shaaaa(lowerCamelCase_ ).hexdigest()
# get importable module names and hash for caching
SCREAMING_SNAKE_CASE__ = {
'''csv''': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())),
'''json''': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())),
'''pandas''': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())),
'''parquet''': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())),
'''arrow''': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())),
'''text''': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())),
'''imagefolder''': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())),
'''audiofolder''': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())),
}
# Used to infer the module to use based on the data files extensions
SCREAMING_SNAKE_CASE__ = {
'''.csv''': ('''csv''', {}),
'''.tsv''': ('''csv''', {'''sep''': '''\t'''}),
'''.json''': ('''json''', {}),
'''.jsonl''': ('''json''', {}),
'''.parquet''': ('''parquet''', {}),
'''.arrow''': ('''arrow''', {}),
'''.txt''': ('''text''', {}),
}
_EXTENSION_TO_MODULE.update({ext: ('''imagefolder''', {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ('''imagefolder''', {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext: ('''audiofolder''', {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ('''audiofolder''', {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
SCREAMING_SNAKE_CASE__ = {'''imagefolder''', '''audiofolder'''}
# Used to filter data files based on extensions given a module name
SCREAMING_SNAKE_CASE__ = {}
for _ext, (_module, _) in _EXTENSION_TO_MODULE.items():
_MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext)
_MODULE_TO_EXTENSIONS["imagefolder"].append('''.zip''')
_MODULE_TO_EXTENSIONS["audiofolder"].append('''.zip''')
| 47 |
"""simple docstring"""
from typing import Optional
import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACTaFN
from ...modeling_outputs import (
BackboneOutput,
BaseModelOutputWithNoAttention,
BaseModelOutputWithPoolingAndNoAttention,
ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig
a_ : int = logging.get_logger(__name__)
# General docstring
a_ : Union[str, Any] = '''ResNetConfig'''
# Base docstring
a_ : int = '''microsoft/resnet-50'''
a_ : str = [1, 20_48, 7, 7]
# Image classification docstring
a_ : Dict = '''microsoft/resnet-50'''
a_ : Optional[Any] = '''tiger cat'''
a_ : Optional[Any] = [
'''microsoft/resnet-50''',
# See all resnet models at https://huggingface.co/models?filter=resnet
]
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a , __a , __a = 3 , __a = 1 , __a = "relu" ):
super().__init__()
__lowerCamelCase : List[Any] = nn.Convad(
__a , __a , kernel_size=__a , stride=__a , padding=kernel_size // 2 , bias=__a )
__lowerCamelCase : Union[str, Any] = nn.BatchNormad(__a )
__lowerCamelCase : List[str] = ACTaFN[activation] if activation is not None else nn.Identity()
def snake_case_ ( self , __a ):
__lowerCamelCase : Dict = self.convolution(__a )
__lowerCamelCase : str = self.normalization(__a )
__lowerCamelCase : str = self.activation(__a )
return hidden_state
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a ):
super().__init__()
__lowerCamelCase : str = ResNetConvLayer(
config.num_channels , config.embedding_size , kernel_size=7 , stride=2 , activation=config.hidden_act )
__lowerCamelCase : Union[str, Any] = nn.MaxPoolad(kernel_size=3 , stride=2 , padding=1 )
__lowerCamelCase : Optional[Any] = config.num_channels
def snake_case_ ( self , __a ):
__lowerCamelCase : int = pixel_values.shape[1]
if num_channels != self.num_channels:
raise ValueError(
'Make sure that the channel dimension of the pixel values match with the one set in the configuration.' )
__lowerCamelCase : str = self.embedder(__a )
__lowerCamelCase : List[Any] = self.pooler(__a )
return embedding
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a , __a , __a = 2 ):
super().__init__()
__lowerCamelCase : Dict = nn.Convad(__a , __a , kernel_size=1 , stride=__a , bias=__a )
__lowerCamelCase : int = nn.BatchNormad(__a )
def snake_case_ ( self , __a ):
__lowerCamelCase : List[Any] = self.convolution(__a )
__lowerCamelCase : Any = self.normalization(__a )
return hidden_state
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a , __a , __a = 1 , __a = "relu" ):
super().__init__()
__lowerCamelCase : Optional[Any] = in_channels != out_channels or stride != 1
__lowerCamelCase : str = (
ResNetShortCut(__a , __a , stride=__a ) if should_apply_shortcut else nn.Identity()
)
__lowerCamelCase : Optional[Any] = nn.Sequential(
ResNetConvLayer(__a , __a , stride=__a ) , ResNetConvLayer(__a , __a , activation=__a ) , )
__lowerCamelCase : Dict = ACTaFN[activation]
def snake_case_ ( self , __a ):
__lowerCamelCase : Optional[int] = hidden_state
__lowerCamelCase : Optional[Any] = self.layer(__a )
__lowerCamelCase : str = self.shortcut(__a )
hidden_state += residual
__lowerCamelCase : List[str] = self.activation(__a )
return hidden_state
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a , __a , __a = 1 , __a = "relu" , __a = 4 ):
super().__init__()
__lowerCamelCase : str = in_channels != out_channels or stride != 1
__lowerCamelCase : str = out_channels // reduction
__lowerCamelCase : Optional[Any] = (
ResNetShortCut(__a , __a , stride=__a ) if should_apply_shortcut else nn.Identity()
)
__lowerCamelCase : Union[str, Any] = nn.Sequential(
ResNetConvLayer(__a , __a , kernel_size=1 ) , ResNetConvLayer(__a , __a , stride=__a ) , ResNetConvLayer(__a , __a , kernel_size=1 , activation=__a ) , )
__lowerCamelCase : Optional[int] = ACTaFN[activation]
def snake_case_ ( self , __a ):
__lowerCamelCase : str = hidden_state
__lowerCamelCase : Optional[int] = self.layer(__a )
__lowerCamelCase : Optional[Any] = self.shortcut(__a )
hidden_state += residual
__lowerCamelCase : Any = self.activation(__a )
return hidden_state
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a , __a , __a , __a = 2 , __a = 2 , ):
super().__init__()
__lowerCamelCase : Optional[Any] = ResNetBottleNeckLayer if config.layer_type == 'bottleneck' else ResNetBasicLayer
__lowerCamelCase : List[Any] = nn.Sequential(
# downsampling is done in the first layer with stride of 2
layer(__a , __a , stride=__a , activation=config.hidden_act ) , *[layer(__a , __a , activation=config.hidden_act ) for _ in range(depth - 1 )] , )
def snake_case_ ( self , __a ):
__lowerCamelCase : int = input
for layer in self.layers:
__lowerCamelCase : Union[str, Any] = layer(__a )
return hidden_state
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a ):
super().__init__()
__lowerCamelCase : Any = nn.ModuleList([] )
# based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
self.stages.append(
ResNetStage(
__a , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) )
__lowerCamelCase : Any = zip(config.hidden_sizes , config.hidden_sizes[1:] )
for (in_channels, out_channels), depth in zip(__a , config.depths[1:] ):
self.stages.append(ResNetStage(__a , __a , __a , depth=__a ) )
def snake_case_ ( self , __a , __a = False , __a = True ):
__lowerCamelCase : List[Any] = () if output_hidden_states else None
for stage_module in self.stages:
if output_hidden_states:
__lowerCamelCase : Dict = hidden_states + (hidden_state,)
__lowerCamelCase : List[str] = stage_module(__a )
if output_hidden_states:
__lowerCamelCase : Dict = hidden_states + (hidden_state,)
if not return_dict:
return tuple(v for v in [hidden_state, hidden_states] if v is not None )
return BaseModelOutputWithNoAttention(
last_hidden_state=__a , hidden_states=__a , )
class __lowercase( lowercase__ ):
'''simple docstring'''
__a : int = ResNetConfig
__a : str = 'resnet'
__a : List[str] = 'pixel_values'
__a : List[Any] = True
def snake_case_ ( self , __a ):
if isinstance(__a , nn.Convad ):
nn.init.kaiming_normal_(module.weight , mode='fan_out' , nonlinearity='relu' )
elif isinstance(__a , (nn.BatchNormad, nn.GroupNorm) ):
nn.init.constant_(module.weight , 1 )
nn.init.constant_(module.bias , 0 )
def snake_case_ ( self , __a , __a=False ):
if isinstance(__a , __a ):
__lowerCamelCase : Optional[Any] = value
a_ : Dict = R'''
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.
Parameters:
config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''
a_ : List[str] = R'''
Args:
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
[`ConvNextImageProcessor.__call__`] for details.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
'''
@add_start_docstrings(
'The bare ResNet model outputting raw features without any specific head on top.' , lowercase__ , )
class __lowercase( lowercase__ ):
'''simple docstring'''
def __init__( self , __a ):
super().__init__(__a )
__lowerCamelCase : List[str] = config
__lowerCamelCase : int = ResNetEmbeddings(__a )
__lowerCamelCase : Optional[Any] = ResNetEncoder(__a )
__lowerCamelCase : int = nn.AdaptiveAvgPoolad((1, 1) )
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(__a )
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC , output_type=__a , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , )
def snake_case_ ( self , __a , __a = None , __a = None ):
__lowerCamelCase : str = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
__lowerCamelCase : str = return_dict if return_dict is not None else self.config.use_return_dict
__lowerCamelCase : int = self.embedder(__a )
__lowerCamelCase : Optional[int] = self.encoder(
__a , output_hidden_states=__a , return_dict=__a )
__lowerCamelCase : Any = encoder_outputs[0]
__lowerCamelCase : Dict = self.pooler(__a )
if not return_dict:
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=__a , pooler_output=__a , hidden_states=encoder_outputs.hidden_states , )
@add_start_docstrings(
'\n ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , lowercase__ , )
class __lowercase( lowercase__ ):
'''simple docstring'''
def __init__( self , __a ):
super().__init__(__a )
__lowerCamelCase : str = config.num_labels
__lowerCamelCase : Tuple = ResNetModel(__a )
# classification head
__lowerCamelCase : str = nn.Sequential(
nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , )
# initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(__a )
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , )
def snake_case_ ( self , __a = None , __a = None , __a = None , __a = None , ):
__lowerCamelCase : str = return_dict if return_dict is not None else self.config.use_return_dict
__lowerCamelCase : Dict = self.resnet(__a , output_hidden_states=__a , return_dict=__a )
__lowerCamelCase : Any = outputs.pooler_output if return_dict else outputs[1]
__lowerCamelCase : List[Any] = self.classifier(__a )
__lowerCamelCase : Optional[Any] = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
__lowerCamelCase : Any = 'regression'
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
__lowerCamelCase : Optional[int] = 'single_label_classification'
else:
__lowerCamelCase : Dict = 'multi_label_classification'
if self.config.problem_type == "regression":
__lowerCamelCase : List[str] = MSELoss()
if self.num_labels == 1:
__lowerCamelCase : Optional[int] = loss_fct(logits.squeeze() , labels.squeeze() )
else:
__lowerCamelCase : Union[str, Any] = loss_fct(__a , __a )
elif self.config.problem_type == "single_label_classification":
__lowerCamelCase : List[str] = CrossEntropyLoss()
__lowerCamelCase : int = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
elif self.config.problem_type == "multi_label_classification":
__lowerCamelCase : int = BCEWithLogitsLoss()
__lowerCamelCase : List[Any] = loss_fct(__a , __a )
if not return_dict:
__lowerCamelCase : Dict = (logits,) + outputs[2:]
return (loss,) + output if loss is not None else output
return ImageClassifierOutputWithNoAttention(loss=__a , logits=__a , hidden_states=outputs.hidden_states )
@add_start_docstrings(
'\n ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n ' , lowercase__ , )
class __lowercase( lowercase__ , lowercase__ ):
'''simple docstring'''
def __init__( self , __a ):
super().__init__(__a )
super()._init_backbone(__a )
__lowerCamelCase : Tuple = [config.embedding_size] + config.hidden_sizes
__lowerCamelCase : str = ResNetEmbeddings(__a )
__lowerCamelCase : Optional[int] = ResNetEncoder(__a )
# initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(__a )
@replace_return_docstrings(output_type=__a , config_class=_CONFIG_FOR_DOC )
def snake_case_ ( self , __a , __a = None , __a = None ):
__lowerCamelCase : Any = return_dict if return_dict is not None else self.config.use_return_dict
__lowerCamelCase : Optional[int] = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
__lowerCamelCase : List[str] = self.embedder(__a )
__lowerCamelCase : Optional[Any] = self.encoder(__a , output_hidden_states=__a , return_dict=__a )
__lowerCamelCase : int = outputs.hidden_states
__lowerCamelCase : List[Any] = ()
for idx, stage in enumerate(self.stage_names ):
if stage in self.out_features:
feature_maps += (hidden_states[idx],)
if not return_dict:
__lowerCamelCase : List[str] = (feature_maps,)
if output_hidden_states:
output += (outputs.hidden_states,)
return output
return BackboneOutput(
feature_maps=__a , hidden_states=outputs.hidden_states if output_hidden_states else None , attentions=__a , )
| 594 | 0 |
from itertools import count
def _lowerCamelCase ( SCREAMING_SNAKE_CASE = 50 ):
'''simple docstring'''
A_ = [1] * min_block_length
for n in count(SCREAMING_SNAKE_CASE ):
fill_count_functions.append(1 )
for block_length in range(SCREAMING_SNAKE_CASE , n + 1 ):
for block_start in range(n - block_length ):
fill_count_functions[n] += fill_count_functions[
n - block_start - block_length - 1
]
fill_count_functions[n] += 1
if fill_count_functions[n] > 1000000:
break
return n
if __name__ == "__main__":
print(f'{solution() = }')
| 714 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, logging
__lowercase = logging.get_logger(__name__)
class _lowercase ( __lowerCamelCase ):
_lowercase : Optional[Any] = ['pixel_values']
def __init__( self : List[str] , lowerCamelCase__ : bool = True , lowerCamelCase__ : Optional[Dict[str, int]] = None , lowerCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , lowerCamelCase__ : bool = True , lowerCamelCase__ : Dict[str, int] = None , lowerCamelCase__ : bool = True , lowerCamelCase__ : Union[int, float] = 1 / 2_5_5 , lowerCamelCase__ : bool = True , lowerCamelCase__ : Optional[Union[float, List[float]]] = None , lowerCamelCase__ : Optional[Union[float, List[float]]] = None , **lowerCamelCase__ : str , ) -> None:
"""simple docstring"""
super().__init__(**lowerCamelCase__ )
A_ = size if size is not None else {'''shortest_edge''': 2_5_6}
A_ = get_size_dict(lowerCamelCase__ , default_to_square=lowerCamelCase__ )
A_ = crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
A_ = get_size_dict(lowerCamelCase__ )
A_ = do_resize
A_ = size
A_ = resample
A_ = do_center_crop
A_ = crop_size
A_ = do_rescale
A_ = rescale_factor
A_ = do_normalize
A_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
A_ = image_std if image_std is not None else IMAGENET_STANDARD_STD
def UpperCamelCase ( self : List[Any] , lowerCamelCase__ : np.ndarray , lowerCamelCase__ : Dict[str, int] , lowerCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase__ : Optional[int] , ) -> np.ndarray:
"""simple docstring"""
A_ = get_size_dict(lowerCamelCase__ , default_to_square=lowerCamelCase__ )
if "shortest_edge" not in size:
raise ValueError(F"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" )
A_ = get_resize_output_image_size(lowerCamelCase__ , size=size['''shortest_edge'''] , default_to_square=lowerCamelCase__ )
return resize(lowerCamelCase__ , size=lowerCamelCase__ , resample=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ )
def UpperCamelCase ( self : Optional[int] , lowerCamelCase__ : np.ndarray , lowerCamelCase__ : Dict[str, int] , lowerCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase__ : Union[str, Any] , ) -> np.ndarray:
"""simple docstring"""
A_ = get_size_dict(lowerCamelCase__ )
return center_crop(lowerCamelCase__ , size=(size['''height'''], size['''width''']) , data_format=lowerCamelCase__ , **lowerCamelCase__ )
def UpperCamelCase ( self : Any , lowerCamelCase__ : np.ndarray , lowerCamelCase__ : float , lowerCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase__ : Union[str, Any] ) -> np.ndarray:
"""simple docstring"""
return rescale(lowerCamelCase__ , scale=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ )
def UpperCamelCase ( self : Optional[Any] , lowerCamelCase__ : np.ndarray , lowerCamelCase__ : Union[float, List[float]] , lowerCamelCase__ : Union[float, List[float]] , lowerCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase__ : Dict , ) -> np.ndarray:
"""simple docstring"""
return normalize(lowerCamelCase__ , mean=lowerCamelCase__ , std=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ )
def UpperCamelCase ( self : Optional[int] , lowerCamelCase__ : ImageInput , lowerCamelCase__ : Optional[bool] = None , lowerCamelCase__ : Dict[str, int] = None , lowerCamelCase__ : PILImageResampling = None , lowerCamelCase__ : bool = None , lowerCamelCase__ : Dict[str, int] = None , lowerCamelCase__ : Optional[bool] = None , lowerCamelCase__ : Optional[float] = None , lowerCamelCase__ : Optional[bool] = None , lowerCamelCase__ : Optional[Union[float, List[float]]] = None , lowerCamelCase__ : Optional[Union[float, List[float]]] = None , lowerCamelCase__ : Optional[Union[str, TensorType]] = None , lowerCamelCase__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **lowerCamelCase__ : Dict , ) -> Dict:
"""simple docstring"""
A_ = do_resize if do_resize is not None else self.do_resize
A_ = size if size is not None else self.size
A_ = get_size_dict(lowerCamelCase__ , default_to_square=lowerCamelCase__ )
A_ = resample if resample is not None else self.resample
A_ = do_center_crop if do_center_crop is not None else self.do_center_crop
A_ = crop_size if crop_size is not None else self.crop_size
A_ = get_size_dict(lowerCamelCase__ )
A_ = do_rescale if do_rescale is not None else self.do_rescale
A_ = rescale_factor if rescale_factor is not None else self.rescale_factor
A_ = do_normalize if do_normalize is not None else self.do_normalize
A_ = image_mean if image_mean is not None else self.image_mean
A_ = image_std if image_std is not None else self.image_std
A_ = 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.
A_ = [to_numpy_array(lowerCamelCase__ ) for image in images]
if do_resize:
A_ = [self.resize(image=lowerCamelCase__ , size=lowerCamelCase__ , resample=lowerCamelCase__ ) for image in images]
if do_center_crop:
A_ = [self.center_crop(image=lowerCamelCase__ , size=lowerCamelCase__ ) for image in images]
if do_rescale:
A_ = [self.rescale(image=lowerCamelCase__ , scale=lowerCamelCase__ ) for image in images]
if do_normalize:
A_ = [self.normalize(image=lowerCamelCase__ , mean=lowerCamelCase__ , std=lowerCamelCase__ ) for image in images]
A_ = [to_channel_dimension_format(lowerCamelCase__ , lowerCamelCase__ ) for image in images]
A_ = {'''pixel_values''': images}
return BatchFeature(data=lowerCamelCase__ , tensor_type=lowerCamelCase__ )
| 563 | 0 |
from __future__ import annotations
import os
from typing import Any
import requests
_lowerCAmelCase : Optional[Any] = "https://api.github.com"
# https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user
_lowerCAmelCase : Union[str, Any] = BASE_URL + "/user"
# https://github.com/settings/tokens
_lowerCAmelCase : str = os.environ.get("USER_TOKEN", "")
def UpperCamelCase_( _snake_case : str ):
"""simple docstring"""
__a ={
'Authorization': F'token {auth_token}',
'Accept': 'application/vnd.github.v3+json',
}
return requests.get(_snake_case , headers=_snake_case ).json()
if __name__ == "__main__": # pragma: no cover
if USER_TOKEN:
for key, value in fetch_github_info(USER_TOKEN).items():
print(f'''{key}: {value}''')
else:
raise ValueError("'USER_TOKEN' field cannot be empty.")
| 242 |
import argparse
import os
import torch
from transformers import FlavaConfig, FlavaForPreTraining
from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint
def UpperCamelCase_( _snake_case : Optional[Any] ):
"""simple docstring"""
return sum(param.float().sum() if 'encoder.embeddings' not in key else 0 for key, param in state_dict.items() )
def UpperCamelCase_( _snake_case : List[str] , _snake_case : Optional[int] ):
"""simple docstring"""
__a ={}
for key, value in state_dict.items():
if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key:
continue
__a =key.replace('heads.cmd.mim_head.cls.predictions' , 'mmm_image_head' )
__a =key.replace('heads.cmd.mlm_head.cls.predictions' , 'mmm_text_head' )
__a =key.replace('heads.cmd.itm_head.cls' , 'itm_head' )
__a =key.replace('heads.cmd.itm_head.pooler' , 'itm_head.pooler' )
__a =key.replace('heads.cmd.clip_head.logit_scale' , 'flava.logit_scale' )
__a =key.replace('heads.fairseq_mlm.cls.predictions' , 'mlm_head' )
__a =key.replace('heads.imagenet.mim_head.cls.predictions' , 'mim_head' )
__a =key.replace('mm_text_projection' , 'flava.text_to_mm_projection' )
__a =key.replace('mm_image_projection' , 'flava.image_to_mm_projection' )
__a =key.replace('image_encoder.module' , 'flava.image_model' )
__a =key.replace('text_encoder.module' , 'flava.text_model' )
__a =key.replace('mm_encoder.module.encoder.cls_token' , 'flava.multimodal_model.cls_token' )
__a =key.replace('mm_encoder.module' , 'flava.multimodal_model' )
__a =key.replace('text_projection' , 'flava.text_projection' )
__a =key.replace('image_projection' , 'flava.image_projection' )
__a =value.float()
for key, value in codebook_state_dict.items():
__a =value
return upgrade
@torch.no_grad()
def UpperCamelCase_( _snake_case : int , _snake_case : Tuple , _snake_case : Tuple , _snake_case : int=None ):
"""simple docstring"""
if config_path is not None:
__a =FlavaConfig.from_pretrained(_snake_case )
else:
__a =FlavaConfig()
__a =FlavaForPreTraining(_snake_case ).eval()
__a =convert_dalle_checkpoint(_snake_case , _snake_case , save_checkpoint=_snake_case )
if os.path.exists(_snake_case ):
__a =torch.load(_snake_case , map_location='cpu' )
else:
__a =torch.hub.load_state_dict_from_url(_snake_case , map_location='cpu' )
__a =upgrade_state_dict(_snake_case , _snake_case )
hf_model.load_state_dict(_snake_case )
__a =hf_model.state_dict()
__a =count_parameters(_snake_case )
__a =count_parameters(_snake_case ) + count_parameters(_snake_case )
assert torch.allclose(_snake_case , _snake_case , atol=1e-3 )
hf_model.save_pretrained(_snake_case )
if __name__ == "__main__":
_lowerCAmelCase : List[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 flava checkpoint")
parser.add_argument("--codebook_path", default=None, type=str, help="Path to flava codebook checkpoint")
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
_lowerCAmelCase : List[Any] = parser.parse_args()
convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
| 242 | 1 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class a__ ( __SCREAMING_SNAKE_CASE ):
_A = ["image_processor", "tokenizer"]
_A = "CLIPImageProcessor"
_A = ("CLIPTokenizer", "CLIPTokenizerFast")
def __init__( self : List[Any] , A_ : Dict=None , A_ : Optional[Any]=None , **A_ : str ) -> int:
"""simple docstring"""
lowerCamelCase_: Dict = None
if "feature_extractor" in kwargs:
warnings.warn(
"""The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
""" instead.""" , A_ , )
lowerCamelCase_: Union[str, Any] = kwargs.pop("""feature_extractor""" )
lowerCamelCase_: str = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("""You need to specify an `image_processor`.""" )
if tokenizer is None:
raise ValueError("""You need to specify a `tokenizer`.""" )
super().__init__(A_ , A_ )
def __call__( self : Optional[Any] , A_ : int=None , A_ : Tuple=None , A_ : List[Any]=None , **A_ : Any ) -> int:
"""simple docstring"""
if text is None and images is None:
raise ValueError("""You have to specify either text or images. Both cannot be none.""" )
if text is not None:
lowerCamelCase_: Optional[Any] = self.tokenizer(A_ , return_tensors=A_ , **A_ )
if images is not None:
lowerCamelCase_: List[Any] = self.image_processor(A_ , return_tensors=A_ , **A_ )
if text is not None and images is not None:
lowerCamelCase_: Dict = image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**A_ ) , tensor_type=A_ )
def lowerCAmelCase ( self : str , *A_ : Dict , **A_ : Optional[int] ) -> Union[str, Any]:
"""simple docstring"""
return self.tokenizer.batch_decode(*A_ , **A_ )
def lowerCAmelCase ( self : Tuple , *A_ : str , **A_ : int ) -> int:
"""simple docstring"""
return self.tokenizer.decode(*A_ , **A_ )
@property
def lowerCAmelCase ( self : Any ) -> int:
"""simple docstring"""
lowerCamelCase_: List[Any] = self.tokenizer.model_input_names
lowerCamelCase_: Union[str, Any] = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
@property
def lowerCAmelCase ( self : int ) -> int:
"""simple docstring"""
warnings.warn(
"""`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , A_ , )
return self.image_processor_class
@property
def lowerCAmelCase ( self : List[str] ) -> Tuple:
"""simple docstring"""
warnings.warn(
"""`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , A_ , )
return self.image_processor
| 719 | import json
import os
from typing import Dict, List, Optional, Tuple
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
lowercase : Optional[Any] = logging.get_logger(__name__)
lowercase : Union[str, Any] = {
"""vocab_file""": """vocab.json""",
"""tokenizer_config_file""": """tokenizer_config.json""",
"""merges_file""": """merges.txt""",
}
lowercase : Optional[int] = {
"""vocab_file""": {
"""facebook/s2t-wav2vec2-large-en-de""": (
"""https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json"""
),
},
"""tokenizer_config_file""": {
"""facebook/s2t-wav2vec2-large-en-de""": (
"""https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json"""
),
},
"""merges_file""": {
"""facebook/s2t-wav2vec2-large-en-de""": (
"""https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt"""
),
},
}
lowercase : List[Any] = """</w>"""
lowercase : str = """@@ """
def UpperCAmelCase_ ( _UpperCAmelCase ):
lowerCamelCase_: List[Any] = set()
lowerCamelCase_: Union[str, Any] = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
lowerCamelCase_: Any = char
return pairs
# Speech2Text2 has no max input length
lowercase : List[Any] = {"""facebook/s2t-wav2vec2-large-en-de""": 1_0_2_4}
class a__ ( __SCREAMING_SNAKE_CASE ):
_A = VOCAB_FILES_NAMES
_A = PRETRAINED_VOCAB_FILES_MAP
_A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_A = ["input_ids", "attention_mask"]
def __init__( self : Union[str, Any] , A_ : Optional[Any] , A_ : Any="<s>" , A_ : Union[str, Any]="<pad>" , A_ : Optional[int]="</s>" , A_ : Tuple="<unk>" , A_ : List[Any]=False , A_ : Dict=None , **A_ : List[Any] , ) -> Any:
"""simple docstring"""
super().__init__(
unk_token=A_ , bos_token=A_ , eos_token=A_ , pad_token=A_ , do_lower_case=A_ , **A_ , )
lowerCamelCase_: int = do_lower_case
with open(A_ , encoding="""utf-8""" ) as vocab_handle:
lowerCamelCase_: Union[str, Any] = json.load(A_ )
lowerCamelCase_: Any = {v: k for k, v in self.encoder.items()}
if merges_file is None:
logger.info(f"""No merges files provided. {self.__class__.__name__} can only be used for decoding.""" )
lowerCamelCase_: int = None
lowerCamelCase_: Union[str, Any] = None
else:
with open(A_ , encoding="""utf-8""" ) as merges_handle:
lowerCamelCase_: Optional[Any] = merges_handle.read().split("""\n""" )[:-1]
lowerCamelCase_: List[Any] = [tuple(merge.split()[:2] ) for merge in merges]
lowerCamelCase_: Union[str, Any] = dict(zip(A_ , range(len(A_ ) ) ) )
lowerCamelCase_: int = {}
@property
def lowerCAmelCase ( self : Tuple ) -> int:
"""simple docstring"""
return len(self.decoder )
def lowerCAmelCase ( self : Optional[int] ) -> Dict:
"""simple docstring"""
return dict(self.encoder , **self.added_tokens_encoder )
def lowerCAmelCase ( self : Tuple , A_ : List[str] ) -> Tuple:
"""simple docstring"""
lowerCamelCase_: Optional[Any] = tuple(token[:-1] ) + (token[-1] + BPE_TOKEN_MERGES,)
if token in self.cache:
return self.cache[token]
lowerCamelCase_: List[str] = get_pairs(A_ )
if not pairs:
return token
while True:
lowerCamelCase_: Optional[int] = min(A_ , key=lambda A_ : self.bpe_ranks.get(A_ , float("""inf""" ) ) )
if bigram not in self.bpe_ranks:
break
lowerCamelCase_ , lowerCamelCase_: Union[str, Any] = bigram
lowerCamelCase_: Optional[Any] = []
lowerCamelCase_: Any = 0
while i < len(A_ ):
try:
lowerCamelCase_: Optional[Any] = word.index(A_ , A_ )
except ValueError:
new_word.extend(word[i:] )
break
else:
new_word.extend(word[i:j] )
lowerCamelCase_: Tuple = j
if word[i] == first and i < len(A_ ) - 1 and word[i + 1] == second:
new_word.append(first + second )
i += 2
else:
new_word.append(word[i] )
i += 1
lowerCamelCase_: Dict = tuple(A_ )
lowerCamelCase_: Union[str, Any] = new_word
if len(A_ ) == 1:
break
else:
lowerCamelCase_: List[Any] = get_pairs(A_ )
lowerCamelCase_: Optional[Any] = """ """.join(A_ )
if word == "\n " + BPE_TOKEN_MERGES:
lowerCamelCase_: int = """\n""" + BPE_TOKEN_MERGES
if word.endswith(A_ ):
lowerCamelCase_: str = word.replace(A_ , """""" )
lowerCamelCase_: Optional[Any] = word.replace(""" """ , A_ )
lowerCamelCase_: Optional[Any] = word
return word
def lowerCAmelCase ( self : int , A_ : Union[str, Any] ) -> str:
"""simple docstring"""
if self.bpe_ranks is None:
raise ValueError(
"""This tokenizer was instantiated without a `merges.txt` file, so"""
""" that it can only be used for decoding, not for encoding."""
"""Make sure to provide `merges.txt` file at instantiation to enable """
"""encoding.""" )
if self.do_lower_case:
lowerCamelCase_: Optional[int] = text.lower()
lowerCamelCase_: Dict = text.split()
lowerCamelCase_: Any = []
for token in text:
if token:
split_tokens.extend(list(self.bpe(A_ ).split(""" """ ) ) )
return split_tokens
def lowerCAmelCase ( self : List[str] , A_ : str ) -> int:
"""simple docstring"""
return self.encoder.get(A_ , self.encoder.get(self.unk_token ) )
def lowerCAmelCase ( self : Dict , A_ : int ) -> str:
"""simple docstring"""
lowerCamelCase_: int = self.decoder.get(A_ , self.unk_token )
return result
def lowerCAmelCase ( self : List[Any] , A_ : List[str] ) -> str:
"""simple docstring"""
lowerCamelCase_: str = """ """.join(A_ )
# make sure @@ tokens are concatenated
lowerCamelCase_: Dict = """""".join(string.split(A_ ) )
return string
def lowerCAmelCase ( self : Tuple , A_ : str , A_ : Optional[str] = None ) -> Tuple[str]:
"""simple docstring"""
if not os.path.isdir(A_ ):
logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" )
return
lowerCamelCase_: List[str] = os.path.join(
A_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )
lowerCamelCase_: str = os.path.join(
A_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] )
with open(A_ , """w""" , encoding="""utf-8""" ) as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=A_ , ensure_ascii=A_ ) + """\n""" )
lowerCamelCase_: Any = 0
if self.bpe_ranks is None:
return (vocab_file,)
with open(A_ , """w""" , encoding="""utf-8""" ) as writer:
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda A_ : kv[1] ):
if index != token_index:
logger.warning(
f"""Saving vocabulary to {merges_file}: BPE merge indices are not consecutive."""
""" Please check that the tokenizer is not corrupted!""" )
lowerCamelCase_: str = token_index
writer.write(""" """.join(A_ ) + """\n""" )
index += 1
return (vocab_file, merges_file)
| 584 | 0 |
import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional
import pyarrow as pa
import pyarrow.json as paj
import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline
__lowerCamelCase : int = datasets.utils.logging.get_logger(__name__)
@dataclass
class SCREAMING_SNAKE_CASE__ ( datasets.BuilderConfig ):
"""simple docstring"""
a_ = None
a_ = "utf-8"
a_ = None
a_ = None
a_ = True # deprecated
a_ = None # deprecated
a_ = 1_0 << 2_0 # 10MB
a_ = None
class SCREAMING_SNAKE_CASE__ ( datasets.ArrowBasedBuilder ):
"""simple docstring"""
a_ = JsonConfig
def _lowercase ( self : Optional[Any] ):
if self.config.block_size is not None:
logger.warning("The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead" )
snake_case__ : Any = self.config.block_size
if self.config.use_threads is not True:
logger.warning(
"The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore." )
if self.config.newlines_in_values is not None:
raise ValueError("The JSON loader parameter `newlines_in_values` is no longer supported" )
return datasets.DatasetInfo(features=self.config.features )
def _lowercase ( self : int , __A : Optional[int] ):
if not self.config.data_files:
raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' )
snake_case__ : List[Any] = dl_manager.download_and_extract(self.config.data_files )
if isinstance(__A , (str, list, tuple) ):
snake_case__ : Any = data_files
if isinstance(__A , __A ):
snake_case__ : Any = [files]
snake_case__ : List[str] = [dl_manager.iter_files(__A ) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files} )]
snake_case__ : Any = []
for split_name, files in data_files.items():
if isinstance(__A , __A ):
snake_case__ : List[Any] = [files]
snake_case__ : Optional[int] = [dl_manager.iter_files(__A ) for file in files]
splits.append(datasets.SplitGenerator(name=__A , gen_kwargs={"files": files} ) )
return splits
def _lowercase ( self : Optional[Any] , __A : pa.Table ):
if self.config.features is not None:
# adding missing columns
for column_name in set(self.config.features ) - set(pa_table.column_names ):
snake_case__ : Any = self.config.features.arrow_schema.field(__A ).type
snake_case__ : List[str] = pa_table.append_column(__A , pa.array([None] * len(__A ) , type=__A ) )
# more expensive cast to support nested structures with keys in a different order
# allows str <-> int/float or str to Audio for example
snake_case__ : List[str] = table_cast(__A , self.config.features.arrow_schema )
return pa_table
def _lowercase ( self : List[Any] , __A : List[str] ):
for file_idx, file in enumerate(itertools.chain.from_iterable(__A ) ):
# If the file is one json object and if we need to look at the list of items in one specific field
if self.config.field is not None:
with open(__A , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f:
snake_case__ : List[Any] = json.load(__A )
# We keep only the field we are interested in
snake_case__ : List[str] = dataset[self.config.field]
# We accept two format: a list of dicts or a dict of lists
if isinstance(__A , (list, tuple) ):
snake_case__ : List[Any] = set().union(*[row.keys() for row in dataset] )
snake_case__ : Optional[Any] = {col: [row.get(__A ) for row in dataset] for col in keys}
else:
snake_case__ : List[str] = dataset
snake_case__ : Dict = pa.Table.from_pydict(__A )
yield file_idx, self._cast_table(__A )
# If the file has one json object per line
else:
with open(__A , "rb" ) as f:
snake_case__ : Optional[Any] = 0
# Use block_size equal to the chunk size divided by 32 to leverage multithreading
# Set a default minimum value of 16kB if the chunk size is really small
snake_case__ : Dict = max(self.config.chunksize // 3_2 , 1_6 << 1_0 )
snake_case__ : List[Any] = (
self.config.encoding_errors if self.config.encoding_errors is not None else "strict"
)
while True:
snake_case__ : str = f.read(self.config.chunksize )
if not batch:
break
# Finish current line
try:
batch += f.readline()
except (AttributeError, io.UnsupportedOperation):
batch += readline(__A )
# PyArrow only accepts utf-8 encoded bytes
if self.config.encoding != "utf-8":
snake_case__ : Optional[Any] = batch.decode(self.config.encoding , errors=__A ).encode("utf-8" )
try:
while True:
try:
snake_case__ : List[Any] = paj.read_json(
io.BytesIO(__A ) , read_options=paj.ReadOptions(block_size=__A ) )
break
except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
if (
isinstance(__A , pa.ArrowInvalid )
and "straddling" not in str(__A )
or block_size > len(__A )
):
raise
else:
# Increase the block size in case it was too small.
# The block size will be reset for the next file.
logger.debug(
f'''Batch of {len(__A )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.''' )
block_size *= 2
except pa.ArrowInvalid as e:
try:
with open(
__A , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f:
snake_case__ : int = json.load(__A )
except json.JSONDecodeError:
logger.error(f'''Failed to read file \'{file}\' with error {type(__A )}: {e}''' )
raise e
# If possible, parse the file as a list of json objects and exit the loop
if isinstance(__A , __A ): # list is the only sequence type supported in JSON
try:
snake_case__ : str = set().union(*[row.keys() for row in dataset] )
snake_case__ : List[str] = {col: [row.get(__A ) for row in dataset] for col in keys}
snake_case__ : Dict = pa.Table.from_pydict(__A )
except (pa.ArrowInvalid, AttributeError) as e:
logger.error(f'''Failed to read file \'{file}\' with error {type(__A )}: {e}''' )
raise ValueError(f'''Not able to read records in the JSON file at {file}.''' ) from None
yield file_idx, self._cast_table(__A )
break
else:
logger.error(f'''Failed to read file \'{file}\' with error {type(__A )}: {e}''' )
raise ValueError(
f'''Not able to read records in the JSON file at {file}. '''
f'''You should probably indicate the field of the JSON file containing your records. '''
f'''This JSON file contain the following fields: {str(list(dataset.keys() ) )}. '''
f'''Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ''' ) from None
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield (file_idx, batch_idx), self._cast_table(__A )
batch_idx += 1
| 297 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_convbert import ConvBertTokenizer
__lowerCamelCase : Union[str, Any] = logging.get_logger(__name__)
__lowerCamelCase : str = {"""vocab_file""": """vocab.txt"""}
__lowerCamelCase : str = {
"""vocab_file""": {
"""YituTech/conv-bert-base""": """https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt""",
"""YituTech/conv-bert-medium-small""": (
"""https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt"""
),
"""YituTech/conv-bert-small""": """https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt""",
}
}
__lowerCamelCase : Dict = {
"""YituTech/conv-bert-base""": 512,
"""YituTech/conv-bert-medium-small""": 512,
"""YituTech/conv-bert-small""": 512,
}
__lowerCamelCase : List[Any] = {
"""YituTech/conv-bert-base""": {"""do_lower_case""": True},
"""YituTech/conv-bert-medium-small""": {"""do_lower_case""": True},
"""YituTech/conv-bert-small""": {"""do_lower_case""": True},
}
class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ):
"""simple docstring"""
a_ = VOCAB_FILES_NAMES
a_ = PRETRAINED_VOCAB_FILES_MAP
a_ = PRETRAINED_INIT_CONFIGURATION
a_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
a_ = ConvBertTokenizer
def __init__( self : Tuple , __A : Any=None , __A : Union[str, Any]=None , __A : List[Any]=True , __A : Optional[Any]="[UNK]" , __A : Tuple="[SEP]" , __A : Tuple="[PAD]" , __A : List[str]="[CLS]" , __A : Optional[Any]="[MASK]" , __A : List[str]=True , __A : Optional[Any]=None , **__A : Any , ):
super().__init__(
__A , tokenizer_file=__A , do_lower_case=__A , unk_token=__A , sep_token=__A , pad_token=__A , cls_token=__A , mask_token=__A , tokenize_chinese_chars=__A , strip_accents=__A , **__A , )
snake_case__ : Optional[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get("lowercase" , __A ) != do_lower_case
or normalizer_state.get("strip_accents" , __A ) != strip_accents
or normalizer_state.get("handle_chinese_chars" , __A ) != tokenize_chinese_chars
):
snake_case__ : Dict = getattr(__A , normalizer_state.pop("type" ) )
snake_case__ : str = do_lower_case
snake_case__ : Optional[int] = strip_accents
snake_case__ : int = tokenize_chinese_chars
snake_case__ : Tuple = normalizer_class(**__A )
snake_case__ : Union[str, Any] = do_lower_case
def _lowercase ( self : Any , __A : int , __A : Union[str, Any]=None ):
snake_case__ : Optional[int] = [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 : Any , __A : List[int] , __A : Optional[List[int]] = None ):
snake_case__ : str = [self.sep_token_id]
snake_case__ : Optional[int] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def _lowercase ( self : Optional[int] , __A : str , __A : Optional[str] = None ):
snake_case__ : Tuple = self._tokenizer.model.save(__A , name=__A )
return tuple(__A )
| 297 | 1 |
"""simple docstring"""
import numpy as np
A_ = [
['''a''', '''b''', '''c''', '''d''', '''e'''],
['''f''', '''g''', '''h''', '''i''', '''k'''],
['''l''', '''m''', '''n''', '''o''', '''p'''],
['''q''', '''r''', '''s''', '''t''', '''u'''],
['''v''', '''w''', '''x''', '''y''', '''z'''],
]
class __SCREAMING_SNAKE_CASE :
def __init__( self : Dict ):
'''simple docstring'''
A__ : Tuple = np.array(snake_case )
def _UpperCamelCase ( self : Optional[Any] , snake_case : str ):
'''simple docstring'''
A__ : List[str] = np.where(letter == self.SQUARE )
A__ : List[str] = np.concatenate([indexa + 1, indexa + 1] )
return indexes
def _UpperCamelCase ( self : Optional[int] , snake_case : int , snake_case : int ):
'''simple docstring'''
A__ : Dict = self.SQUARE[indexa - 1, indexa - 1]
return letter
def _UpperCamelCase ( self : Tuple , snake_case : str ):
'''simple docstring'''
A__ : Dict = message.lower()
A__ : Optional[Any] = message.replace(""" """ , """""" )
A__ : Tuple = message.replace("""j""" , """i""" )
A__ : Optional[int] = np.empty((2, len(snake_case )) )
for letter_index in range(len(snake_case ) ):
A__ : Dict = self.letter_to_numbers(message[letter_index] )
A__ : Optional[Any] = numbers[0]
A__ : str = numbers[1]
A__ : int = first_step.reshape(2 * len(snake_case ) )
A__ : Optional[Any] = """"""
for numbers_index in range(len(snake_case ) ):
A__ : List[str] = int(second_step[numbers_index * 2] )
A__ : Any = int(second_step[(numbers_index * 2) + 1] )
A__ : Optional[Any] = self.numbers_to_letter(snake_case , snake_case )
A__ : Union[str, Any] = encoded_message + letter
return encoded_message
def _UpperCamelCase ( self : int , snake_case : str ):
'''simple docstring'''
A__ : Optional[Any] = message.lower()
message.replace(""" """ , """""" )
A__ : Tuple = np.empty(2 * len(snake_case ) )
for letter_index in range(len(snake_case ) ):
A__ : List[str] = self.letter_to_numbers(message[letter_index] )
A__ : Tuple = numbers[0]
A__ : List[str] = numbers[1]
A__ : Dict = first_step.reshape((2, len(snake_case )) )
A__ : Dict = """"""
for numbers_index in range(len(snake_case ) ):
A__ : Tuple = int(second_step[0, numbers_index] )
A__ : List[str] = int(second_step[1, numbers_index] )
A__ : Tuple = self.numbers_to_letter(snake_case , snake_case )
A__ : Any = decoded_message + letter
return decoded_message
| 713 |
"""simple docstring"""
import baseaa
def _lowerCAmelCase ( UpperCAmelCase__ : str ) ->bytes:
return baseaa.baaencode(string.encode("""utf-8""" ) )
def _lowerCAmelCase ( UpperCAmelCase__ : bytes ) ->str:
return baseaa.baadecode(UpperCAmelCase__ ).decode("""utf-8""" )
if __name__ == "__main__":
A_ = '''Hello World!'''
A_ = baseaa_encode(test)
print(encoded)
A_ = baseaa_decode(encoded)
print(decoded)
| 498 | 0 |
import unittest
import numpy as np
import requests
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
lowerCAmelCase = False
if is_vision_available():
from PIL import Image
from transformers import PixaStructImageProcessor
class _a ( unittest.TestCase ):
def __init__( self: Union[str, Any] , UpperCamelCase_: List[Any] , UpperCamelCase_: Tuple=7 , UpperCamelCase_: int=3 , UpperCamelCase_: int=18 , UpperCamelCase_: Optional[Any]=30 , UpperCamelCase_: str=400 , UpperCamelCase_: Optional[int]=None , UpperCamelCase_: Optional[Any]=True , UpperCamelCase_: Optional[int]=True , UpperCamelCase_: List[str]=None , ) -> Tuple:
"""simple docstring"""
lowercase__ = size if size is not None else {'''height''': 20, '''width''': 20}
lowercase__ = parent
lowercase__ = batch_size
lowercase__ = num_channels
lowercase__ = image_size
lowercase__ = min_resolution
lowercase__ = max_resolution
lowercase__ = size
lowercase__ = do_normalize
lowercase__ = do_convert_rgb
lowercase__ = [512, 1_024, 2_048, 4_096]
lowercase__ = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16}
def lowerCamelCase_ ( self: Tuple ) -> Union[str, Any]:
"""simple docstring"""
return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}
def lowerCamelCase_ ( self: Union[str, Any] ) -> Optional[Any]:
"""simple docstring"""
lowercase__ = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
lowercase__ = Image.open(requests.get(UpperCamelCase_ , stream=UpperCamelCase_ ).raw ).convert('''RGB''' )
return raw_image
@unittest.skipIf(
not is_torch_greater_or_equal_than_1_11 , reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.''' , )
@require_torch
@require_vision
class _a ( UpperCamelCase__ , unittest.TestCase ):
_lowercase : Optional[Any] = PixaStructImageProcessor if is_vision_available() else None
def lowerCamelCase_ ( self: Any ) -> int:
"""simple docstring"""
lowercase__ = PixaStructImageProcessingTester(self )
@property
def lowerCamelCase_ ( self: Dict ) -> Tuple:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCamelCase_ ( self: Optional[int] ) -> Union[str, Any]:
"""simple docstring"""
lowercase__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(UpperCamelCase_ , '''do_normalize''' ) )
self.assertTrue(hasattr(UpperCamelCase_ , '''do_convert_rgb''' ) )
def lowerCamelCase_ ( self: Optional[Any] ) -> Dict:
"""simple docstring"""
lowercase__ = self.image_processor_tester.prepare_dummy_image()
lowercase__ = self.image_processing_class(**self.image_processor_dict )
lowercase__ = 2_048
lowercase__ = image_processor(UpperCamelCase_ , return_tensors='''pt''' , max_patches=UpperCamelCase_ )
self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1E-3 , rtol=1E-3 ) )
def lowerCamelCase_ ( self: Optional[Any] ) -> Dict:
"""simple docstring"""
lowercase__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
lowercase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase_ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase_ , Image.Image )
# Test not batched input
lowercase__ = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* self.image_processor_tester.num_channels
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
lowercase__ = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=UpperCamelCase_ ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
lowercase__ = image_processor(
UpperCamelCase_ , return_tensors='''pt''' , max_patches=UpperCamelCase_ ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
def lowerCamelCase_ ( self: List[Any] ) -> Optional[int]:
"""simple docstring"""
lowercase__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
lowercase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase_ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase_ , Image.Image )
# Test not batched input
lowercase__ = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* self.image_processor_tester.num_channels
) + 2
lowercase__ = True
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
with self.assertRaises(UpperCamelCase_ ):
lowercase__ = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=UpperCamelCase_ ).flattened_patches
lowercase__ = '''Hello'''
lowercase__ = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=UpperCamelCase_ , header_text=UpperCamelCase_ ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
lowercase__ = image_processor(
UpperCamelCase_ , return_tensors='''pt''' , max_patches=UpperCamelCase_ , header_text=UpperCamelCase_ ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
def lowerCamelCase_ ( self: List[Any] ) -> int:
"""simple docstring"""
lowercase__ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
lowercase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase_ , numpify=UpperCamelCase_ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase_ , np.ndarray )
lowercase__ = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* self.image_processor_tester.num_channels
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
lowercase__ = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=UpperCamelCase_ ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
lowercase__ = image_processor(
UpperCamelCase_ , return_tensors='''pt''' , max_patches=UpperCamelCase_ ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
def lowerCamelCase_ ( self: Optional[Any] ) -> str:
"""simple docstring"""
lowercase__ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
lowercase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase_ , torchify=UpperCamelCase_ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase_ , torch.Tensor )
# Test not batched input
lowercase__ = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* self.image_processor_tester.num_channels
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
lowercase__ = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=UpperCamelCase_ ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
lowercase__ = image_processor(
UpperCamelCase_ , return_tensors='''pt''' , max_patches=UpperCamelCase_ ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
@unittest.skipIf(
not is_torch_greater_or_equal_than_1_11 , reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.''' , )
@require_torch
@require_vision
class _a ( UpperCamelCase__ , unittest.TestCase ):
_lowercase : Tuple = PixaStructImageProcessor if is_vision_available() else None
def lowerCamelCase_ ( self: str ) -> Any:
"""simple docstring"""
lowercase__ = PixaStructImageProcessingTester(self , num_channels=4 )
lowercase__ = 3
@property
def lowerCamelCase_ ( self: List[Any] ) -> Tuple:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCamelCase_ ( self: Any ) -> Optional[Any]:
"""simple docstring"""
lowercase__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(UpperCamelCase_ , '''do_normalize''' ) )
self.assertTrue(hasattr(UpperCamelCase_ , '''do_convert_rgb''' ) )
def lowerCamelCase_ ( self: int ) -> Union[str, Any]:
"""simple docstring"""
lowercase__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
lowercase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase_ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase_ , Image.Image )
# Test not batched input
lowercase__ = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* (self.image_processor_tester.num_channels - 1)
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
lowercase__ = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=UpperCamelCase_ ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
lowercase__ = image_processor(
UpperCamelCase_ , return_tensors='''pt''' , max_patches=UpperCamelCase_ ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
| 43 |
lowerCAmelCase = {
'a': 'AAAAA',
'b': 'AAAAB',
'c': 'AAABA',
'd': 'AAABB',
'e': 'AABAA',
'f': 'AABAB',
'g': 'AABBA',
'h': 'AABBB',
'i': 'ABAAA',
'j': 'BBBAA',
'k': 'ABAAB',
'l': 'ABABA',
'm': 'ABABB',
'n': 'ABBAA',
'o': 'ABBAB',
'p': 'ABBBA',
'q': 'ABBBB',
'r': 'BAAAA',
's': 'BAAAB',
't': 'BAABA',
'u': 'BAABB',
'v': 'BBBAB',
'w': 'BABAA',
'x': 'BABAB',
'y': 'BABBA',
'z': 'BABBB',
' ': ' ',
}
lowerCAmelCase = {value: key for key, value in encode_dict.items()}
def _a ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
lowercase__ = ''''''
for letter in word.lower():
if letter.isalpha() or letter == " ":
encoded += encode_dict[letter]
else:
raise Exception('''encode() accepts only letters of the alphabet and spaces''' )
return encoded
def _a ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
if set(SCREAMING_SNAKE_CASE ) - {"A", "B", " "} != set():
raise Exception('''decode() accepts only \'A\', \'B\' and spaces''' )
lowercase__ = ''''''
for word in coded.split():
while len(SCREAMING_SNAKE_CASE ) != 0:
decoded += decode_dict[word[:5]]
lowercase__ = word[5:]
decoded += " "
return decoded.strip()
if __name__ == "__main__":
from doctest import testmod
testmod()
| 43 | 1 |
"""simple docstring"""
from __future__ import annotations
import math
from collections.abc import Callable
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ = 100, ) -> float:
a_ : Union[str, Any] = x_start
a_ : Optional[Any] = fnc(_SCREAMING_SNAKE_CASE )
a_ : Optional[int] = 0.0
for _ in range(_SCREAMING_SNAKE_CASE ):
# Approximates curve as a sequence of linear lines and sums their length
a_ : int = (x_end - x_start) / steps + xa
a_ : Optional[int] = fnc(_SCREAMING_SNAKE_CASE )
length += math.hypot(xa - xa, fxa - fxa )
# Increment step
a_ : Any = xa
a_ : Union[str, Any] = fxa
return length
if __name__ == "__main__":
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__ ) -> str:
return math.sin(10 * x )
print("""f(x) = sin(10 * x)""")
print("""The length of the curve from x = -10 to x = 10 is:""")
SCREAMING_SNAKE_CASE_ = 10
while i <= 10_00_00:
print(F"""With {i} steps: {line_length(f, -10, 10, i)}""")
i *= 10 | 701 |
"""simple docstring"""
import unittest
import numpy as np
import torch
from diffusers import VersatileDiffusionImageVariationPipeline
from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device
SCREAMING_SNAKE_CASE_ = False
class snake_case_ ( unittest.TestCase ):
pass
@slow
@require_torch_gpu
class snake_case_ ( unittest.TestCase ):
def snake_case_ ( self ):
a_ : Tuple = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" )
pipe.to(a_ )
pipe.set_progress_bar_config(disable=a_ )
a_ : Optional[Any] = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" )
a_ : Optional[Any] = torch.manual_seed(0 )
a_ : Dict = pipe(
image=a_ , generator=a_ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images
a_ : List[Any] = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]
assert image.shape == (1, 5_1_2, 5_1_2, 3)
a_ : Any = np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 | 370 | 0 |
from typing import Callable, List, Optional, Tuple, Union
import torch
from transformers import CLIPTextModel, CLIPTokenizer
from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin, TransformeraDModel, VQModel
from ...schedulers import VQDiffusionScheduler
from ...utils import logging
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
__snake_case = logging.get_logger(__name__) # pylint: disable=invalid-name
class __lowerCamelCase (_a , _a ):
@register_to_config
def __init__( self: str,A_: bool,A_: Optional[int] = None,A_: Optional[int] = None ):
'''simple docstring'''
super().__init__()
__UpperCamelCase = learnable
if self.learnable:
assert hidden_size is not None, "learnable=True requires `hidden_size` to be set"
assert length is not None, "learnable=True requires `length` to be set"
__UpperCamelCase = torch.zeros(A_,A_ )
else:
__UpperCamelCase = None
__UpperCamelCase = torch.nn.Parameter(A_ )
class __lowerCamelCase (_a ):
_lowercase = 42
_lowercase = 42
_lowercase = 42
_lowercase = 42
_lowercase = 42
_lowercase = 42
def __init__( self: Any,A_: VQModel,A_: CLIPTextModel,A_: CLIPTokenizer,A_: TransformeraDModel,A_: VQDiffusionScheduler,A_: LearnedClassifierFreeSamplingEmbeddings,):
'''simple docstring'''
super().__init__()
self.register_modules(
vqvae=A_,transformer=A_,text_encoder=A_,tokenizer=A_,scheduler=A_,learned_classifier_free_sampling_embeddings=A_,)
def snake_case_ ( self: Dict,A_: Optional[Any],A_: Any,A_: str ):
'''simple docstring'''
__UpperCamelCase = len(A_ ) if isinstance(A_,A_ ) else 1
# get prompt text embeddings
__UpperCamelCase = self.tokenizer(
A_,padding='max_length',max_length=self.tokenizer.model_max_length,return_tensors='pt',)
__UpperCamelCase = text_inputs.input_ids
if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
__UpperCamelCase = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] )
logger.warning(
'The following part of your input was truncated because CLIP can only handle sequences up to'
F''' {self.tokenizer.model_max_length} tokens: {removed_text}''' )
__UpperCamelCase = text_input_ids[:, : self.tokenizer.model_max_length]
__UpperCamelCase = self.text_encoder(text_input_ids.to(self.device ) )[0]
# NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion.
# While CLIP does normalize the pooled output of the text transformer when combining
# the image and text embeddings, CLIP does not directly normalize the last hidden state.
#
# CLIP normalizing the pooled output.
# https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053
__UpperCamelCase = prompt_embeds / prompt_embeds.norm(dim=-1,keepdim=A_ )
# duplicate text embeddings for each generation per prompt
__UpperCamelCase = prompt_embeds.repeat_interleave(A_,dim=0 )
if do_classifier_free_guidance:
if self.learned_classifier_free_sampling_embeddings.learnable:
__UpperCamelCase = self.learned_classifier_free_sampling_embeddings.embeddings
__UpperCamelCase = negative_prompt_embeds.unsqueeze(0 ).repeat(A_,1,1 )
else:
__UpperCamelCase = [''] * batch_size
__UpperCamelCase = text_input_ids.shape[-1]
__UpperCamelCase = self.tokenizer(
A_,padding='max_length',max_length=A_,truncation=A_,return_tensors='pt',)
__UpperCamelCase = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]
# See comment for normalizing text embeddings
__UpperCamelCase = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1,keepdim=A_ )
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
__UpperCamelCase = negative_prompt_embeds.shape[1]
__UpperCamelCase = negative_prompt_embeds.repeat(1,A_,1 )
__UpperCamelCase = negative_prompt_embeds.view(batch_size * num_images_per_prompt,A_,-1 )
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
__UpperCamelCase = torch.cat([negative_prompt_embeds, prompt_embeds] )
return prompt_embeds
@torch.no_grad()
def __call__( self: List[str],A_: Union[str, List[str]],A_: int = 100,A_: float = 5.0,A_: float = 1.0,A_: int = 1,A_: Optional[Union[torch.Generator, List[torch.Generator]]] = None,A_: Optional[torch.FloatTensor] = None,A_: Optional[str] = "pil",A_: bool = True,A_: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,A_: int = 1,):
'''simple docstring'''
if isinstance(A_,A_ ):
__UpperCamelCase = 1
elif isinstance(A_,A_ ):
__UpperCamelCase = len(A_ )
else:
raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(A_ )}''' )
__UpperCamelCase = batch_size * num_images_per_prompt
__UpperCamelCase = guidance_scale > 1.0
__UpperCamelCase = self._encode_prompt(A_,A_,A_ )
if (callback_steps is None) or (
callback_steps is not None and (not isinstance(A_,A_ ) or callback_steps <= 0)
):
raise ValueError(
F'''`callback_steps` has to be a positive integer but is {callback_steps} of type'''
F''' {type(A_ )}.''' )
# get the initial completely masked latents unless the user supplied it
__UpperCamelCase = (batch_size, self.transformer.num_latent_pixels)
if latents is None:
__UpperCamelCase = self.transformer.num_vector_embeds - 1
__UpperCamelCase = torch.full(A_,A_ ).to(self.device )
else:
if latents.shape != latents_shape:
raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' )
if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any():
raise ValueError(
'Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,'
F''' {self.transformer.num_vector_embeds - 1} (inclusive).''' )
__UpperCamelCase = latents.to(self.device )
# set timesteps
self.scheduler.set_timesteps(A_,device=self.device )
__UpperCamelCase = self.scheduler.timesteps.to(self.device )
__UpperCamelCase = latents
for i, t in enumerate(self.progress_bar(A_ ) ):
# expand the sample if we are doing classifier free guidance
__UpperCamelCase = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample
# predict the un-noised image
# model_output == `log_p_x_0`
__UpperCamelCase = self.transformer(A_,encoder_hidden_states=A_,timestep=A_ ).sample
if do_classifier_free_guidance:
__UpperCamelCase, __UpperCamelCase = model_output.chunk(2 )
__UpperCamelCase = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond)
model_output -= torch.logsumexp(A_,dim=1,keepdim=A_ )
__UpperCamelCase = self.truncate(A_,A_ )
# remove `log(0)`'s (`-inf`s)
__UpperCamelCase = model_output.clamp(-70 )
# compute the previous noisy sample x_t -> x_t-1
__UpperCamelCase = self.scheduler.step(A_,timestep=A_,sample=A_,generator=A_ ).prev_sample
# call the callback, if provided
if callback is not None and i % callback_steps == 0:
callback(A_,A_,A_ )
__UpperCamelCase = self.vqvae.config.vq_embed_dim
__UpperCamelCase = (batch_size, self.transformer.height, self.transformer.width, embedding_channels)
__UpperCamelCase = self.vqvae.quantize.get_codebook_entry(A_,shape=A_ )
__UpperCamelCase = self.vqvae.decode(A_,force_not_quantize=A_ ).sample
__UpperCamelCase = (image / 2 + 0.5).clamp(0,1 )
__UpperCamelCase = image.cpu().permute(0,2,3,1 ).numpy()
if output_type == "pil":
__UpperCamelCase = self.numpy_to_pil(A_ )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=A_ )
def snake_case_ ( self: int,A_: torch.FloatTensor,A_: float ):
'''simple docstring'''
__UpperCamelCase, __UpperCamelCase = torch.sort(A_,1,descending=A_ )
__UpperCamelCase = torch.exp(A_ )
__UpperCamelCase = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate
# Ensure that at least the largest probability is not zeroed out
__UpperCamelCase = torch.full_like(keep_mask[:, 0:1, :],A_ )
__UpperCamelCase = torch.cat((all_true, keep_mask),dim=1 )
__UpperCamelCase = keep_mask[:, :-1, :]
__UpperCamelCase = keep_mask.gather(1,indices.argsort(1 ) )
__UpperCamelCase = log_p_x_0.clone()
__UpperCamelCase = -torch.inf # -inf = log(0)
return rv
| 1 |
"""simple docstring"""
def _lowerCAmelCase ( ) -> int:
return [
a * b * (1_0_0_0 - a - b)
for a in range(1, 9_9_9 )
for b in range(lowerCamelCase__, 9_9_9 )
if (a * a + b * b == (1_0_0_0 - a - b) ** 2)
][0]
if __name__ == "__main__":
print(F'{solution() = }')
| 572 | 0 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
A_ :Any = logging.get_logger(__name__)
A_ :Optional[int] = {
'''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 __A ( a ):
"""simple docstring"""
UpperCamelCase__ : Dict ="""xmod"""
def __init__( self , lowerCamelCase__=30522 , lowerCamelCase__=768 , lowerCamelCase__=12 , lowerCamelCase__=12 , lowerCamelCase__=3072 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=512 , lowerCamelCase__=2 , lowerCamelCase__=0.02 , lowerCamelCase__=1E-12 , lowerCamelCase__=1 , lowerCamelCase__=0 , lowerCamelCase__=2 , lowerCamelCase__="absolute" , lowerCamelCase__=True , lowerCamelCase__=None , lowerCamelCase__=False , lowerCamelCase__=2 , lowerCamelCase__=False , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=("en_XX",) , lowerCamelCase__=None , **lowerCamelCase__ , ):
"""simple docstring"""
super().__init__(pad_token_id=lowerCamelCase__ , bos_token_id=lowerCamelCase__ , eos_token_id=lowerCamelCase__ , **lowerCamelCase__ )
__UpperCamelCase : int =vocab_size
__UpperCamelCase : int =hidden_size
__UpperCamelCase : Tuple =num_hidden_layers
__UpperCamelCase : Dict =num_attention_heads
__UpperCamelCase : str =hidden_act
__UpperCamelCase : str =intermediate_size
__UpperCamelCase : str =hidden_dropout_prob
__UpperCamelCase : List[str] =attention_probs_dropout_prob
__UpperCamelCase : Dict =max_position_embeddings
__UpperCamelCase : Optional[Any] =type_vocab_size
__UpperCamelCase : List[Any] =initializer_range
__UpperCamelCase : List[Any] =layer_norm_eps
__UpperCamelCase : Dict =position_embedding_type
__UpperCamelCase : Tuple =use_cache
__UpperCamelCase : int =classifier_dropout
__UpperCamelCase : Union[str, Any] =pre_norm
__UpperCamelCase : List[str] =adapter_reduction_factor
__UpperCamelCase : Any =adapter_layer_norm
__UpperCamelCase : Any =adapter_reuse_layer_norm
__UpperCamelCase : List[str] =ln_before_adapter
__UpperCamelCase : int =list(lowerCamelCase__ )
__UpperCamelCase : Dict =default_language
class __A ( a ):
"""simple docstring"""
@property
def __lowercase ( self ):
"""simple docstring"""
if self.task == "multiple-choice":
__UpperCamelCase : int ={0: 'batch', 1: 'choice', 2: 'sequence'}
else:
__UpperCamelCase : List[Any] ={0: 'batch', 1: 'sequence'}
return OrderedDict(
[
('input_ids', dynamic_axis),
('attention_mask', dynamic_axis),
] )
| 154 |
import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import ClassLabel, Features, Image
from .base import TaskTemplate
@dataclass(frozen=a )
class __A ( a ):
"""simple docstring"""
UpperCamelCase__ : str =field(default="""image-classification""" , metadata={"""include_in_asdict_even_if_is_default""": True} )
UpperCamelCase__ : ClassVar[Features] =Features({"""image""": Image()} )
UpperCamelCase__ : ClassVar[Features] =Features({"""labels""": ClassLabel} )
UpperCamelCase__ : str ="image"
UpperCamelCase__ : str ="labels"
def __lowercase ( self , lowerCamelCase__ ):
"""simple docstring"""
if self.label_column not in features:
raise ValueError(f'Column {self.label_column} is not present in features.' )
if not isinstance(features[self.label_column] , lowerCamelCase__ ):
raise ValueError(f'Column {self.label_column} is not a ClassLabel.' )
__UpperCamelCase : List[str] =copy.deepcopy(self )
__UpperCamelCase : Optional[Any] =self.label_schema.copy()
__UpperCamelCase : List[Any] =features[self.label_column]
__UpperCamelCase : Optional[int] =label_schema
return task_template
@property
def __lowercase ( self ):
"""simple docstring"""
return {
self.image_column: "image",
self.label_column: "labels",
}
| 154 | 1 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import _LazyModule
_lowerCAmelCase = {"""processing_wav2vec2_with_lm""": ["""Wav2Vec2ProcessorWithLM"""]}
if TYPE_CHECKING:
from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM
else:
import sys
_lowerCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 259 |
'''simple docstring'''
def _UpperCamelCase ( UpperCamelCase__ ):
if not isinstance(UpperCamelCase__ , UpperCamelCase__ ):
UpperCAmelCase__ : int = f'''Input value of [number={number}] must be an integer'''
raise TypeError(UpperCamelCase__ )
if number < 1:
UpperCAmelCase__ : Optional[Any] = f'''Input value of [number={number}] must be > 0'''
raise ValueError(UpperCamelCase__ )
UpperCAmelCase__ : Optional[Any] = 1
for i in range(1 , UpperCamelCase__ ):
current_number *= 4 * i - 2
current_number //= i + 1
return current_number
if __name__ == "__main__":
import doctest
doctest.testmod() | 407 | 0 |
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
if TYPE_CHECKING:
from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType
UpperCAmelCase__ = logging.get_logger(__name__)
UpperCAmelCase__ = {
"""microsoft/deberta-v2-xlarge""": """https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json""",
"""microsoft/deberta-v2-xxlarge""": """https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json""",
"""microsoft/deberta-v2-xlarge-mnli""": (
"""https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json"""
),
"""microsoft/deberta-v2-xxlarge-mnli""": (
"""https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json"""
),
}
class __lowerCAmelCase ( UpperCamelCase_ ):
UpperCamelCase = '''deberta-v2'''
def __init__( self : Dict , A : Dict=12_81_00 , A : Any=15_36 , A : Union[str, Any]=24 , A : Optional[int]=24 , A : Any=61_44 , A : List[str]="gelu" , A : List[str]=0.1 , A : int=0.1 , A : Dict=5_12 , A : Optional[int]=0 , A : Union[str, Any]=0.0_2 , A : str=1E-7 , A : Union[str, Any]=False , A : str=-1 , A : str=0 , A : Optional[Any]=True , A : Union[str, Any]=None , A : Any=0 , A : Any="gelu" , **A : Optional[int] , ) -> Dict:
"""simple docstring"""
super().__init__(**__A)
_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 = initializer_range
_UpperCAmelCase = relative_attention
_UpperCAmelCase = max_relative_positions
_UpperCAmelCase = pad_token_id
_UpperCAmelCase = position_biased_input
# Backwards compatibility
if type(__A) == str:
_UpperCAmelCase = [x.strip() for x in pos_att_type.lower().split('|')]
_UpperCAmelCase = pos_att_type
_UpperCAmelCase = vocab_size
_UpperCAmelCase = layer_norm_eps
_UpperCAmelCase = kwargs.get('pooler_hidden_size' , __A)
_UpperCAmelCase = pooler_dropout
_UpperCAmelCase = pooler_hidden_act
class __lowerCAmelCase ( UpperCamelCase_ ):
@property
def _lowerCamelCase ( self : str) -> List[Any]:
"""simple docstring"""
if self.task == "multiple-choice":
_UpperCAmelCase = {0: "batch", 1: "choice", 2: "sequence"}
else:
_UpperCAmelCase = {0: "batch", 1: "sequence"}
if self._config.type_vocab_size > 0:
return OrderedDict(
[('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)])
else:
return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)])
@property
def _lowerCamelCase ( self : Dict) -> Any:
"""simple docstring"""
return 12
def _lowerCamelCase ( self : List[Any] , A : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , A : int = -1 , A : int = -1 , A : int = -1 , A : bool = False , A : Optional["TensorType"] = None , A : int = 3 , A : int = 40 , A : int = 40 , A : "PreTrainedTokenizerBase" = None , ) -> int:
"""simple docstring"""
_UpperCAmelCase = super().generate_dummy_inputs(preprocessor=__A , framework=__A)
if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs:
del dummy_inputs["token_type_ids"]
return dummy_inputs
| 703 |
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging
if is_torch_available():
import torch
UpperCAmelCase__ = logging.get_logger(__name__)
class __lowerCAmelCase ( A ):
UpperCamelCase = ['''pixel_values''']
def __init__( self : Any , A : bool = True , A : Optional[Dict[str, int]] = None , A : PILImageResampling = PILImageResampling.BILINEAR , A : bool = True , A : Dict[str, int] = None , A : bool = True , A : Union[int, float] = 1 / 2_55 , A : bool = True , A : Optional[Union[float, List[float]]] = None , A : Optional[Union[float, List[float]]] = None , **A : Union[str, Any] , ) -> None:
"""simple docstring"""
super().__init__(**A)
_UpperCAmelCase = size if size is not None else {'shortest_edge': 2_56}
_UpperCAmelCase = get_size_dict(A , default_to_square=A)
_UpperCAmelCase = crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24}
_UpperCAmelCase = get_size_dict(A , param_name='crop_size')
_UpperCAmelCase = do_resize
_UpperCAmelCase = size
_UpperCAmelCase = resample
_UpperCAmelCase = do_center_crop
_UpperCAmelCase = crop_size
_UpperCAmelCase = do_rescale
_UpperCAmelCase = rescale_factor
_UpperCAmelCase = do_normalize
_UpperCAmelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
_UpperCAmelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD
def _lowerCamelCase ( self : List[str] , A : np.ndarray , A : Dict[str, int] , A : PILImageResampling = PILImageResampling.BICUBIC , A : Optional[Union[str, ChannelDimension]] = None , **A : List[str] , ) -> np.ndarray:
"""simple docstring"""
_UpperCAmelCase = get_size_dict(A , default_to_square=A)
if "shortest_edge" not in size:
raise ValueError(F"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}")
_UpperCAmelCase = get_resize_output_image_size(A , size=size['shortest_edge'] , default_to_square=A)
return resize(A , size=A , resample=A , data_format=A , **A)
def _lowerCamelCase ( self : Any , A : np.ndarray , A : Dict[str, int] , A : Optional[Union[str, ChannelDimension]] = None , **A : Union[str, Any] , ) -> np.ndarray:
"""simple docstring"""
_UpperCAmelCase = get_size_dict(A)
if "height" not in size or "width" not in size:
raise ValueError(F"The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}")
return center_crop(A , size=(size['height'], size['width']) , data_format=A , **A)
def _lowerCamelCase ( self : Any , A : np.ndarray , A : float , A : Optional[Union[str, ChannelDimension]] = None , **A : Dict) -> np.ndarray:
"""simple docstring"""
return rescale(A , scale=A , data_format=A , **A)
def _lowerCamelCase ( self : int , A : np.ndarray , A : Union[float, List[float]] , A : Union[float, List[float]] , A : Optional[Union[str, ChannelDimension]] = None , **A : Dict , ) -> np.ndarray:
"""simple docstring"""
return normalize(A , mean=A , std=A , data_format=A , **A)
def _lowerCamelCase ( self : Union[str, Any] , A : ImageInput , A : Optional[bool] = None , A : Dict[str, int] = None , A : PILImageResampling = None , A : bool = None , A : Dict[str, int] = None , A : Optional[bool] = None , A : Optional[float] = None , A : Optional[bool] = None , A : Optional[Union[float, List[float]]] = None , A : Optional[Union[float, List[float]]] = None , A : Optional[Union[str, TensorType]] = None , A : Union[str, ChannelDimension] = ChannelDimension.FIRST , **A : int , ) -> Dict:
"""simple docstring"""
_UpperCAmelCase = do_resize if do_resize is not None else self.do_resize
_UpperCAmelCase = size if size is not None else self.size
_UpperCAmelCase = get_size_dict(A , default_to_square=A)
_UpperCAmelCase = resample if resample is not None else self.resample
_UpperCAmelCase = do_center_crop if do_center_crop is not None else self.do_center_crop
_UpperCAmelCase = crop_size if crop_size is not None else self.crop_size
_UpperCAmelCase = get_size_dict(A , param_name='crop_size')
_UpperCAmelCase = do_rescale if do_rescale is not None else self.do_rescale
_UpperCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor
_UpperCAmelCase = do_normalize if do_normalize is not None else self.do_normalize
_UpperCAmelCase = image_mean if image_mean is not None else self.image_mean
_UpperCAmelCase = image_std if image_std is not None else self.image_std
_UpperCAmelCase = make_list_of_images(A)
if not valid_images(A):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.')
if do_resize and size is None:
raise ValueError('Size must be specified if do_resize is True.')
if do_center_crop and crop_size is None:
raise ValueError('Crop size must be specified if do_center_crop is True.')
if do_rescale and rescale_factor is None:
raise ValueError('Rescale factor must be specified if do_rescale is True.')
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('Image mean and std must be specified if do_normalize is True.')
# All transformations expect numpy arrays.
_UpperCAmelCase = [to_numpy_array(A) for image in images]
if do_resize:
_UpperCAmelCase = [self.resize(image=A , size=A , resample=A) for image in images]
if do_center_crop:
_UpperCAmelCase = [self.center_crop(image=A , size=A) for image in images]
if do_rescale:
_UpperCAmelCase = [self.rescale(image=A , scale=A) for image in images]
if do_normalize:
_UpperCAmelCase = [self.normalize(image=A , mean=A , std=A) for image in images]
_UpperCAmelCase = [to_channel_dimension_format(A , A) for image in images]
_UpperCAmelCase = {'pixel_values': images}
return BatchFeature(data=A , tensor_type=A)
def _lowerCamelCase ( self : str , A : Any , A : List[Tuple] = None) -> Tuple:
"""simple docstring"""
_UpperCAmelCase = outputs.logits
# Resize logits and compute semantic segmentation maps
if target_sizes is not None:
if len(A) != len(A):
raise ValueError(
'Make sure that you pass in as many target sizes as the batch dimension of the logits')
if is_torch_tensor(A):
_UpperCAmelCase = target_sizes.numpy()
_UpperCAmelCase = []
for idx in range(len(A)):
_UpperCAmelCase = torch.nn.functional.interpolate(
logits[idx].unsqueeze(dim=0) , size=target_sizes[idx] , mode='bilinear' , align_corners=A)
_UpperCAmelCase = resized_logits[0].argmax(dim=0)
semantic_segmentation.append(A)
else:
_UpperCAmelCase = logits.argmax(dim=1)
_UpperCAmelCase = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
return semantic_segmentation
| 639 | 0 |
"""simple docstring"""
def A ( __snake_case: str , __snake_case: bool = False ) -> str:
"""simple docstring"""
if not isinstance(__snake_case , __snake_case ):
__magic_name__ = F"""Expected string as input, found {type(__snake_case )}"""
raise ValueError(__snake_case )
if not isinstance(__snake_case , __snake_case ):
__magic_name__ = F"""Expected boolean as use_pascal parameter, found {type(__snake_case )}"""
raise ValueError(__snake_case )
__magic_name__ = input_str.split('_' )
__magic_name__ = 0 if use_pascal else 1
__magic_name__ = words[start_index:]
__magic_name__ = [word[0].upper() + word[1:] for word in words_to_capitalize]
__magic_name__ = '' if use_pascal else words[0]
return "".join([initial_word, *capitalized_words] )
if __name__ == "__main__":
from doctest import testmod
testmod() | 545 |
"""simple docstring"""
from __future__ import annotations
import random
import unittest
from transformers import TransfoXLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
TFTransfoXLForSequenceClassification,
TFTransfoXLLMHeadModel,
TFTransfoXLModel,
)
class UpperCamelCase__ :
"""simple docstring"""
def __init__( self : int , UpperCamelCase_ : Union[str, Any] , ):
'''simple docstring'''
__magic_name__ = parent
__magic_name__ = 1_3
__magic_name__ = 7
__magic_name__ = 3_0
__magic_name__ = self.seq_length + self.mem_len
__magic_name__ = 1_5
__magic_name__ = True
__magic_name__ = True
__magic_name__ = 9_9
__magic_name__ = [1_0, 5_0, 8_0]
__magic_name__ = 3_2
__magic_name__ = 3_2
__magic_name__ = 4
__magic_name__ = 8
__magic_name__ = 1_2_8
__magic_name__ = 2
__magic_name__ = 2
__magic_name__ = None
__magic_name__ = 1
__magic_name__ = 0
__magic_name__ = 3
__magic_name__ = self.vocab_size - 1
__magic_name__ = 0.01
def a__ ( self : Dict ):
'''simple docstring'''
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__magic_name__ = None
if self.use_labels:
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__magic_name__ = TransfoXLConfig(
vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , )
return (config, input_ids_a, input_ids_a, lm_labels)
def a__ ( self : Optional[Any] ):
'''simple docstring'''
random.seed(self.seed )
tf.random.set_seed(self.seed )
def a__ ( self : Dict , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : int , UpperCamelCase_ : List[Any] ):
'''simple docstring'''
__magic_name__ = TFTransfoXLModel(UpperCamelCase_ )
__magic_name__ , __magic_name__ = model(UpperCamelCase_ ).to_tuple()
__magic_name__ = {'input_ids': input_ids_a, 'mems': mems_a}
__magic_name__ , __magic_name__ = model(UpperCamelCase_ ).to_tuple()
self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertListEqual(
[mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , )
self.parent.assertListEqual(
[mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , )
def a__ ( self : Optional[int] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Tuple ):
'''simple docstring'''
__magic_name__ = TFTransfoXLLMHeadModel(UpperCamelCase_ )
__magic_name__ , __magic_name__ = model(UpperCamelCase_ ).to_tuple()
__magic_name__ = {'input_ids': input_ids_a, 'labels': lm_labels}
__magic_name__ , __magic_name__ = model(UpperCamelCase_ ).to_tuple()
__magic_name__ , __magic_name__ = model([input_ids_a, mems_a] ).to_tuple()
__magic_name__ = {'input_ids': input_ids_a, 'mems': mems_a, 'labels': lm_labels}
__magic_name__ , __magic_name__ = model(UpperCamelCase_ ).to_tuple()
self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) )
self.parent.assertListEqual(
[mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , )
self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) )
self.parent.assertListEqual(
[mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , )
def a__ ( self : Union[str, Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Tuple , UpperCamelCase_ : Tuple , UpperCamelCase_ : Dict ):
'''simple docstring'''
__magic_name__ = TFTransfoXLForSequenceClassification(UpperCamelCase_ )
__magic_name__ = model(UpperCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def a__ ( self : Dict ):
'''simple docstring'''
__magic_name__ = self.prepare_config_and_inputs()
((__magic_name__) , (__magic_name__) , (__magic_name__) , (__magic_name__)) = config_and_inputs
__magic_name__ = {'input_ids': input_ids_a}
return config, inputs_dict
@require_tf
class UpperCamelCase__ ( a_ , a_ , unittest.TestCase):
"""simple docstring"""
__UpperCAmelCase = (
(TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else ()
)
__UpperCAmelCase = () if is_tf_available() else ()
__UpperCAmelCase = (
{
"""feature-extraction""": TFTransfoXLModel,
"""text-classification""": TFTransfoXLForSequenceClassification,
"""text-generation""": TFTransfoXLLMHeadModel,
"""zero-shot""": TFTransfoXLForSequenceClassification,
}
if is_tf_available()
else {}
)
# TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented
__UpperCAmelCase = False
__UpperCAmelCase = False
__UpperCAmelCase = False
__UpperCAmelCase = False
def a__ ( self : int , UpperCamelCase_ : Dict , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : List[str] , UpperCamelCase_ : Tuple ):
'''simple docstring'''
if pipeline_test_casse_name == "TextGenerationPipelineTests":
# Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`.
# `TransfoXLConfig` was never used in pipeline tests: cannot create a simple
# tokenizer.
return True
return False
def a__ ( self : Union[str, Any] ):
'''simple docstring'''
__magic_name__ = TFTransfoXLModelTester(self )
__magic_name__ = ConfigTester(self , config_class=UpperCamelCase_ , d_embed=3_7 )
def a__ ( self : List[str] ):
'''simple docstring'''
self.config_tester.run_common_tests()
def a__ ( self : int ):
'''simple docstring'''
self.model_tester.set_seed()
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_transfo_xl_model(*UpperCamelCase_ )
def a__ ( self : str ):
'''simple docstring'''
self.model_tester.set_seed()
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_transfo_xl_lm_head(*UpperCamelCase_ )
def a__ ( self : Any ):
'''simple docstring'''
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*UpperCamelCase_ )
def a__ ( self : List[str] ):
'''simple docstring'''
__magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
__magic_name__ = [TFTransfoXLForSequenceClassification]
for model_class in self.all_model_classes:
__magic_name__ = model_class(UpperCamelCase_ )
assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer )
if model_class in list_other_models_with_output_ebd:
__magic_name__ = model.get_output_embeddings()
assert isinstance(UpperCamelCase_ , tf.keras.layers.Layer )
__magic_name__ = model.get_bias()
assert name is None
else:
__magic_name__ = model.get_output_embeddings()
assert x is None
__magic_name__ = model.get_bias()
assert name is None
def a__ ( self : int ):
'''simple docstring'''
pass
@slow
def a__ ( self : str ):
'''simple docstring'''
for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__magic_name__ = TFTransfoXLModel.from_pretrained(UpperCamelCase_ )
self.assertIsNotNone(UpperCamelCase_ )
@unittest.skip(reason='This model doesn\'t play well with fit() due to not returning a single loss.' )
def a__ ( self : List[str] ):
'''simple docstring'''
pass
@require_tf
class UpperCamelCase__ ( unittest.TestCase):
"""simple docstring"""
@unittest.skip('Skip test until #12651 is resolved.' )
@slow
def a__ ( self : Optional[Any] ):
'''simple docstring'''
__magic_name__ = TFTransfoXLLMHeadModel.from_pretrained('transfo-xl-wt103' )
# fmt: off
__magic_name__ = tf.convert_to_tensor([[3_3,1_2_9_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_2,1_7_0_6,1_7,2_0_0_9_8,5,3_2_1_5,2_1,3_7,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,6_2_2_4,8_3_1,1_6_0_0_2,2,8,6_0_3,7_8_9_6_7,2_9_5_4_6,2_3,8_0_3,2_0,2_5,4_1_6,5,8,2_3_2,4,2_7_7,6,1_8_5_5,4_6_0_1,3,2_9_5_4_6,5_4,8,3_6_0_9,5,5_7_2_1_1,4_9,4,1,2_7_7,1_8,8,1_7_5_5,1_5_6_9_1,3,3_4_1,2_5,4_1_6,6_9_3,4_2_5_7_3,7_1,1_7,4_0_1,9_4,3_1,1_7_9_1_9,2,2_9_5_4_6,7_8_7_3,1_8,1,4_3_5,2_3,1_1_0_1_1,7_5_5,5,5_1_6_7,3,7_9_8_3,9_8,8_4,2,2_9_5_4_6,3_2_6_7,8,3_6_0_9,4,1,4_8_6_5,1_0_7_5,2,6_0_8_7,7_1,6,3_4_6,8,5_8_5_4,3,2_9_5_4_6,8_2_4,1_4_0_0,1_8_6_8,2,1_9,1_6_0,2,3_1_1,8,5_4_9_6,2,2_0_9_2_0,1_7,2_5,1_5_0_9_7,3,2_4,2_4,0]] , dtype=tf.intaa ) # noqa: E231
# fmt: on
# In 1991 , the remains of Russian Tsar Nicholas II and his family
# ( except for Alexei and Maria ) are discovered .
# The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the
# remainder of the story . 1883 Western Siberia ,
# a young Grigori Rasputin is asked by his father and a group of men to perform magic .
# Rasputin has a vision and denounces one of the men as a horse thief . Although his
# father initially slaps him for making such an accusation , Rasputin watches as the
# man is chased outside and beaten . Twenty years later , Rasputin sees a vision of
# the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous ,
# with people , even a bishop , begging for his blessing . <eod> </s> <eos>
# fmt: off
__magic_name__ = [3_3,1_2_9_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_2,1_7_0_6,1_7,2_0_0_9_8,5,3_2_1_5,2_1,3_7,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,6_2_2_4,8_3_1,1_6_0_0_2,2,8,6_0_3,7_8_9_6_7,2_9_5_4_6,2_3,8_0_3,2_0,2_5,4_1_6,5,8,2_3_2,4,2_7_7,6,1_8_5_5,4_6_0_1,3,2_9_5_4_6,5_4,8,3_6_0_9,5,5_7_2_1_1,4_9,4,1,2_7_7,1_8,8,1_7_5_5,1_5_6_9_1,3,3_4_1,2_5,4_1_6,6_9_3,4_2_5_7_3,7_1,1_7,4_0_1,9_4,3_1,1_7_9_1_9,2,2_9_5_4_6,7_8_7_3,1_8,1,4_3_5,2_3,1_1_0_1_1,7_5_5,5,5_1_6_7,3,7_9_8_3,9_8,8_4,2,2_9_5_4_6,3_2_6_7,8,3_6_0_9,4,1,4_8_6_5,1_0_7_5,2,6_0_8_7,7_1,6,3_4_6,8,5_8_5_4,3,2_9_5_4_6,8_2_4,1_4_0_0,1_8_6_8,2,1_9,1_6_0,2,3_1_1,8,5_4_9_6,2,2_0_9_2_0,1_7,2_5,1_5_0_9_7,3,2_4,2_4,0,3_3,1,1_8_5_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_8,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,0] # noqa: E231
# fmt: on
# In 1991, the remains of Russian Tsar Nicholas II and his family (
# except for Alexei and Maria ) are discovered. The voice of young son,
# Tsarevich Alexei Nikolaevich, narrates the remainder of the story.
# 1883 Western Siberia, a young Grigori Rasputin is asked by his father
# and a group of men to perform magic. Rasputin has a vision and
# denounces one of the men as a horse thief. Although his father initially
# slaps him for making such an accusation, Rasputin watches as the man
# is chased outside and beaten. Twenty years later, Rasputin sees a vision
# of the Virgin Mary, prompting him to become a priest.
# Rasputin quickly becomes famous, with people, even a bishop, begging for
# his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar
# Nicholas II and his family were discovered. The voice of <unk> young son,
# Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos>
__magic_name__ = model.generate(UpperCamelCase_ , max_length=2_0_0 , do_sample=UpperCamelCase_ )
self.assertListEqual(output_ids[0].numpy().tolist() , UpperCamelCase_ ) | 545 | 1 |
"""simple docstring"""
import argparse
import torch
from transformers import (
UniSpeechSatConfig,
UniSpeechSatForAudioFrameClassification,
UniSpeechSatForSequenceClassification,
UniSpeechSatForXVector,
WavaVecaFeatureExtractor,
logging,
)
logging.set_verbosity_info()
lowerCamelCase = logging.get_logger(__name__)
def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
UpperCAmelCase_ = UniSpeechSatForSequenceClassification.from_pretrained(lowerCAmelCase__ , config=lowerCAmelCase__ )
UpperCAmelCase_ = downstream_dict["projector.weight"]
UpperCAmelCase_ = downstream_dict["projector.bias"]
UpperCAmelCase_ = downstream_dict["model.post_net.linear.weight"]
UpperCAmelCase_ = downstream_dict["model.post_net.linear.bias"]
return model
def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
UpperCAmelCase_ = UniSpeechSatForAudioFrameClassification.from_pretrained(lowerCAmelCase__ , config=lowerCAmelCase__ )
UpperCAmelCase_ = downstream_dict["model.linear.weight"]
UpperCAmelCase_ = downstream_dict["model.linear.bias"]
return model
def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
UpperCAmelCase_ = UniSpeechSatForXVector.from_pretrained(lowerCAmelCase__ , config=lowerCAmelCase__ )
UpperCAmelCase_ = downstream_dict["connector.weight"]
UpperCAmelCase_ = downstream_dict["connector.bias"]
for i, kernel_size in enumerate(hf_config.tdnn_kernel ):
UpperCAmelCase_ = downstream_dict[
f"""model.framelevel_feature_extractor.module.{i}.kernel.weight"""
]
UpperCAmelCase_ = downstream_dict[f"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""]
UpperCAmelCase_ = downstream_dict["model.utterancelevel_feature_extractor.linear1.weight"]
UpperCAmelCase_ = downstream_dict["model.utterancelevel_feature_extractor.linear1.bias"]
UpperCAmelCase_ = downstream_dict["model.utterancelevel_feature_extractor.linear2.weight"]
UpperCAmelCase_ = downstream_dict["model.utterancelevel_feature_extractor.linear2.bias"]
UpperCAmelCase_ = downstream_dict["objective.W"]
return model
@torch.no_grad()
def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
UpperCAmelCase_ = torch.load(lowerCAmelCase__ , map_location="cpu" )
UpperCAmelCase_ = checkpoint["Downstream"]
UpperCAmelCase_ = UniSpeechSatConfig.from_pretrained(lowerCAmelCase__ )
UpperCAmelCase_ = WavaVecaFeatureExtractor.from_pretrained(
lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , do_normalize=lowerCAmelCase__ )
UpperCAmelCase_ = hf_config.architectures[0]
if arch.endswith("ForSequenceClassification" ):
UpperCAmelCase_ = convert_classification(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
elif arch.endswith("ForAudioFrameClassification" ):
UpperCAmelCase_ = convert_diarization(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
elif arch.endswith("ForXVector" ):
UpperCAmelCase_ = convert_xvector(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
else:
raise NotImplementedError(f"""S3PRL weights conversion is not supported for {arch}""" )
if hf_config.use_weighted_layer_sum:
UpperCAmelCase_ = checkpoint["Featurizer"]["weights"]
hf_feature_extractor.save_pretrained(lowerCAmelCase__ )
hf_model.save_pretrained(lowerCAmelCase__ )
if __name__ == "__main__":
lowerCamelCase = argparse.ArgumentParser()
parser.add_argument(
"""--base_model_name""", default=None, type=str, help="""Name of the huggingface pretrained base model."""
)
parser.add_argument("""--config_path""", default=None, type=str, help="""Path to the huggingface classifier config.""")
parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to the s3prl checkpoint.""")
parser.add_argument("""--model_dump_path""", default=None, type=str, help="""Path to the final converted model.""")
lowerCamelCase = parser.parse_args()
convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
| 721 |
"""simple docstring"""
from __future__ import annotations
import math
def a__ ( lowerCAmelCase__ ):
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(math.sqrt(lowerCAmelCase__ ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
lowerCamelCase = [num for num in range(3, 100_001, 2) if not is_prime(num)]
def a__ ( lowerCAmelCase__ ):
if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ):
raise ValueError("n must be an integer" )
if n <= 0:
raise ValueError("n must be >= 0" )
UpperCAmelCase_ = []
for num in range(len(lowerCAmelCase__ ) ):
UpperCAmelCase_ = 0
while 2 * i * i <= odd_composites[num]:
UpperCAmelCase_ = odd_composites[num] - 2 * i * i
if is_prime(lowerCAmelCase__ ):
break
i += 1
else:
list_nums.append(odd_composites[num] )
if len(lowerCAmelCase__ ) == n:
return list_nums
return []
def a__ ( ):
return compute_nums(1 )[0]
if __name__ == "__main__":
print(F"{solution() = }")
| 14 | 0 |
'''simple docstring'''
import unittest
import numpy as np
import timeout_decorator # noqa
from transformers import BlenderbotSmallConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor
if is_flax_available():
import os
# The slow tests are often failing with OOM error on GPU
# This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
# but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
lowerCamelCase : str = "platform"
import jax
import jax.numpy as jnp
from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import (
FlaxBlenderbotSmallForConditionalGeneration,
FlaxBlenderbotSmallModel,
shift_tokens_right,
)
def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : List[str] , _UpperCamelCase : Optional[Any]=None , _UpperCamelCase : Any=None , _UpperCamelCase : List[Any]=None , _UpperCamelCase : Union[str, Any]=None , _UpperCamelCase : Union[str, Any]=None , _UpperCamelCase : Union[str, Any]=None , ) -> Dict:
"""simple docstring"""
if attention_mask is None:
_SCREAMING_SNAKE_CASE =np.where(input_ids != config.pad_token_id , 1 , 0 )
if decoder_attention_mask is None:
_SCREAMING_SNAKE_CASE =np.where(decoder_input_ids != config.pad_token_id , 1 , 0 )
if head_mask is None:
_SCREAMING_SNAKE_CASE =np.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
_SCREAMING_SNAKE_CASE =np.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
_SCREAMING_SNAKE_CASE =np.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": attention_mask,
}
class A__ :
def __init__( self : Optional[Any] , _a : Any , _a : Tuple=13 , _a : Union[str, Any]=7 , _a : Tuple=True , _a : str=False , _a : Union[str, Any]=99 , _a : str=16 , _a : int=2 , _a : Optional[int]=4 , _a : Optional[int]=4 , _a : Any="gelu" , _a : Union[str, Any]=0.1 , _a : Any=0.1 , _a : Any=32 , _a : List[str]=2 , _a : Tuple=1 , _a : List[str]=0 , _a : List[Any]=0.02 , ) -> Dict:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =parent
_SCREAMING_SNAKE_CASE =batch_size
_SCREAMING_SNAKE_CASE =seq_length
_SCREAMING_SNAKE_CASE =is_training
_SCREAMING_SNAKE_CASE =use_labels
_SCREAMING_SNAKE_CASE =vocab_size
_SCREAMING_SNAKE_CASE =hidden_size
_SCREAMING_SNAKE_CASE =num_hidden_layers
_SCREAMING_SNAKE_CASE =num_attention_heads
_SCREAMING_SNAKE_CASE =intermediate_size
_SCREAMING_SNAKE_CASE =hidden_act
_SCREAMING_SNAKE_CASE =hidden_dropout_prob
_SCREAMING_SNAKE_CASE =attention_probs_dropout_prob
_SCREAMING_SNAKE_CASE =max_position_embeddings
_SCREAMING_SNAKE_CASE =eos_token_id
_SCREAMING_SNAKE_CASE =pad_token_id
_SCREAMING_SNAKE_CASE =bos_token_id
_SCREAMING_SNAKE_CASE =initializer_range
def A ( self : Dict ) -> Optional[int]:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size )
_SCREAMING_SNAKE_CASE =np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 )
_SCREAMING_SNAKE_CASE =shift_tokens_right(_a , 1 , 2 )
_SCREAMING_SNAKE_CASE =BlenderbotSmallConfig(
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_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=_a , )
_SCREAMING_SNAKE_CASE =prepare_blenderbot_inputs_dict(_a , _a , _a )
return config, inputs_dict
def A ( self : Optional[int] ) -> Optional[int]:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs()
return config, inputs_dict
def A ( self : int , _a : List[Any] , _a : Tuple , _a : Optional[Any] ) -> Union[str, Any]:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =20
_SCREAMING_SNAKE_CASE =model_class_name(_a )
_SCREAMING_SNAKE_CASE =model.encode(inputs_dict['input_ids'] )
_SCREAMING_SNAKE_CASE =(
inputs_dict['decoder_input_ids'],
inputs_dict['decoder_attention_mask'],
)
_SCREAMING_SNAKE_CASE =model.init_cache(decoder_input_ids.shape[0] , _a , _a )
_SCREAMING_SNAKE_CASE =jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='i4' )
_SCREAMING_SNAKE_CASE =jnp.broadcast_to(
jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , )
_SCREAMING_SNAKE_CASE =model.decode(
decoder_input_ids[:, :-1] , _a , decoder_attention_mask=_a , past_key_values=_a , decoder_position_ids=_a , )
_SCREAMING_SNAKE_CASE =jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='i4' )
_SCREAMING_SNAKE_CASE =model.decode(
decoder_input_ids[:, -1:] , _a , decoder_attention_mask=_a , past_key_values=outputs_cache.past_key_values , decoder_position_ids=_a , )
_SCREAMING_SNAKE_CASE =model.decode(_a , _a )
_SCREAMING_SNAKE_CASE =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 A ( self : Any , _a : str , _a : str , _a : Any ) -> str:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =20
_SCREAMING_SNAKE_CASE =model_class_name(_a )
_SCREAMING_SNAKE_CASE =model.encode(inputs_dict['input_ids'] )
_SCREAMING_SNAKE_CASE =(
inputs_dict['decoder_input_ids'],
inputs_dict['decoder_attention_mask'],
)
_SCREAMING_SNAKE_CASE =jnp.concatenate(
[
decoder_attention_mask,
jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ),
] , axis=-1 , )
_SCREAMING_SNAKE_CASE =model.init_cache(decoder_input_ids.shape[0] , _a , _a )
_SCREAMING_SNAKE_CASE =jnp.broadcast_to(
jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , )
_SCREAMING_SNAKE_CASE =model.decode(
decoder_input_ids[:, :-1] , _a , decoder_attention_mask=_a , past_key_values=_a , decoder_position_ids=_a , )
_SCREAMING_SNAKE_CASE =jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='i4' )
_SCREAMING_SNAKE_CASE =model.decode(
decoder_input_ids[:, -1:] , _a , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=_a , decoder_position_ids=_a , )
_SCREAMING_SNAKE_CASE =model.decode(_a , _a , decoder_attention_mask=_a )
_SCREAMING_SNAKE_CASE =np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) )
self.parent.assertTrue(diff < 1e-3 , msg=f"Max diff is {diff}" )
@require_flax
class A__ ( unittest.TestCase ):
A__ = 99
def A ( self : Union[str, Any] ) -> List[str]:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =np.array(
[
[71, 82, 18, 33, 46, 91, 2],
[68, 34, 26, 58, 30, 82, 2],
[5, 97, 17, 39, 94, 40, 2],
[76, 83, 94, 25, 70, 78, 2],
[87, 59, 41, 35, 48, 66, 2],
[55, 13, 16, 58, 5, 2, 1], # note padding
[64, 27, 31, 51, 12, 75, 2],
[52, 64, 86, 17, 83, 39, 2],
[48, 61, 9, 24, 71, 82, 2],
[26, 1, 60, 48, 22, 13, 2],
[21, 5, 62, 28, 14, 76, 2],
[45, 98, 37, 86, 59, 48, 2],
[70, 70, 50, 9, 28, 0, 2],
] , dtype=np.intaa , )
_SCREAMING_SNAKE_CASE =input_ids.shape[0]
_SCREAMING_SNAKE_CASE =BlenderbotSmallConfig(
vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , )
return config, input_ids, batch_size
def A ( self : Optional[Any] ) -> Optional[int]:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self._get_config_and_data()
_SCREAMING_SNAKE_CASE =FlaxBlenderbotSmallForConditionalGeneration(_a )
_SCREAMING_SNAKE_CASE =lm_model(input_ids=_a )
_SCREAMING_SNAKE_CASE =(batch_size, input_ids.shape[1], config.vocab_size)
self.assertEqual(outputs['logits'].shape , _a )
def A ( self : Tuple ) -> Dict:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =BlenderbotSmallConfig(
vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , )
_SCREAMING_SNAKE_CASE =FlaxBlenderbotSmallForConditionalGeneration(_a )
_SCREAMING_SNAKE_CASE =np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa )
_SCREAMING_SNAKE_CASE =np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa )
_SCREAMING_SNAKE_CASE =lm_model(input_ids=_a , decoder_input_ids=_a )
_SCREAMING_SNAKE_CASE =(*summary.shape, config.vocab_size)
self.assertEqual(outputs['logits'].shape , _a )
def A ( self : Optional[Any] ) -> Dict:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa )
_SCREAMING_SNAKE_CASE =shift_tokens_right(_a , 1 , 2 )
_SCREAMING_SNAKE_CASE =np.equal(_a , 1 ).astype(np.floataa ).sum()
_SCREAMING_SNAKE_CASE =np.equal(_a , 1 ).astype(np.floataa ).sum()
self.assertEqual(shifted.shape , input_ids.shape )
self.assertEqual(_a , n_pad_before - 1 )
self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() )
@require_flax
class A__ ( snake_case_ , unittest.TestCase , snake_case_ ):
A__ = True
A__ = (
(
FlaxBlenderbotSmallModel,
FlaxBlenderbotSmallForConditionalGeneration,
)
if is_flax_available()
else ()
)
A__ = (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else ()
def A ( self : List[str] ) -> List[str]:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =FlaxBlenderbotSmallModelTester(self )
def A ( self : List[Any] ) -> Dict:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
self.model_tester.check_use_cache_forward(_a , _a , _a )
def A ( self : str ) -> Optional[Any]:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
self.model_tester.check_use_cache_forward_with_attn_mask(_a , _a , _a )
def A ( self : Optional[int] ) -> Any:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__ ):
_SCREAMING_SNAKE_CASE =self._prepare_for_class(_a , _a )
_SCREAMING_SNAKE_CASE =model_class(_a )
@jax.jit
def encode_jitted(_a : Optional[Any] , _a : int=None , **_a : Optional[int] ):
return model.encode(input_ids=_a , attention_mask=_a )
with self.subTest('JIT Enabled' ):
_SCREAMING_SNAKE_CASE =encode_jitted(**_a ).to_tuple()
with self.subTest('JIT Disabled' ):
with jax.disable_jit():
_SCREAMING_SNAKE_CASE =encode_jitted(**_a ).to_tuple()
self.assertEqual(len(_a ) , len(_a ) )
for jitted_output, output in zip(_a , _a ):
self.assertEqual(jitted_output.shape , output.shape )
def A ( self : List[Any] ) -> Tuple:
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__ ):
_SCREAMING_SNAKE_CASE =model_class(_a )
_SCREAMING_SNAKE_CASE =model.encode(inputs_dict['input_ids'] , inputs_dict['attention_mask'] )
_SCREAMING_SNAKE_CASE ={
'decoder_input_ids': inputs_dict['decoder_input_ids'],
'decoder_attention_mask': inputs_dict['decoder_attention_mask'],
'encoder_outputs': encoder_outputs,
}
@jax.jit
def decode_jitted(_a : Union[str, Any] , _a : Optional[int] , _a : Optional[int] ):
return model.decode(
decoder_input_ids=_a , decoder_attention_mask=_a , encoder_outputs=_a , )
with self.subTest('JIT Enabled' ):
_SCREAMING_SNAKE_CASE =decode_jitted(**_a ).to_tuple()
with self.subTest('JIT Disabled' ):
with jax.disable_jit():
_SCREAMING_SNAKE_CASE =decode_jitted(**_a ).to_tuple()
self.assertEqual(len(_a ) , len(_a ) )
for jitted_output, output in zip(_a , _a ):
self.assertEqual(jitted_output.shape , output.shape )
@slow
def A ( self : Union[str, Any] ) -> int:
'''simple docstring'''
for model_class_name in self.all_model_classes:
_SCREAMING_SNAKE_CASE =model_class_name.from_pretrained('facebook/blenderbot_small-90M' )
# FlaxBlenderbotForSequenceClassification expects eos token in input_ids
_SCREAMING_SNAKE_CASE =np.ones((1, 1) ) * model.config.eos_token_id
_SCREAMING_SNAKE_CASE =model(_a )
self.assertIsNotNone(_a )
| 405 | import warnings
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class _lowercase ( snake_case_ ):
lowercase = ['image_processor', 'tokenizer']
lowercase = 'LayoutLMv3ImageProcessor'
lowercase = ('LayoutLMv3Tokenizer', 'LayoutLMv3TokenizerFast')
def __init__( self : List[Any] , snake_case : int=None , snake_case : str=None , **snake_case : int ) -> Tuple:
"""simple docstring"""
UpperCamelCase_ : str = None
if "feature_extractor" in kwargs:
warnings.warn(
'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
' instead.' , snake_case , )
UpperCamelCase_ : Optional[Any] = kwargs.pop('feature_extractor' )
UpperCamelCase_ : Optional[Any] = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('You need to specify an `image_processor`.' )
if tokenizer is None:
raise ValueError('You need to specify a `tokenizer`.' )
super().__init__(snake_case , snake_case )
def __call__( self : Optional[Any] , snake_case : List[Any] , snake_case : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , snake_case : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , snake_case : Union[List[List[int]], List[List[List[int]]]] = None , snake_case : Optional[Union[List[int], List[List[int]]]] = None , snake_case : bool = True , snake_case : Union[bool, str, PaddingStrategy] = False , snake_case : Union[bool, str, TruncationStrategy] = None , snake_case : Optional[int] = None , snake_case : int = 0 , snake_case : Optional[int] = None , snake_case : Optional[bool] = None , snake_case : Optional[bool] = None , snake_case : bool = False , snake_case : bool = False , snake_case : bool = False , snake_case : bool = False , snake_case : bool = True , snake_case : Optional[Union[str, TensorType]] = None , **snake_case : Optional[int] , ) -> BatchEncoding:
"""simple docstring"""
if self.image_processor.apply_ocr and (boxes is not None):
raise ValueError(
'You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.' )
if self.image_processor.apply_ocr and (word_labels is not None):
raise ValueError(
'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.' )
# first, apply the image processor
UpperCamelCase_ : Optional[int] = self.image_processor(images=snake_case , return_tensors=snake_case )
# second, apply the tokenizer
if text is not None and self.image_processor.apply_ocr and text_pair is None:
if isinstance(snake_case , snake_case ):
UpperCamelCase_ : Optional[Any] = [text] # add batch dimension (as the image processor always adds a batch dimension)
UpperCamelCase_ : str = features['words']
UpperCamelCase_ : int = self.tokenizer(
text=text if text is not None else features['words'] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['boxes'] , word_labels=snake_case , add_special_tokens=snake_case , padding=snake_case , truncation=snake_case , max_length=snake_case , stride=snake_case , pad_to_multiple_of=snake_case , return_token_type_ids=snake_case , return_attention_mask=snake_case , return_overflowing_tokens=snake_case , return_special_tokens_mask=snake_case , return_offsets_mapping=snake_case , return_length=snake_case , verbose=snake_case , return_tensors=snake_case , **snake_case , )
# add pixel values
UpperCamelCase_ : int = features.pop('pixel_values' )
if return_overflowing_tokens is True:
UpperCamelCase_ : Optional[Any] = self.get_overflowing_images(snake_case , encoded_inputs['overflow_to_sample_mapping'] )
UpperCamelCase_ : List[str] = images
return encoded_inputs
def SCREAMING_SNAKE_CASE__ ( self : Any , snake_case : Any , snake_case : Dict ) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase_ : List[str] = []
for sample_idx in overflow_to_sample_mapping:
images_with_overflow.append(images[sample_idx] )
if len(snake_case ) != len(snake_case ):
raise ValueError(
'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'
f" {len(snake_case )} and {len(snake_case )}" )
return images_with_overflow
def SCREAMING_SNAKE_CASE__ ( self : List[str] , *snake_case : Dict , **snake_case : List[Any] ) -> Tuple:
"""simple docstring"""
return self.tokenizer.batch_decode(*snake_case , **snake_case )
def SCREAMING_SNAKE_CASE__ ( self : List[Any] , *snake_case : Optional[int] , **snake_case : int ) -> Any:
"""simple docstring"""
return self.tokenizer.decode(*snake_case , **snake_case )
@property
def SCREAMING_SNAKE_CASE__ ( self : str ) -> List[str]:
"""simple docstring"""
return ["input_ids", "bbox", "attention_mask", "pixel_values"]
@property
def SCREAMING_SNAKE_CASE__ ( self : int ) -> List[Any]:
"""simple docstring"""
warnings.warn(
'`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , snake_case , )
return self.image_processor_class
@property
def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
warnings.warn(
'`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , snake_case , )
return self.image_processor
| 417 | 0 |
import math
def __lowerCAmelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )-> float:
"""simple docstring"""
if (
not isinstance(SCREAMING_SNAKE_CASE , (int, float) )
or power_factor < -1
or power_factor > 1
):
raise ValueError('''power_factor must be a valid float value between -1 and 1.''' )
return apparent_power * power_factor
def __lowerCAmelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )-> float:
"""simple docstring"""
if (
not isinstance(SCREAMING_SNAKE_CASE , (int, float) )
or power_factor < -1
or power_factor > 1
):
raise ValueError('''power_factor must be a valid float value between -1 and 1.''' )
return apparent_power * math.sqrt(1 - power_factor**2 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 700 |
# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional
import numpy as np
import pyarrow as pa
from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter
if TYPE_CHECKING:
import jax
import jaxlib
UpperCAmelCase = get_logger()
UpperCAmelCase = None
class lowerCAmelCase_ ( TensorFormatter[Mapping, "jax.Array", Mapping] ):
'''simple docstring'''
def __init__( self , _UpperCAmelCase=None , _UpperCAmelCase=None , **_UpperCAmelCase ):
super().__init__(features=_UpperCAmelCase )
import jax
from jaxlib.xla_client import Device
if isinstance(_UpperCAmelCase , _UpperCAmelCase ):
raise ValueError(
F'''Expected {device} to be a `str` not {type(_UpperCAmelCase )}, as `jaxlib.xla_extension.Device` '''
'''is not serializable neither with `pickle` nor with `dill`. Instead you can surround '''
'''the device with `str()` to get its string identifier that will be internally mapped '''
'''to the actual `jaxlib.xla_extension.Device`.''' )
snake_case_ = device if isinstance(_UpperCAmelCase , _UpperCAmelCase ) else str(jax.devices()[0] )
# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
# with `pickle` nor with `dill`, so we need to use a global variable instead
global DEVICE_MAPPING
if DEVICE_MAPPING is None:
snake_case_ = self._map_devices_to_str()
if self.device not in list(DEVICE_MAPPING.keys() ):
logger.warning(
F'''Device with string identifier {self.device} not listed among the available '''
F'''devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default '''
F'''device: {str(jax.devices()[0] )}.''' )
snake_case_ = str(jax.devices()[0] )
snake_case_ = jnp_array_kwargs
@staticmethod
def UpperCamelCase__ ( ):
import jax
return {str(_UpperCAmelCase ): device for device in jax.devices()}
def UpperCamelCase__ ( self , _UpperCAmelCase ):
import jax
import jax.numpy as jnp
if isinstance(_UpperCAmelCase , _UpperCAmelCase ) and column:
if all(
isinstance(_UpperCAmelCase , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ):
return jnp.stack(_UpperCAmelCase , axis=0 )
return column
def UpperCamelCase__ ( self , _UpperCAmelCase ):
import jax
import jax.numpy as jnp
if isinstance(_UpperCAmelCase , (str, bytes, type(_UpperCAmelCase )) ):
return value
elif isinstance(_UpperCAmelCase , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ):
return value.tolist()
snake_case_ = {}
if isinstance(_UpperCAmelCase , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ):
# the default int precision depends on the jax config
# see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
if jax.config.jax_enable_xaa:
snake_case_ = {'''dtype''': jnp.intaa}
else:
snake_case_ = {'''dtype''': jnp.intaa}
elif isinstance(_UpperCAmelCase , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ):
snake_case_ = {'''dtype''': jnp.floataa}
elif config.PIL_AVAILABLE and "PIL" in sys.modules:
import PIL.Image
if isinstance(_UpperCAmelCase , PIL.Image.Image ):
snake_case_ = np.asarray(_UpperCAmelCase )
# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
# with `pickle` nor with `dill`, so we need to use a global variable instead
global DEVICE_MAPPING
if DEVICE_MAPPING is None:
snake_case_ = self._map_devices_to_str()
with jax.default_device(DEVICE_MAPPING[self.device] ):
# calling jnp.array on a np.ndarray does copy the data
# see https://github.com/google/jax/issues/4486
return jnp.array(_UpperCAmelCase , **{**default_dtype, **self.jnp_array_kwargs} )
def UpperCamelCase__ ( self , _UpperCAmelCase ):
import jax
# support for torch, tf, jax etc.
if config.TORCH_AVAILABLE and "torch" in sys.modules:
import torch
if isinstance(_UpperCAmelCase , torch.Tensor ):
return self._tensorize(data_struct.detach().cpu().numpy()[()] )
if hasattr(_UpperCAmelCase , '''__array__''' ) and not isinstance(_UpperCAmelCase , jax.Array ):
snake_case_ = data_struct.__array__()
# support for nested types like struct of list of struct
if isinstance(_UpperCAmelCase , np.ndarray ):
if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects
return self._consolidate([self.recursive_tensorize(_UpperCAmelCase ) for substruct in data_struct] )
elif isinstance(_UpperCAmelCase , (list, tuple) ):
return self._consolidate([self.recursive_tensorize(_UpperCAmelCase ) for substruct in data_struct] )
return self._tensorize(_UpperCAmelCase )
def UpperCamelCase__ ( self , _UpperCAmelCase ):
return map_nested(self._recursive_tensorize , _UpperCAmelCase , map_list=_UpperCAmelCase )
def UpperCamelCase__ ( self , _UpperCAmelCase ):
snake_case_ = self.numpy_arrow_extractor().extract_row(_UpperCAmelCase )
snake_case_ = self.python_features_decoder.decode_row(_UpperCAmelCase )
return self.recursive_tensorize(_UpperCAmelCase )
def UpperCamelCase__ ( self , _UpperCAmelCase ):
snake_case_ = self.numpy_arrow_extractor().extract_column(_UpperCAmelCase )
snake_case_ = self.python_features_decoder.decode_column(_UpperCAmelCase , pa_table.column_names[0] )
snake_case_ = self.recursive_tensorize(_UpperCAmelCase )
snake_case_ = self._consolidate(_UpperCAmelCase )
return column
def UpperCamelCase__ ( self , _UpperCAmelCase ):
snake_case_ = self.numpy_arrow_extractor().extract_batch(_UpperCAmelCase )
snake_case_ = self.python_features_decoder.decode_batch(_UpperCAmelCase )
snake_case_ = self.recursive_tensorize(_UpperCAmelCase )
for column_name in batch:
snake_case_ = self._consolidate(batch[column_name] )
return batch | 531 | 0 |
'''simple docstring'''
import collections
import json
import os
import re
from typing import TYPE_CHECKING, List, Optional, Tuple
import numpy as np
from ...tokenization_utils_fast import PreTrainedTokenizer
from ...utils import logging
if TYPE_CHECKING:
from transformers.pipelines.conversational import Conversation
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {"""vocab_file""": """vocab.txt""", """emoji_file""": """emoji.json"""}
_lowerCamelCase = {
"""vocab_file""": {
"""abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt""",
},
"""emoji_file""": {
"""abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json""",
},
}
_lowerCamelCase = {
"""abeja/gpt-neox-japanese-2.7b""": 2048,
}
def a__ ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
with open(UpperCamelCase__ , "r" , encoding="utf-8" ) as f:
UpperCAmelCase_ : Dict = json.loads(f.read() )
UpperCAmelCase_ : int = collections.OrderedDict()
UpperCAmelCase_ : int = collections.OrderedDict()
UpperCAmelCase_ : Optional[Any] = collections.OrderedDict()
with open(UpperCamelCase__ , "r" , encoding="utf-8" ) as f:
UpperCAmelCase_ : List[str] = f.readlines()
UpperCAmelCase_ : List[str] = [[t.rstrip("\n" )] if (t == "," or "," not in t) else t.rstrip("\n" ).split("," ) for t in token]
for idx, b in enumerate(UpperCamelCase__ ):
UpperCAmelCase_ : Tuple = b
UpperCAmelCase_ : Union[str, Any] = idx
for wd in b:
UpperCAmelCase_ : Union[str, Any] = idx
return vocab, raw_vocab, ids_to_tokens, emoji
class _snake_case (__SCREAMING_SNAKE_CASE):
__A : int =VOCAB_FILES_NAMES
__A : Tuple =PRETRAINED_VOCAB_FILES_MAP
__A : Any =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__A : Optional[Any] =["input_ids", "attention_mask"]
def __init__( self ,_snake_case ,_snake_case ,_snake_case="<|endoftext|>" ,_snake_case="<|endoftext|>" ,_snake_case="<|startoftext|>" ,_snake_case="<|endoftext|>" ,_snake_case=False ,**_snake_case ,):
super().__init__(
unk_token=__lowerCamelCase ,pad_token=__lowerCamelCase ,bos_token=__lowerCamelCase ,eos_token=__lowerCamelCase ,do_clean_text=__lowerCamelCase ,**__lowerCamelCase ,)
if not os.path.isfile(__lowerCamelCase ):
raise ValueError(
f'''Can\'t find a vocabulary file at path \'{vocab_file}\'. To load the vocabulary from a Google pretrained'''
" model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`" )
if not os.path.isfile(__lowerCamelCase ):
raise ValueError(
f'''Can\'t find a emoji file at path \'{emoji_file}\'. To load the emoji information from a Google'''
" pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`" )
UpperCAmelCase_ : int = do_clean_text
UpperCAmelCase_ : Union[str, Any] = load_vocab_and_emoji(__lowerCamelCase ,__lowerCamelCase )
UpperCAmelCase_ : str = SubWordJapaneseTokenizer(
vocab=self.vocab ,ids_to_tokens=self.ids_to_tokens ,emoji=self.emoji )
@property
def UpperCamelCase__ ( self ):
# self.vocab contains support for character fluctuation unique to Japanese, and has a large number of vocab
return len(self.raw_vocab )
def UpperCamelCase__ ( self ):
return dict(self.raw_vocab ,**self.added_tokens_encoder )
def UpperCamelCase__ ( self ,_snake_case ):
return self.subword_tokenizer.tokenize(__lowerCamelCase ,clean=self.do_clean_text )
def UpperCamelCase__ ( self ,_snake_case ):
return self.vocab.get(__lowerCamelCase ,self.vocab.get(self.unk_token ) )
def UpperCamelCase__ ( self ,_snake_case ):
return self.subword_tokenizer.convert_id_to_token(__lowerCamelCase )
def UpperCamelCase__ ( self ,_snake_case ):
UpperCAmelCase_ : Union[str, Any] = "".join(__lowerCamelCase ).strip()
return out_string
def UpperCamelCase__ ( self ,_snake_case ):
UpperCAmelCase_ : Union[str, Any] = []
for is_user, text in conversation.iter_texts():
input_ids.extend(self.encode(__lowerCamelCase ,add_special_tokens=__lowerCamelCase ) + [self.eos_token_id] )
if len(__lowerCamelCase ) > self.model_max_length:
UpperCAmelCase_ : Any = input_ids[-self.model_max_length :]
return input_ids
def UpperCamelCase__ ( self ,_snake_case ,_snake_case = None ):
UpperCAmelCase_ : Union[str, Any] = 0
if os.path.isdir(__lowerCamelCase ):
UpperCAmelCase_ : str = os.path.join(
__lowerCamelCase ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
UpperCAmelCase_ : Union[str, Any] = os.path.join(
__lowerCamelCase ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["emoji_file"] )
else:
UpperCAmelCase_ : List[str] = (
(filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["vocab_file"]
)
UpperCAmelCase_ : List[Any] = (
(filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["emoji_file"]
)
with open(__lowerCamelCase ,"w" ,encoding="utf-8" ) as writer:
for token_index, token in self.ids_to_tokens.items():
if index != token_index:
logger.warning(
f'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'''
" Please check that the vocabulary is not corrupted!" )
UpperCAmelCase_ : List[str] = token_index
writer.write(",".join(__lowerCamelCase ) + "\n" )
index += 1
with open(__lowerCamelCase ,"w" ,encoding="utf-8" ) as writer:
json.dump(self.emoji ,__lowerCamelCase )
return vocab_file, emoji_file
class _snake_case (__SCREAMING_SNAKE_CASE):
def __init__( self ,_snake_case ,_snake_case ,_snake_case ):
UpperCAmelCase_ : str = vocab # same as swe
UpperCAmelCase_ : Optional[int] = ids_to_tokens # same as bpe
UpperCAmelCase_ : Tuple = emoji
UpperCAmelCase_ : str = np.max([len(__lowerCamelCase ) for w in self.vocab.keys()] )
UpperCAmelCase_ : Any = re.compile(R"(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)" )
UpperCAmelCase_ : Dict = re.compile(R"[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*" )
UpperCAmelCase_ : List[str] = re.compile(R"[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}" )
UpperCAmelCase_ : Any = re.compile(
R"([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*" )
UpperCAmelCase_ : Any = re.compile(
R"(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*" )
UpperCAmelCase_ : Optional[Any] = re.compile(
R"((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*" )
UpperCAmelCase_ : Union[str, Any] = "─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿"
UpperCAmelCase_ : Union[str, Any] = "▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟"
UpperCAmelCase_ : int = str.maketrans({k: "<BLOCK>" for k in keisen + blocks} )
def __len__( self ):
return len(self.ids_to_tokens )
def UpperCamelCase__ ( self ,_snake_case ):
UpperCAmelCase_ : Union[str, Any] = self.content_repattera.sub("<URL>" ,__lowerCamelCase )
UpperCAmelCase_ : Union[str, Any] = self.content_repattera.sub("<EMAIL>" ,__lowerCamelCase )
UpperCAmelCase_ : str = self.content_repattera.sub("<TEL>" ,__lowerCamelCase )
UpperCAmelCase_ : List[str] = self.content_repattera.sub("<DATE>" ,__lowerCamelCase )
UpperCAmelCase_ : Union[str, Any] = self.content_repattera.sub("<DATE>" ,__lowerCamelCase )
UpperCAmelCase_ : Optional[Any] = self.content_repattera.sub("<PRICE>" ,__lowerCamelCase )
UpperCAmelCase_ : Tuple = content.translate(self.content_transa )
while "<BLOCK><BLOCK>" in content:
UpperCAmelCase_ : Dict = content.replace("<BLOCK><BLOCK>" ,"<BLOCK>" )
return content
def UpperCamelCase__ ( self ,_snake_case ,_snake_case=False ):
UpperCAmelCase_ : Optional[int] = text.replace(" " ,"<SP>" )
UpperCAmelCase_ : Tuple = text.replace(" " ,"<SP>" )
UpperCAmelCase_ : List[Any] = text.replace("\r\n" ,"<BR>" )
UpperCAmelCase_ : Union[str, Any] = text.replace("\n" ,"<BR>" )
UpperCAmelCase_ : List[str] = text.replace("\r" ,"<BR>" )
UpperCAmelCase_ : Tuple = text.replace("\t" ,"<TAB>" )
UpperCAmelCase_ : List[str] = text.replace("—" ,"ー" )
UpperCAmelCase_ : Dict = text.replace("−" ,"ー" )
for k, v in self.emoji["emoji"].items():
if k in text:
UpperCAmelCase_ : str = text.replace(__lowerCamelCase ,__lowerCamelCase )
if clean:
UpperCAmelCase_ : List[Any] = self.clean_text(__lowerCamelCase )
def check_simbol(_snake_case ):
UpperCAmelCase_ : Optional[Any] = x.encode()
if len(__lowerCamelCase ) == 1 and len(__lowerCamelCase ) == 2:
UpperCAmelCase_ : int = (int(e[0] ) << 8) + int(e[1] )
if (
(c >= 0xC_2A1 and c <= 0xC_2BF)
or (c >= 0xC_780 and c <= 0xC_783)
or (c >= 0xC_AB9 and c <= 0xC_BBF)
or (c >= 0xC_C80 and c <= 0xC_DA2)
):
return True
return False
def checkuae(_snake_case ):
UpperCAmelCase_ : int = x.encode()
if len(__lowerCamelCase ) == 1 and len(__lowerCamelCase ) == 3:
UpperCAmelCase_ : Tuple = (int(e[0] ) << 16) + (int(e[1] ) << 8) + int(e[2] )
if c >= 0xE28_080 and c <= 0xE2B_07F:
return True
return False
UpperCAmelCase_ : Dict = 0
UpperCAmelCase_ : Dict = []
while pos < len(__lowerCamelCase ):
UpperCAmelCase_ : str = min(len(__lowerCamelCase ) ,pos + self.maxlen + 1 ) if text[pos] == "<" else pos + 3
UpperCAmelCase_ : Tuple = [] # (token_id, token, pos)
for e in range(__lowerCamelCase ,__lowerCamelCase ,-1 ):
UpperCAmelCase_ : int = text[pos:e]
if wd in self.vocab:
if wd[0] == "<" and len(__lowerCamelCase ) > 2:
UpperCAmelCase_ : Optional[Any] = [(self.vocab[wd], wd, e)]
break
else:
candidates.append((self.vocab[wd], wd, e) )
if len(__lowerCamelCase ) > 0:
# the smallest token_id is adopted
UpperCAmelCase_ : Optional[Any] = sorted(__lowerCamelCase ,key=lambda _snake_case : x[0] )[0]
result.append(__lowerCamelCase )
UpperCAmelCase_ : Tuple = e
else:
UpperCAmelCase_ : Dict = pos + 1
UpperCAmelCase_ : List[Any] = text[pos:end]
if check_simbol(__lowerCamelCase ):
result.append("<KIGOU>" )
elif checkuae(__lowerCamelCase ):
result.append("<U2000U2BFF>" )
else:
for i in wd.encode("utf-8" ):
result.append("<|byte%d|>" % i )
UpperCAmelCase_ : List[str] = end
return result
def UpperCamelCase__ ( self ,_snake_case ,_snake_case="\n" ):
UpperCAmelCase_ : List[Any] = []
UpperCAmelCase_ : str = []
UpperCAmelCase_ : Optional[int] = self.ids_to_tokens[index][0]
if word[:6] == "<|byte" and word[-2:] == "|>":
byte_tokens.append(int(word[6:-2] ) )
else:
if len(__lowerCamelCase ) > 0:
words.append(bytearray(__lowerCamelCase ).decode("utf-8" ,errors="replace" ) )
UpperCAmelCase_ : int = []
if word[:7] == "<|emoji" and word[-2:] == "|>":
words.append(self.emoji["emoji_inv"][word] )
elif word == "<SP>":
words.append(" " )
elif word == "<BR>":
words.append(__lowerCamelCase )
elif word == "<TAB>":
words.append("\t" )
elif word == "<BLOCK>":
words.append("▀" )
elif word == "<KIGOU>":
words.append("ǀ" )
elif word == "<U2000U2BFF>":
words.append("‖" )
else:
words.append(__lowerCamelCase )
if len(__lowerCamelCase ) > 0:
words.append(bytearray(__lowerCamelCase ).decode("utf-8" ,errors="replace" ) )
UpperCAmelCase_ : List[Any] = "".join(__lowerCamelCase )
return text
| 71 |
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 _UpperCAmelCase (UpperCamelCase__ : List[Any] , UpperCamelCase__ : str ):
assert isinstance(UpperCamelCase__ , UpperCamelCase__ )
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 _UpperCAmelCase (UpperCamelCase__ : str , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Dict ):
_A : Any = tmp_path / "cache"
_A : int = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
_A : List[str] = ParquetDatasetReader(UpperCamelCase__ , cache_dir=UpperCamelCase__ , keep_in_memory=UpperCamelCase__ ).read()
_check_parquet_dataset(UpperCamelCase__ , UpperCamelCase__ )
@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 _UpperCAmelCase (UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[int] ):
_A : Dict = tmp_path / "cache"
_A : List[str] = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
_A : Optional[Any] = features.copy() if features else default_expected_features
_A : Union[str, Any] = (
Features({feature: Value(UpperCamelCase__ ) for feature, dtype in features.items()} ) if features is not None else None
)
_A : int = ParquetDatasetReader(UpperCamelCase__ , features=UpperCamelCase__ , cache_dir=UpperCamelCase__ ).read()
_check_parquet_dataset(UpperCamelCase__ , UpperCamelCase__ )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def _UpperCAmelCase (UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : List[str] ):
_A : Any = tmp_path / "cache"
_A : Tuple = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
_A : List[str] = ParquetDatasetReader(UpperCamelCase__ , cache_dir=UpperCamelCase__ , split=UpperCamelCase__ ).read()
_check_parquet_dataset(UpperCamelCase__ , UpperCamelCase__ )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize("path_type" , [str, list] )
def _UpperCAmelCase (UpperCamelCase__ : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Any ):
if issubclass(UpperCamelCase__ , UpperCamelCase__ ):
_A : Optional[int] = parquet_path
elif issubclass(UpperCamelCase__ , UpperCamelCase__ ):
_A : Optional[int] = [parquet_path]
_A : Dict = tmp_path / "cache"
_A : Union[str, Any] = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
_A : Tuple = ParquetDatasetReader(UpperCamelCase__ , cache_dir=UpperCamelCase__ ).read()
_check_parquet_dataset(UpperCamelCase__ , UpperCamelCase__ )
def _UpperCAmelCase (UpperCamelCase__ : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : Union[str, Any]=("train",) ):
assert isinstance(UpperCamelCase__ , UpperCamelCase__ )
for split in splits:
_A : List[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 _UpperCAmelCase (UpperCamelCase__ : int , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any] ):
_A : Tuple = tmp_path / "cache"
_A : Any = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
_A : List[str] = ParquetDatasetReader(
{"train": parquet_path} , cache_dir=UpperCamelCase__ , keep_in_memory=UpperCamelCase__ ).read()
_check_parquet_datasetdict(UpperCamelCase__ , UpperCamelCase__ )
@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 _UpperCAmelCase (UpperCamelCase__ : List[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int] ):
_A : Optional[int] = tmp_path / "cache"
_A : Any = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
_A : str = features.copy() if features else default_expected_features
_A : Any = (
Features({feature: Value(UpperCamelCase__ ) for feature, dtype in features.items()} ) if features is not None else None
)
_A : int = ParquetDatasetReader({"train": parquet_path} , features=UpperCamelCase__ , cache_dir=UpperCamelCase__ ).read()
_check_parquet_datasetdict(UpperCamelCase__ , UpperCamelCase__ )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def _UpperCAmelCase (UpperCamelCase__ : List[str] , UpperCamelCase__ : int , UpperCamelCase__ : int ):
if split:
_A : Any = {split: parquet_path}
else:
_A : Optional[Any] = "train"
_A : int = {"train": parquet_path, "test": parquet_path}
_A : Any = tmp_path / "cache"
_A : str = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
_A : Dict = ParquetDatasetReader(UpperCamelCase__ , cache_dir=UpperCamelCase__ ).read()
_check_parquet_datasetdict(UpperCamelCase__ , UpperCamelCase__ , splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
def _UpperCAmelCase (UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] ):
_A : Union[str, Any] = ParquetDatasetWriter(UpperCamelCase__ , tmp_path / "foo.parquet" )
assert writer.write() > 0
_A : List[Any] = pq.ParquetFile(tmp_path / "foo.parquet" )
_A : List[str] = pf.read()
assert dataset.data.table == output_table
def _UpperCAmelCase (UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any] ):
_A : Any = str(shared_datadir / "test_image_rgb.jpg" )
_A : Dict = {"image": [image_path]}
_A : Union[str, Any] = Features({"image": Image()} )
_A : List[Any] = Dataset.from_dict(UpperCamelCase__ , features=UpperCamelCase__ )
_A : Any = ParquetDatasetWriter(UpperCamelCase__ , tmp_path / "foo.parquet" )
assert writer.write() > 0
_A : Optional[int] = Dataset.from_parquet(str(tmp_path / "foo.parquet" ) )
assert dataset.features == reloaded_dataset.features
_A : Union[str, Any] = ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=UpperCamelCase__ ).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 _UpperCAmelCase (UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] ):
assert get_writer_batch_size(UpperCamelCase__ ) == expected
| 503 | 0 |
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 (
SwiftFormerConfig,
SwiftFormerForImageClassification,
ViTImageProcessor,
)
from transformers.utils import logging
logging.set_verbosity_info()
_lowerCAmelCase : List[str] = logging.get_logger(__name__)
_lowerCAmelCase : Optional[Any] = torch.device("cpu")
def UpperCAmelCase_ ( ) -> int:
"""simple docstring"""
lowerCAmelCase__ = 'http://images.cocodataset.org/val2017/000000039769.jpg'
lowerCAmelCase__ = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw )
return im
def UpperCAmelCase_ ( snake_case__ ) -> Tuple:
"""simple docstring"""
if swiftformer_name == "swiftformer_xs":
return torch.tensor([-2.17_03E00, 2.11_07E00, -2.08_11E00, 8.86_85E-01, 2.43_60E-01] )
elif swiftformer_name == "swiftformer_s":
return torch.tensor([3.96_36E-01, 2.34_78E-01, -1.69_63E00, -1.73_81E00, -8.63_37E-01] )
elif swiftformer_name == "swiftformer_l1":
return torch.tensor([-4.27_68E-01, -4.74_29E-01, -1.08_97E00, -1.02_48E00, 3.55_23E-02] )
elif swiftformer_name == "swiftformer_l3":
return torch.tensor([-2.53_30E-01, 2.42_11E-01, -6.01_85E-01, -8.27_89E-01, -6.04_46E-02] )
def UpperCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ) -> int:
"""simple docstring"""
lowerCAmelCase__ = dct.pop(snake_case__ )
lowerCAmelCase__ = val
def UpperCAmelCase_ ( snake_case__ ) -> Optional[Any]:
"""simple docstring"""
lowerCAmelCase__ = []
for k in state_dict.keys():
lowerCAmelCase__ = k
if ".pwconv" in k:
lowerCAmelCase__ = k_new.replace('.pwconv' , '.point_wise_conv' )
if ".dwconv" in k:
lowerCAmelCase__ = k_new.replace('.dwconv' , '.depth_wise_conv' )
if ".Proj." in k:
lowerCAmelCase__ = k_new.replace('.Proj.' , '.proj.' )
if "patch_embed" in k_new:
lowerCAmelCase__ = k_new.replace('patch_embed' , 'swiftformer.patch_embed.patch_embedding' )
if "network" in k_new:
lowerCAmelCase__ = k_new.split('.' )
if ls[2].isdigit():
lowerCAmelCase__ = 'swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:] )
else:
lowerCAmelCase__ = k_new.replace('network' , 'swiftformer.encoder.network' )
rename_keys.append((k, k_new) )
return rename_keys
@torch.no_grad()
def UpperCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ) -> Union[str, Any]:
"""simple docstring"""
lowerCAmelCase__ = SwiftFormerConfig()
# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
lowerCAmelCase__ = 1000
lowerCAmelCase__ = 'huggingface/label-files'
lowerCAmelCase__ = 'imagenet-1k-id2label.json'
lowerCAmelCase__ = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) )
lowerCAmelCase__ = {int(snake_case__ ): v for k, v in idalabel.items()}
lowerCAmelCase__ = idalabel
lowerCAmelCase__ = {v: k for k, v in idalabel.items()}
# size of the architecture
if swiftformer_name == "swiftformer_xs":
lowerCAmelCase__ = [3, 3, 6, 4]
lowerCAmelCase__ = [48, 56, 112, 220]
elif swiftformer_name == "swiftformer_s":
lowerCAmelCase__ = [3, 3, 9, 6]
lowerCAmelCase__ = [48, 64, 168, 224]
elif swiftformer_name == "swiftformer_l1":
lowerCAmelCase__ = [4, 3, 10, 5]
lowerCAmelCase__ = [48, 96, 192, 384]
elif swiftformer_name == "swiftformer_l3":
lowerCAmelCase__ = [4, 4, 12, 6]
lowerCAmelCase__ = [64, 128, 320, 512]
# load state_dict of original model, remove and rename some keys
if original_ckpt:
if original_ckpt.startswith('https' ):
lowerCAmelCase__ = torch.hub.load_state_dict_from_url(snake_case__ , map_location='cpu' , check_hash=snake_case__ )
else:
lowerCAmelCase__ = torch.load(snake_case__ , map_location='cpu' )
lowerCAmelCase__ = checkpoint
lowerCAmelCase__ = create_rename_keys(snake_case__ )
for rename_key_src, rename_key_dest in rename_keys:
rename_key(snake_case__ , snake_case__ , snake_case__ )
# load HuggingFace model
lowerCAmelCase__ = SwiftFormerForImageClassification(snake_case__ ).eval()
hf_model.load_state_dict(snake_case__ )
# prepare test inputs
lowerCAmelCase__ = prepare_img()
lowerCAmelCase__ = ViTImageProcessor.from_pretrained('preprocessor_config' )
lowerCAmelCase__ = processor(images=snake_case__ , return_tensors='pt' )
# compare outputs from both models
lowerCAmelCase__ = get_expected_output(snake_case__ )
lowerCAmelCase__ = hf_model(inputs['pixel_values'] ).logits
assert hf_logits.shape == torch.Size([1, 1000] )
assert torch.allclose(hf_logits[0, 0:5] , snake_case__ , atol=1E-3 )
Path(snake_case__ ).mkdir(exist_ok=snake_case__ )
print(f'Saving model {swiftformer_name} to {pytorch_dump_folder_path}' )
hf_model.save_pretrained(snake_case__ )
if __name__ == "__main__":
_lowerCAmelCase : int = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--swiftformer_name",
default="swiftformer_xs",
choices=["swiftformer_xs", "swiftformer_s", "swiftformer_l1", "swiftformer_l3"],
type=str,
help="Name of the SwiftFormer model you'd like to convert.",
)
parser.add_argument(
"--pytorch_dump_folder_path",
default="./converted_outputs/",
type=str,
help="Path to the output PyTorch model directory.",
)
parser.add_argument("--original_ckpt", default=None, type=str, help="Path to the original model checkpoint.")
_lowerCAmelCase : str = parser.parse_args()
convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
| 604 |
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 DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig
from transformers.utils import logging
logging.set_verbosity_info()
_lowerCAmelCase : str = logging.get_logger(__name__)
def UpperCAmelCase_ ( snake_case__ ) -> Optional[int]:
"""simple docstring"""
if "resnet-50" in model_name:
lowerCAmelCase__ = ResNetConfig.from_pretrained('microsoft/resnet-50' )
elif "resnet-101" in model_name:
lowerCAmelCase__ = ResNetConfig.from_pretrained('microsoft/resnet-101' )
else:
raise ValueError('Model name should include either resnet50 or resnet101' )
lowerCAmelCase__ = DetrConfig(use_timm_backbone=snake_case__ , backbone_config=snake_case__ )
# set label attributes
lowerCAmelCase__ = 'panoptic' in model_name
if is_panoptic:
lowerCAmelCase__ = 250
else:
lowerCAmelCase__ = 91
lowerCAmelCase__ = 'huggingface/label-files'
lowerCAmelCase__ = 'coco-detection-id2label.json'
lowerCAmelCase__ = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) )
lowerCAmelCase__ = {int(snake_case__ ): v for k, v in idalabel.items()}
lowerCAmelCase__ = idalabel
lowerCAmelCase__ = {v: k for k, v in idalabel.items()}
return config, is_panoptic
def UpperCAmelCase_ ( snake_case__ ) -> Any:
"""simple docstring"""
lowerCAmelCase__ = []
# stem
# fmt: off
rename_keys.append(('backbone.0.body.conv1.weight', 'backbone.conv_encoder.model.embedder.embedder.convolution.weight') )
rename_keys.append(('backbone.0.body.bn1.weight', 'backbone.conv_encoder.model.embedder.embedder.normalization.weight') )
rename_keys.append(('backbone.0.body.bn1.bias', 'backbone.conv_encoder.model.embedder.embedder.normalization.bias') )
rename_keys.append(('backbone.0.body.bn1.running_mean', 'backbone.conv_encoder.model.embedder.embedder.normalization.running_mean') )
rename_keys.append(('backbone.0.body.bn1.running_var', 'backbone.conv_encoder.model.embedder.embedder.normalization.running_var') )
# stages
for stage_idx in range(len(config.backbone_config.depths ) ):
for layer_idx in range(config.backbone_config.depths[stage_idx] ):
# shortcut
if layer_idx == 0:
rename_keys.append(
(
f'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight',
f'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight',
) )
rename_keys.append(
(
f'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight',
f'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight',
) )
rename_keys.append(
(
f'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias',
f'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias',
) )
rename_keys.append(
(
f'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean',
f'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean',
) )
rename_keys.append(
(
f'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var',
f'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var',
) )
# 3 convs
for i in range(3 ):
rename_keys.append(
(
f'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight',
f'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight',
) )
rename_keys.append(
(
f'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight',
f'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight',
) )
rename_keys.append(
(
f'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias',
f'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias',
) )
rename_keys.append(
(
f'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean',
f'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean',
) )
rename_keys.append(
(
f'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var',
f'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var',
) )
# fmt: on
for i in range(config.encoder_layers ):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append(
(
f'transformer.encoder.layers.{i}.self_attn.out_proj.weight',
f'encoder.layers.{i}.self_attn.out_proj.weight',
) )
rename_keys.append(
(f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') )
rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight') )
rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias') )
rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight') )
rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias') )
rename_keys.append(
(f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') )
rename_keys.append(
(f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias') )
rename_keys.append(
(f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight') )
rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias') )
# decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms
rename_keys.append(
(
f'transformer.decoder.layers.{i}.self_attn.out_proj.weight',
f'decoder.layers.{i}.self_attn.out_proj.weight',
) )
rename_keys.append(
(f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') )
rename_keys.append(
(
f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight',
f'decoder.layers.{i}.encoder_attn.out_proj.weight',
) )
rename_keys.append(
(
f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias',
f'decoder.layers.{i}.encoder_attn.out_proj.bias',
) )
rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight') )
rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias') )
rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight') )
rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias') )
rename_keys.append(
(f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') )
rename_keys.append(
(f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias') )
rename_keys.append(
(f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') )
rename_keys.append(
(f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') )
rename_keys.append(
(f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight') )
rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias') )
# convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads
rename_keys.extend(
[
('input_proj.weight', 'input_projection.weight'),
('input_proj.bias', 'input_projection.bias'),
('query_embed.weight', 'query_position_embeddings.weight'),
('transformer.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'),
] )
return rename_keys
def UpperCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ) -> List[Any]:
"""simple docstring"""
lowerCAmelCase__ = state_dict.pop(snake_case__ )
lowerCAmelCase__ = val
def UpperCAmelCase_ ( snake_case__ , snake_case__=False ) -> str:
"""simple docstring"""
lowerCAmelCase__ = ''
if is_panoptic:
lowerCAmelCase__ = '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__ = state_dict.pop(f'{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight' )
lowerCAmelCase__ = 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__ = in_proj_weight[:256, :]
lowerCAmelCase__ = in_proj_bias[:256]
lowerCAmelCase__ = in_proj_weight[256:512, :]
lowerCAmelCase__ = in_proj_bias[256:512]
lowerCAmelCase__ = in_proj_weight[-256:, :]
lowerCAmelCase__ = in_proj_bias[-256:]
# next: transformer decoder (which is a bit more complex because it also includes cross-attention)
for i in range(6 ):
# read in weights + bias of input projection layer of self-attention
lowerCAmelCase__ = state_dict.pop(f'{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight' )
lowerCAmelCase__ = state_dict.pop(f'{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias' )
# next, add query, keys and values (in that order) to the state dict
lowerCAmelCase__ = in_proj_weight[:256, :]
lowerCAmelCase__ = in_proj_bias[:256]
lowerCAmelCase__ = in_proj_weight[256:512, :]
lowerCAmelCase__ = in_proj_bias[256:512]
lowerCAmelCase__ = in_proj_weight[-256:, :]
lowerCAmelCase__ = in_proj_bias[-256:]
# read in weights + bias of input projection layer of cross-attention
lowerCAmelCase__ = state_dict.pop(
f'{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight' )
lowerCAmelCase__ = state_dict.pop(f'{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias' )
# next, add query, keys and values (in that order) of cross-attention to the state dict
lowerCAmelCase__ = in_proj_weight_cross_attn[:256, :]
lowerCAmelCase__ = in_proj_bias_cross_attn[:256]
lowerCAmelCase__ = in_proj_weight_cross_attn[256:512, :]
lowerCAmelCase__ = in_proj_bias_cross_attn[256:512]
lowerCAmelCase__ = in_proj_weight_cross_attn[-256:, :]
lowerCAmelCase__ = in_proj_bias_cross_attn[-256:]
def UpperCAmelCase_ ( ) -> Any:
"""simple docstring"""
lowerCAmelCase__ = 'http://images.cocodataset.org/val2017/000000039769.jpg'
lowerCAmelCase__ = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw )
return im
@torch.no_grad()
def UpperCAmelCase_ ( snake_case__ , snake_case__=None , snake_case__=False ) -> List[str]:
"""simple docstring"""
lowerCAmelCase__ , lowerCAmelCase__ = get_detr_config(snake_case__ )
# load original model from torch hub
lowerCAmelCase__ = {
'detr-resnet-50': 'detr_resnet50',
'detr-resnet-101': 'detr_resnet101',
}
logger.info(f'Converting model {model_name}...' )
lowerCAmelCase__ = torch.hub.load('facebookresearch/detr' , model_name_to_original_name[model_name] , pretrained=snake_case__ ).eval()
lowerCAmelCase__ = detr.state_dict()
# rename keys
for src, dest in create_rename_keys(snake_case__ ):
if is_panoptic:
lowerCAmelCase__ = 'detr.' + src
rename_key(snake_case__ , snake_case__ , snake_case__ )
# query, key and value matrices need special treatment
read_in_q_k_v(snake_case__ , is_panoptic=snake_case__ )
# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
lowerCAmelCase__ = 'detr.model.' if is_panoptic else 'model.'
for key in state_dict.copy().keys():
if is_panoptic:
if (
key.startswith('detr' )
and not key.startswith('class_labels_classifier' )
and not key.startswith('bbox_predictor' )
):
lowerCAmelCase__ = state_dict.pop(snake_case__ )
lowerCAmelCase__ = val
elif "class_labels_classifier" in key or "bbox_predictor" in key:
lowerCAmelCase__ = state_dict.pop(snake_case__ )
lowerCAmelCase__ = val
elif key.startswith('bbox_attention' ) or key.startswith('mask_head' ):
continue
else:
lowerCAmelCase__ = state_dict.pop(snake_case__ )
lowerCAmelCase__ = val
else:
if not key.startswith('class_labels_classifier' ) and not key.startswith('bbox_predictor' ):
lowerCAmelCase__ = state_dict.pop(snake_case__ )
lowerCAmelCase__ = val
# finally, create HuggingFace model and load state dict
lowerCAmelCase__ = DetrForSegmentation(snake_case__ ) if is_panoptic else DetrForObjectDetection(snake_case__ )
model.load_state_dict(snake_case__ )
model.eval()
# verify our conversion on an image
lowerCAmelCase__ = 'coco_panoptic' if is_panoptic else 'coco_detection'
lowerCAmelCase__ = DetrImageProcessor(format=snake_case__ )
lowerCAmelCase__ = processor(images=prepare_img() , return_tensors='pt' )
lowerCAmelCase__ = encoding['pixel_values']
lowerCAmelCase__ = detr(snake_case__ )
lowerCAmelCase__ = model(snake_case__ )
assert torch.allclose(outputs.logits , original_outputs['pred_logits'] , atol=1E-3 )
assert torch.allclose(outputs.pred_boxes , original_outputs['pred_boxes'] , atol=1E-3 )
if is_panoptic:
assert torch.allclose(outputs.pred_masks , original_outputs['pred_masks'] , atol=1E-4 )
print('Looks ok!' )
if pytorch_dump_folder_path is not None:
# Save model and image processor
logger.info(f'Saving PyTorch model and image processor to {pytorch_dump_folder_path}...' )
Path(snake_case__ ).mkdir(exist_ok=snake_case__ )
model.save_pretrained(snake_case__ )
processor.save_pretrained(snake_case__ )
if push_to_hub:
# Upload model and image processor to the hub
logger.info('Uploading PyTorch model and image processor to the hub...' )
model.push_to_hub(f'nielsr/{model_name}' )
processor.push_to_hub(f'nielsr/{model_name}' )
if __name__ == "__main__":
_lowerCAmelCase : Dict = argparse.ArgumentParser()
parser.add_argument(
"--model_name",
default="detr-resnet-50",
type=str,
choices=["detr-resnet-50", "detr-resnet-101"],
help="Name of the 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."
)
parser.add_argument("--push_to_hub", action="store_true", help="Whether to push the model to the hub or not.")
_lowerCAmelCase : List[Any] = parser.parse_args()
convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 604 | 1 |
from typing import List
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCAmelCase__ : Optional[Any] = logging.get_logger(__name__)
UpperCAmelCase__ : Optional[int] = {
"snap-research/efficientformer-l1-300": (
"https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json"
),
}
class __lowercase ( lowerCamelCase__ ):
__UpperCAmelCase = '''efficientformer'''
def __init__( self , lowercase_ = [3, 2, 6, 4] , lowercase_ = [4_8, 9_6, 2_2_4, 4_4_8] , lowercase_ = [True, True, True, True] , lowercase_ = 4_4_8 , lowercase_ = 3_2 , lowercase_ = 4 , lowercase_ = 7 , lowercase_ = 5 , lowercase_ = 8 , lowercase_ = 4 , lowercase_ = 0.0 , lowercase_ = 1_6 , lowercase_ = 3 , lowercase_ = 3 , lowercase_ = 3 , lowercase_ = 2 , lowercase_ = 1 , lowercase_ = 0.0 , lowercase_ = 1 , lowercase_ = True , lowercase_ = True , lowercase_ = 1e-5 , lowercase_ = "gelu" , lowercase_ = 0.02 , lowercase_ = 1e-12 , lowercase_ = 2_2_4 , lowercase_ = 1e-05 , **lowercase_ , ) -> None:
super().__init__(**lowercase_)
__snake_case = hidden_act
__snake_case = hidden_dropout_prob
__snake_case = hidden_sizes
__snake_case = num_hidden_layers
__snake_case = num_attention_heads
__snake_case = initializer_range
__snake_case = layer_norm_eps
__snake_case = patch_size
__snake_case = num_channels
__snake_case = depths
__snake_case = mlp_expansion_ratio
__snake_case = downsamples
__snake_case = dim
__snake_case = key_dim
__snake_case = attention_ratio
__snake_case = resolution
__snake_case = pool_size
__snake_case = downsample_patch_size
__snake_case = downsample_stride
__snake_case = downsample_pad
__snake_case = drop_path_rate
__snake_case = num_metaad_blocks
__snake_case = distillation
__snake_case = use_layer_scale
__snake_case = layer_scale_init_value
__snake_case = image_size
__snake_case = batch_norm_eps
| 313 |
import unittest
import numpy as np
import timeout_decorator # noqa
from transformers import BlenderbotConfig, is_flax_available
from transformers.testing_utils import jax_device, require_flax, slow
from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor
if is_flax_available():
import os
# The slow tests are often failing with OOM error on GPU
# This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
# but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
UpperCAmelCase__ : int = "platform"
import jax
import jax.numpy as jnp
from transformers import BlenderbotTokenizer
from transformers.models.blenderbot.modeling_flax_blenderbot import (
FlaxBlenderbotForConditionalGeneration,
FlaxBlenderbotModel,
shift_tokens_right,
)
def A ( snake_case__ : List[str] , snake_case__ : Dict , snake_case__ : Optional[int]=None , snake_case__ : str=None , snake_case__ : Union[str, Any]=None , snake_case__ : List[Any]=None , snake_case__ : Optional[int]=None , snake_case__ : Optional[int]=None , ) -> List[str]:
'''simple docstring'''
if attention_mask is None:
__snake_case = np.where(input_ids != config.pad_token_id , 1 , 0 )
if decoder_attention_mask is None:
__snake_case = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 )
if head_mask is None:
__snake_case = np.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
__snake_case = np.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
__snake_case = np.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": attention_mask,
}
class __lowercase :
def __init__( self , lowercase_ , lowercase_=1_3 , lowercase_=7 , lowercase_=True , lowercase_=False , lowercase_=9_9 , lowercase_=1_6 , lowercase_=2 , lowercase_=4 , lowercase_=4 , lowercase_="gelu" , lowercase_=0.1 , lowercase_=0.1 , lowercase_=3_2 , lowercase_=2 , lowercase_=1 , lowercase_=0 , lowercase_=0.02 , ) -> Optional[int]:
__snake_case = parent
__snake_case = batch_size
__snake_case = seq_length
__snake_case = is_training
__snake_case = use_labels
__snake_case = vocab_size
__snake_case = hidden_size
__snake_case = num_hidden_layers
__snake_case = num_attention_heads
__snake_case = intermediate_size
__snake_case = hidden_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = eos_token_id
__snake_case = pad_token_id
__snake_case = bos_token_id
__snake_case = initializer_range
def _a ( self) -> Any:
__snake_case = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size) , 3 , self.vocab_size)
__snake_case = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa)) , -1)
__snake_case = shift_tokens_right(lowercase_ , 1 , 2)
__snake_case = BlenderbotConfig(
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_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=lowercase_ , )
__snake_case = prepare_blenderbot_inputs_dict(lowercase_ , lowercase_ , lowercase_)
return config, inputs_dict
def _a ( self) -> List[str]:
__snake_case , __snake_case = self.prepare_config_and_inputs()
return config, inputs_dict
def _a ( self , lowercase_ , lowercase_ , lowercase_) -> Tuple:
__snake_case = 2_0
__snake_case = model_class_name(lowercase_)
__snake_case = model.encode(inputs_dict['input_ids'])
__snake_case , __snake_case = (
inputs_dict['decoder_input_ids'],
inputs_dict['decoder_attention_mask'],
)
__snake_case = model.init_cache(decoder_input_ids.shape[0] , lowercase_ , lowercase_)
__snake_case = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='i4')
__snake_case = jnp.broadcast_to(
jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , )
__snake_case = model.decode(
decoder_input_ids[:, :-1] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=lowercase_ , decoder_position_ids=lowercase_ , )
__snake_case = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='i4')
__snake_case = model.decode(
decoder_input_ids[:, -1:] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowercase_ , )
__snake_case = model.decode(lowercase_ , lowercase_)
__snake_case = 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 _a ( self , lowercase_ , lowercase_ , lowercase_) -> List[Any]:
__snake_case = 2_0
__snake_case = model_class_name(lowercase_)
__snake_case = model.encode(inputs_dict['input_ids'])
__snake_case , __snake_case = (
inputs_dict['decoder_input_ids'],
inputs_dict['decoder_attention_mask'],
)
__snake_case = jnp.concatenate(
[
decoder_attention_mask,
jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])),
] , axis=-1 , )
__snake_case = model.init_cache(decoder_input_ids.shape[0] , lowercase_ , lowercase_)
__snake_case = jnp.broadcast_to(
jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , )
__snake_case = model.decode(
decoder_input_ids[:, :-1] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=lowercase_ , decoder_position_ids=lowercase_ , )
__snake_case = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='i4')
__snake_case = model.decode(
decoder_input_ids[:, -1:] , lowercase_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowercase_ , decoder_position_ids=lowercase_ , )
__snake_case = model.decode(lowercase_ , lowercase_ , decoder_attention_mask=lowercase_)
__snake_case = 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 __lowercase ( unittest.TestCase ):
__UpperCAmelCase = 99
def _a ( self) -> str:
__snake_case = np.array(
[
[7_1, 8_2, 1_8, 3_3, 4_6, 9_1, 2],
[6_8, 3_4, 2_6, 5_8, 3_0, 8_2, 2],
[5, 9_7, 1_7, 3_9, 9_4, 4_0, 2],
[7_6, 8_3, 9_4, 2_5, 7_0, 7_8, 2],
[8_7, 5_9, 4_1, 3_5, 4_8, 6_6, 2],
[5_5, 1_3, 1_6, 5_8, 5, 2, 1], # note padding
[6_4, 2_7, 3_1, 5_1, 1_2, 7_5, 2],
[5_2, 6_4, 8_6, 1_7, 8_3, 3_9, 2],
[4_8, 6_1, 9, 2_4, 7_1, 8_2, 2],
[2_6, 1, 6_0, 4_8, 2_2, 1_3, 2],
[2_1, 5, 6_2, 2_8, 1_4, 7_6, 2],
[4_5, 9_8, 3_7, 8_6, 5_9, 4_8, 2],
[7_0, 7_0, 5_0, 9, 2_8, 0, 2],
] , dtype=np.intaa , )
__snake_case = input_ids.shape[0]
__snake_case = BlenderbotConfig(
vocab_size=self.vocab_size , d_model=2_4 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=3_2 , decoder_ffn_dim=3_2 , max_position_embeddings=4_8 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , )
return config, input_ids, batch_size
def _a ( self) -> Tuple:
__snake_case , __snake_case , __snake_case = self._get_config_and_data()
__snake_case = FlaxBlenderbotForConditionalGeneration(lowercase_)
__snake_case = lm_model(input_ids=lowercase_)
__snake_case = (batch_size, input_ids.shape[1], config.vocab_size)
self.assertEqual(outputs['logits'].shape , lowercase_)
def _a ( self) -> Tuple:
__snake_case = BlenderbotConfig(
vocab_size=self.vocab_size , d_model=1_4 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=4_8 , )
__snake_case = FlaxBlenderbotForConditionalGeneration(lowercase_)
__snake_case = np.array([[7_1, 8_2, 1_8, 3_3, 4_6, 9_1, 2], [6_8, 3_4, 2_6, 5_8, 3_0, 2, 1]] , dtype=np.intaa)
__snake_case = np.array([[8_2, 7_1, 8_2, 1_8, 2], [5_8, 6_8, 2, 1, 1]] , dtype=np.intaa)
__snake_case = lm_model(input_ids=lowercase_ , decoder_input_ids=lowercase_)
__snake_case = (*summary.shape, config.vocab_size)
self.assertEqual(outputs['logits'].shape , lowercase_)
def _a ( self) -> List[str]:
__snake_case = np.array([[7_1, 8_2, 1_8, 3_3, 2, 1, 1], [6_8, 3_4, 2_6, 5_8, 3_0, 8_2, 2]] , dtype=np.intaa)
__snake_case = shift_tokens_right(lowercase_ , 1 , 2)
__snake_case = np.equal(lowercase_ , 1).astype(np.floataa).sum()
__snake_case = np.equal(lowercase_ , 1).astype(np.floataa).sum()
self.assertEqual(shifted.shape , input_ids.shape)
self.assertEqual(lowercase_ , n_pad_before - 1)
self.assertTrue(np.equal(shifted[:, 0] , 2).all())
@require_flax
class __lowercase ( lowerCamelCase__ , unittest.TestCase , lowerCamelCase__ ):
__UpperCAmelCase = True
__UpperCAmelCase = (
(
FlaxBlenderbotModel,
FlaxBlenderbotForConditionalGeneration,
)
if is_flax_available()
else ()
)
__UpperCAmelCase = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else ()
def _a ( self) -> Dict:
__snake_case = FlaxBlenderbotModelTester(self)
def _a ( self) -> Union[str, Any]:
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
self.model_tester.check_use_cache_forward(lowercase_ , lowercase_ , lowercase_)
def _a ( self) -> str:
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
self.model_tester.check_use_cache_forward_with_attn_mask(lowercase_ , lowercase_ , lowercase_)
def _a ( self) -> Dict:
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__):
__snake_case = self._prepare_for_class(lowercase_ , lowercase_)
__snake_case = model_class(lowercase_)
@jax.jit
def encode_jitted(lowercase_ , lowercase_=None , **lowercase_):
return model.encode(input_ids=lowercase_ , attention_mask=lowercase_)
with self.subTest('JIT Enabled'):
__snake_case = encode_jitted(**lowercase_).to_tuple()
with self.subTest('JIT Disabled'):
with jax.disable_jit():
__snake_case = encode_jitted(**lowercase_).to_tuple()
self.assertEqual(len(lowercase_) , len(lowercase_))
for jitted_output, output in zip(lowercase_ , lowercase_):
self.assertEqual(jitted_output.shape , output.shape)
def _a ( self) -> Union[str, Any]:
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__):
__snake_case = model_class(lowercase_)
__snake_case = model.encode(inputs_dict['input_ids'] , inputs_dict['attention_mask'])
__snake_case = {
'decoder_input_ids': inputs_dict['decoder_input_ids'],
'decoder_attention_mask': inputs_dict['decoder_attention_mask'],
'encoder_outputs': encoder_outputs,
}
@jax.jit
def decode_jitted(lowercase_ , lowercase_ , lowercase_):
return model.decode(
decoder_input_ids=lowercase_ , decoder_attention_mask=lowercase_ , encoder_outputs=lowercase_ , )
with self.subTest('JIT Enabled'):
__snake_case = decode_jitted(**lowercase_).to_tuple()
with self.subTest('JIT Disabled'):
with jax.disable_jit():
__snake_case = decode_jitted(**lowercase_).to_tuple()
self.assertEqual(len(lowercase_) , len(lowercase_))
for jitted_output, output in zip(lowercase_ , lowercase_):
self.assertEqual(jitted_output.shape , output.shape)
@slow
def _a ( self) -> str:
for model_class_name in self.all_model_classes:
__snake_case = model_class_name.from_pretrained('facebook/blenderbot-400M-distill')
# FlaxBlenderbotForSequenceClassification expects eos token in input_ids
__snake_case = np.ones((1, 1)) * model.config.eos_token_id
__snake_case = model(lowercase_)
self.assertIsNotNone(lowercase_)
@unittest.skipUnless(jax_device != 'cpu' , '3B test too slow on CPU.')
@slow
def _a ( self) -> int:
__snake_case = {'num_beams': 1, 'early_stopping': True, 'min_length': 1_5, 'max_length': 2_5}
__snake_case = {'skip_special_tokens': True, 'clean_up_tokenization_spaces': True}
__snake_case = FlaxBlenderbotForConditionalGeneration.from_pretrained('facebook/blenderbot-3B' , from_pt=lowercase_)
__snake_case = BlenderbotTokenizer.from_pretrained('facebook/blenderbot-3B')
__snake_case = ['Sam']
__snake_case = tokenizer(lowercase_ , return_tensors='jax')
__snake_case = model.generate(**lowercase_ , **lowercase_)
__snake_case = 'Sam is a great name. It means "sun" in Gaelic.'
__snake_case = tokenizer.batch_decode(lowercase_ , **lowercase_)
assert generated_txt[0].strip() == tgt_text
| 313 | 1 |
"""simple docstring"""
import itertools
import os
import random
import tempfile
import unittest
import numpy as np
from datasets import load_dataset
from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available
from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin
if is_speech_available():
from transformers import WhisperFeatureExtractor
if is_torch_available():
import torch
a : str = random.Random()
def snake_case__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) ->int:
if rng is None:
UpperCAmelCase__ = global_rng
UpperCAmelCase__ = []
for batch_idx in range(shape[0] ):
values.append([] )
for _ in range(shape[1] ):
values[-1].append(rng.random() * scale )
return values
@require_torch
@require_torchaudio
class _UpperCamelCase ( unittest.TestCase ):
'''simple docstring'''
def __init__( self , __lowercase , __lowercase=7 , __lowercase=400 , __lowercase=2000 , __lowercase=10 , __lowercase=160 , __lowercase=8 , __lowercase=0.0 , __lowercase=4000 , __lowercase=False , __lowercase=True , ):
UpperCAmelCase__ = parent
UpperCAmelCase__ = batch_size
UpperCAmelCase__ = min_seq_length
UpperCAmelCase__ = max_seq_length
UpperCAmelCase__ = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
UpperCAmelCase__ = padding_value
UpperCAmelCase__ = sampling_rate
UpperCAmelCase__ = return_attention_mask
UpperCAmelCase__ = do_normalize
UpperCAmelCase__ = feature_size
UpperCAmelCase__ = chunk_length
UpperCAmelCase__ = hop_length
def A__ ( self ):
return {
"feature_size": self.feature_size,
"hop_length": self.hop_length,
"chunk_length": self.chunk_length,
"padding_value": self.padding_value,
"sampling_rate": self.sampling_rate,
"return_attention_mask": self.return_attention_mask,
"do_normalize": self.do_normalize,
}
def A__ ( self , __lowercase=False , __lowercase=False ):
def _flatten(__lowercase ):
return list(itertools.chain(*__lowercase ) )
if equal_length:
UpperCAmelCase__ = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )]
else:
# make sure that inputs increase in size
UpperCAmelCase__ = [
floats_list((x, self.feature_size) )
for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff )
]
if numpify:
UpperCAmelCase__ = [np.asarray(__lowercase ) for x in speech_inputs]
return speech_inputs
@require_torch
@require_torchaudio
class _UpperCamelCase ( __UpperCamelCase , unittest.TestCase ):
'''simple docstring'''
__lowercase : Optional[Any] = WhisperFeatureExtractor if is_speech_available() else None
def A__ ( self ):
UpperCAmelCase__ = WhisperFeatureExtractionTester(self )
def A__ ( self ):
UpperCAmelCase__ = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
UpperCAmelCase__ = feat_extract_first.save_pretrained(__lowercase )[0]
check_json_file_has_correct_format(__lowercase )
UpperCAmelCase__ = self.feature_extraction_class.from_pretrained(__lowercase )
UpperCAmelCase__ = feat_extract_first.to_dict()
UpperCAmelCase__ = feat_extract_second.to_dict()
UpperCAmelCase__ = feat_extract_first.mel_filters
UpperCAmelCase__ = feat_extract_second.mel_filters
self.assertTrue(np.allclose(__lowercase , __lowercase ) )
self.assertEqual(__lowercase , __lowercase )
def A__ ( self ):
UpperCAmelCase__ = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
UpperCAmelCase__ = os.path.join(__lowercase , """feat_extract.json""" )
feat_extract_first.to_json_file(__lowercase )
UpperCAmelCase__ = self.feature_extraction_class.from_json_file(__lowercase )
UpperCAmelCase__ = feat_extract_first.to_dict()
UpperCAmelCase__ = feat_extract_second.to_dict()
UpperCAmelCase__ = feat_extract_first.mel_filters
UpperCAmelCase__ = feat_extract_second.mel_filters
self.assertTrue(np.allclose(__lowercase , __lowercase ) )
self.assertEqual(__lowercase , __lowercase )
def A__ ( self ):
# Tests that all call wrap to encode_plus and batch_encode_plus
UpperCAmelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
# create three inputs of length 800, 1000, and 1200
UpperCAmelCase__ = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )]
UpperCAmelCase__ = [np.asarray(__lowercase ) for speech_input in speech_inputs]
# Test feature size
UpperCAmelCase__ = feature_extractor(__lowercase , padding="""max_length""" , return_tensors="""np""" ).input_features
self.assertTrue(input_features.ndim == 3 )
self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames )
self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size )
# Test not batched input
UpperCAmelCase__ = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features
UpperCAmelCase__ = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features
self.assertTrue(np.allclose(__lowercase , __lowercase , atol=1e-3 ) )
# Test batched
UpperCAmelCase__ = feature_extractor(__lowercase , return_tensors="""np""" ).input_features
UpperCAmelCase__ = feature_extractor(__lowercase , return_tensors="""np""" ).input_features
for enc_seq_a, enc_seq_a in zip(__lowercase , __lowercase ):
self.assertTrue(np.allclose(__lowercase , __lowercase , atol=1e-3 ) )
# Test 2-D numpy arrays are batched.
UpperCAmelCase__ = [floats_list((1, x) )[0] for x in (800, 800, 800)]
UpperCAmelCase__ = np.asarray(__lowercase )
UpperCAmelCase__ = feature_extractor(__lowercase , return_tensors="""np""" ).input_features
UpperCAmelCase__ = feature_extractor(__lowercase , return_tensors="""np""" ).input_features
for enc_seq_a, enc_seq_a in zip(__lowercase , __lowercase ):
self.assertTrue(np.allclose(__lowercase , __lowercase , atol=1e-3 ) )
# Test truncation required
UpperCAmelCase__ = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )]
UpperCAmelCase__ = [np.asarray(__lowercase ) for speech_input in speech_inputs]
UpperCAmelCase__ = [x[: feature_extractor.n_samples] for x in speech_inputs]
UpperCAmelCase__ = [np.asarray(__lowercase ) for speech_input in speech_inputs_truncated]
UpperCAmelCase__ = feature_extractor(__lowercase , return_tensors="""np""" ).input_features
UpperCAmelCase__ = feature_extractor(__lowercase , return_tensors="""np""" ).input_features
for enc_seq_a, enc_seq_a in zip(__lowercase , __lowercase ):
self.assertTrue(np.allclose(__lowercase , __lowercase , atol=1e-3 ) )
def A__ ( self ):
import torch
UpperCAmelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
UpperCAmelCase__ = np.random.rand(100 , 32 ).astype(np.floataa )
UpperCAmelCase__ = np_speech_inputs.tolist()
for inputs in [py_speech_inputs, np_speech_inputs]:
UpperCAmelCase__ = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" )
self.assertTrue(np_processed.input_features.dtype == np.floataa )
UpperCAmelCase__ = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" )
self.assertTrue(pt_processed.input_features.dtype == torch.floataa )
def A__ ( self , __lowercase ):
UpperCAmelCase__ = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" )
# automatic decoding with librispeech
UpperCAmelCase__ = ds.sort("""id""" ).select(range(__lowercase ) )[:num_samples]["""audio"""]
return [x["array"] for x in speech_samples]
def A__ ( self ):
# fmt: off
UpperCAmelCase__ = torch.tensor(
[
0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951,
0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678,
0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554,
-0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854
] )
# fmt: on
UpperCAmelCase__ = self._load_datasamples(1 )
UpperCAmelCase__ = WhisperFeatureExtractor()
UpperCAmelCase__ = feature_extractor(__lowercase , return_tensors="""pt""" ).input_features
self.assertEqual(input_features.shape , (1, 80, 3000) )
self.assertTrue(torch.allclose(input_features[0, 0, :30] , __lowercase , atol=1e-4 ) )
def A__ ( self ):
UpperCAmelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
UpperCAmelCase__ = self._load_datasamples(1 )[0]
UpperCAmelCase__ = ((audio - audio.min()) / (audio.max() - audio.min())) * 65535 # Rescale to [0, 65535] to show issue
UpperCAmelCase__ = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__lowercase )[0]
self.assertTrue(np.all(np.mean(__lowercase ) < 1e-3 ) )
self.assertTrue(np.all(np.abs(np.var(__lowercase ) - 1 ) < 1e-3 ) )
| 422 |
"""simple docstring"""
import json
import os
from collections import Counter
import torch
import torchvision
import torchvision.transforms as transforms
from PIL import Image
from torch import nn
from torch.utils.data import Dataset
a : Tuple = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)}
class _UpperCamelCase ( nn.Module ):
'''simple docstring'''
def __init__( self , __lowercase ):
super().__init__()
UpperCAmelCase__ = torchvision.models.resnetaaa(pretrained=__lowercase )
UpperCAmelCase__ = list(model.children() )[:-2]
UpperCAmelCase__ = nn.Sequential(*__lowercase )
UpperCAmelCase__ = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] )
def A__ ( self , __lowercase ):
# Bx3x224x224 -> Bx2048x7x7 -> Bx2048xN -> BxNx2048
UpperCAmelCase__ = self.pool(self.model(__lowercase ) )
UpperCAmelCase__ = torch.flatten(__lowercase , start_dim=2 )
UpperCAmelCase__ = out.transpose(1 , 2 ).contiguous()
return out # BxNx2048
class _UpperCamelCase ( __UpperCamelCase ):
'''simple docstring'''
def __init__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ):
UpperCAmelCase__ = [json.loads(__lowercase ) for l in open(__lowercase )]
UpperCAmelCase__ = os.path.dirname(__lowercase )
UpperCAmelCase__ = tokenizer
UpperCAmelCase__ = labels
UpperCAmelCase__ = len(__lowercase )
UpperCAmelCase__ = max_seq_length
UpperCAmelCase__ = transforms
def __len__( self ):
return len(self.data )
def __getitem__( self , __lowercase ):
UpperCAmelCase__ = torch.LongTensor(self.tokenizer.encode(self.data[index]["""text"""] , add_special_tokens=__lowercase ) )
UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = sentence[0], sentence[1:-1], sentence[-1]
UpperCAmelCase__ = sentence[: self.max_seq_length]
UpperCAmelCase__ = torch.zeros(self.n_classes )
UpperCAmelCase__ = 1
UpperCAmelCase__ = Image.open(os.path.join(self.data_dir , self.data[index]["""img"""] ) ).convert("""RGB""" )
UpperCAmelCase__ = self.transforms(__lowercase )
return {
"image_start_token": start_token,
"image_end_token": end_token,
"sentence": sentence,
"image": image,
"label": label,
}
def A__ ( self ):
UpperCAmelCase__ = Counter()
for row in self.data:
label_freqs.update(row["""label"""] )
return label_freqs
def snake_case__ ( _SCREAMING_SNAKE_CASE ) ->List[str]:
UpperCAmelCase__ = [len(row["""sentence"""] ) for row in batch]
UpperCAmelCase__ , UpperCAmelCase__ = len(_SCREAMING_SNAKE_CASE ), max(_SCREAMING_SNAKE_CASE )
UpperCAmelCase__ = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=torch.long )
UpperCAmelCase__ = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=torch.long )
for i_batch, (input_row, length) in enumerate(zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ):
UpperCAmelCase__ = input_row["""sentence"""]
UpperCAmelCase__ = 1
UpperCAmelCase__ = torch.stack([row["""image"""] for row in batch] )
UpperCAmelCase__ = torch.stack([row["""label"""] for row in batch] )
UpperCAmelCase__ = torch.stack([row["""image_start_token"""] for row in batch] )
UpperCAmelCase__ = torch.stack([row["""image_end_token"""] for row in batch] )
return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor
def snake_case__ ( ) ->int:
return [
"Crime",
"Drama",
"Thriller",
"Action",
"Comedy",
"Romance",
"Documentary",
"Short",
"Mystery",
"History",
"Family",
"Adventure",
"Fantasy",
"Sci-Fi",
"Western",
"Horror",
"Sport",
"War",
"Music",
"Musical",
"Animation",
"Biography",
"Film-Noir",
]
def snake_case__ ( ) ->str:
return transforms.Compose(
[
transforms.Resize(2_5_6 ),
transforms.CenterCrop(2_2_4 ),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.4677_7044, 0.4453_1429, 0.4066_1017] , std=[0.1222_1994, 0.1214_5835, 0.1438_0469] , ),
] )
| 422 | 1 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
UpperCamelCase_ : Optional[int] = logging.get_logger(__name__)
UpperCamelCase_ : str = {
'''kssteven/ibert-roberta-base''': '''https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json''',
'''kssteven/ibert-roberta-large''': '''https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json''',
'''kssteven/ibert-roberta-large-mnli''': (
'''https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json'''
),
}
class _a ( __lowerCAmelCase ):
SCREAMING_SNAKE_CASE_ : List[Any] = """ibert"""
def __init__( self ,_SCREAMING_SNAKE_CASE=30_522 ,_SCREAMING_SNAKE_CASE=768 ,_SCREAMING_SNAKE_CASE=12 ,_SCREAMING_SNAKE_CASE=12 ,_SCREAMING_SNAKE_CASE=3_072 ,_SCREAMING_SNAKE_CASE="gelu" ,_SCREAMING_SNAKE_CASE=0.1 ,_SCREAMING_SNAKE_CASE=0.1 ,_SCREAMING_SNAKE_CASE=512 ,_SCREAMING_SNAKE_CASE=2 ,_SCREAMING_SNAKE_CASE=0.0_2 ,_SCREAMING_SNAKE_CASE=1e-12 ,_SCREAMING_SNAKE_CASE=1 ,_SCREAMING_SNAKE_CASE=0 ,_SCREAMING_SNAKE_CASE=2 ,_SCREAMING_SNAKE_CASE="absolute" ,_SCREAMING_SNAKE_CASE=False ,_SCREAMING_SNAKE_CASE="none" ,**_SCREAMING_SNAKE_CASE ,) -> Dict:
super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE ,bos_token_id=_SCREAMING_SNAKE_CASE ,eos_token_id=_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE )
_snake_case = vocab_size
_snake_case = hidden_size
_snake_case = num_hidden_layers
_snake_case = num_attention_heads
_snake_case = hidden_act
_snake_case = intermediate_size
_snake_case = hidden_dropout_prob
_snake_case = attention_probs_dropout_prob
_snake_case = max_position_embeddings
_snake_case = type_vocab_size
_snake_case = initializer_range
_snake_case = layer_norm_eps
_snake_case = position_embedding_type
_snake_case = quant_mode
_snake_case = force_dequant
class _a ( __lowerCAmelCase ):
@property
def _lowercase ( self ) -> Mapping[str, Mapping[int, str]]:
if self.task == "multiple-choice":
_snake_case = {0: "batch", 1: "choice", 2: "sequence"}
else:
_snake_case = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
] )
| 185 |
'''simple docstring'''
from typing import List, Optional, Union
import torch
from transformers import (
XLMRobertaTokenizer,
)
from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import (
is_accelerate_available,
is_accelerate_version,
logging,
randn_tensor,
replace_example_docstring,
)
from .text_encoder import MultilingualCLIP
UpperCamelCase_ : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name
UpperCamelCase_ : Dict = '''
Examples:
```py
>>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline
>>> import torch
>>> pipe_prior = KandinskyPriorPipeline.from_pretrained("kandinsky-community/Kandinsky-2-1-prior")
>>> pipe_prior.to("cuda")
>>> prompt = "red cat, 4k photo"
>>> out = pipe_prior(prompt)
>>> image_emb = out.image_embeds
>>> negative_image_emb = out.negative_image_embeds
>>> pipe = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1")
>>> pipe.to("cuda")
>>> image = pipe(
... prompt,
... image_embeds=image_emb,
... negative_image_embeds=negative_image_emb,
... height=768,
... width=768,
... num_inference_steps=100,
... ).images
>>> image[0].save("cat.png")
```
'''
def __a ( _UpperCamelCase: Any , _UpperCamelCase: List[Any] , _UpperCamelCase: Union[str, Any]=8 ) -> Optional[int]:
"""simple docstring"""
_snake_case = h // scale_factor**2
if h % scale_factor**2 != 0:
new_h += 1
_snake_case = w // scale_factor**2
if w % scale_factor**2 != 0:
new_w += 1
return new_h * scale_factor, new_w * scale_factor
class _a ( __lowerCAmelCase ):
def __init__( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,) -> str:
super().__init__()
self.register_modules(
text_encoder=_SCREAMING_SNAKE_CASE ,tokenizer=_SCREAMING_SNAKE_CASE ,unet=_SCREAMING_SNAKE_CASE ,scheduler=_SCREAMING_SNAKE_CASE ,movq=_SCREAMING_SNAKE_CASE ,)
_snake_case = 2 ** (len(self.movq.config.block_out_channels ) - 1)
def _lowercase ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Any:
if latents is None:
_snake_case = randn_tensor(_SCREAMING_SNAKE_CASE ,generator=_SCREAMING_SNAKE_CASE ,device=_SCREAMING_SNAKE_CASE ,dtype=_SCREAMING_SNAKE_CASE )
else:
if latents.shape != shape:
raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}""" )
_snake_case = latents.to(_SCREAMING_SNAKE_CASE )
_snake_case = latents * scheduler.init_noise_sigma
return latents
def _lowercase ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=None ,) -> Union[str, Any]:
_snake_case = len(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) else 1
# get prompt text embeddings
_snake_case = self.tokenizer(
_SCREAMING_SNAKE_CASE ,padding="max_length" ,truncation=_SCREAMING_SNAKE_CASE ,max_length=77 ,return_attention_mask=_SCREAMING_SNAKE_CASE ,add_special_tokens=_SCREAMING_SNAKE_CASE ,return_tensors="pt" ,)
_snake_case = text_inputs.input_ids
_snake_case = self.tokenizer(_SCREAMING_SNAKE_CASE ,padding="longest" ,return_tensors="pt" ).input_ids
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ):
_snake_case = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] )
logger.warning(
"The following part of your input was truncated because CLIP can only handle sequences up to"
f""" {self.tokenizer.model_max_length} tokens: {removed_text}""" )
_snake_case = text_input_ids.to(_SCREAMING_SNAKE_CASE )
_snake_case = text_inputs.attention_mask.to(_SCREAMING_SNAKE_CASE )
_snake_case , _snake_case = self.text_encoder(
input_ids=_SCREAMING_SNAKE_CASE ,attention_mask=_SCREAMING_SNAKE_CASE )
_snake_case = prompt_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE ,dim=0 )
_snake_case = text_encoder_hidden_states.repeat_interleave(_SCREAMING_SNAKE_CASE ,dim=0 )
_snake_case = text_mask.repeat_interleave(_SCREAMING_SNAKE_CASE ,dim=0 )
if do_classifier_free_guidance:
_snake_case = 42
if negative_prompt is None:
_snake_case = [""] * batch_size
elif type(_SCREAMING_SNAKE_CASE ) is not type(_SCREAMING_SNAKE_CASE ):
raise TypeError(
f"""`negative_prompt` should be the same type to `prompt`, but got {type(_SCREAMING_SNAKE_CASE )} !="""
f""" {type(_SCREAMING_SNAKE_CASE )}.""" )
elif isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ):
_snake_case = [negative_prompt]
elif batch_size != len(_SCREAMING_SNAKE_CASE ):
raise ValueError(
f"""`negative_prompt`: {negative_prompt} has batch size {len(_SCREAMING_SNAKE_CASE )}, but `prompt`:"""
f""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"""
" the batch size of `prompt`." )
else:
_snake_case = negative_prompt
_snake_case = self.tokenizer(
_SCREAMING_SNAKE_CASE ,padding="max_length" ,max_length=77 ,truncation=_SCREAMING_SNAKE_CASE ,return_attention_mask=_SCREAMING_SNAKE_CASE ,add_special_tokens=_SCREAMING_SNAKE_CASE ,return_tensors="pt" ,)
_snake_case = uncond_input.input_ids.to(_SCREAMING_SNAKE_CASE )
_snake_case = uncond_input.attention_mask.to(_SCREAMING_SNAKE_CASE )
_snake_case , _snake_case = self.text_encoder(
input_ids=_SCREAMING_SNAKE_CASE ,attention_mask=_SCREAMING_SNAKE_CASE )
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
_snake_case = negative_prompt_embeds.shape[1]
_snake_case = negative_prompt_embeds.repeat(1 ,_SCREAMING_SNAKE_CASE )
_snake_case = negative_prompt_embeds.view(batch_size * num_images_per_prompt ,_SCREAMING_SNAKE_CASE )
_snake_case = uncond_text_encoder_hidden_states.shape[1]
_snake_case = uncond_text_encoder_hidden_states.repeat(1 ,_SCREAMING_SNAKE_CASE ,1 )
_snake_case = uncond_text_encoder_hidden_states.view(
batch_size * num_images_per_prompt ,_SCREAMING_SNAKE_CASE ,-1 )
_snake_case = uncond_text_mask.repeat_interleave(_SCREAMING_SNAKE_CASE ,dim=0 )
# done duplicates
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
_snake_case = torch.cat([negative_prompt_embeds, prompt_embeds] )
_snake_case = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] )
_snake_case = torch.cat([uncond_text_mask, text_mask] )
return prompt_embeds, text_encoder_hidden_states, text_mask
def _lowercase ( self ,_SCREAMING_SNAKE_CASE=0 ) -> List[Any]:
if is_accelerate_available():
from accelerate import cpu_offload
else:
raise ImportError("Please install accelerate via `pip install accelerate`" )
_snake_case = torch.device(f"""cuda:{gpu_id}""" )
_snake_case = [
self.unet,
self.text_encoder,
self.movq,
]
for cpu_offloaded_model in models:
if cpu_offloaded_model is not None:
cpu_offload(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
def _lowercase ( self ,_SCREAMING_SNAKE_CASE=0 ) -> List[Any]:
if is_accelerate_available() and is_accelerate_version(">=" ,"0.17.0.dev0" ):
from accelerate import cpu_offload_with_hook
else:
raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher." )
_snake_case = torch.device(f"""cuda:{gpu_id}""" )
if self.device.type != "cpu":
self.to("cpu" ,silence_dtype_warnings=_SCREAMING_SNAKE_CASE )
torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
_snake_case = None
for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]:
_snake_case , _snake_case = cpu_offload_with_hook(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,prev_module_hook=_SCREAMING_SNAKE_CASE )
if self.safety_checker is not None:
_snake_case , _snake_case = cpu_offload_with_hook(self.safety_checker ,_SCREAMING_SNAKE_CASE ,prev_module_hook=_SCREAMING_SNAKE_CASE )
# We'll offload the last model manually.
_snake_case = hook
@property
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
def _lowercase ( self ) -> Optional[int]:
if not hasattr(self.unet ,"_hf_hook" ):
return self.device
for module in self.unet.modules():
if (
hasattr(_SCREAMING_SNAKE_CASE ,"_hf_hook" )
and hasattr(module._hf_hook ,"execution_device" )
and module._hf_hook.execution_device is not None
):
return torch.device(module._hf_hook.execution_device )
return self.device
@torch.no_grad()
@replace_example_docstring(_SCREAMING_SNAKE_CASE )
def __call__( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE = None ,_SCREAMING_SNAKE_CASE = 512 ,_SCREAMING_SNAKE_CASE = 512 ,_SCREAMING_SNAKE_CASE = 100 ,_SCREAMING_SNAKE_CASE = 4.0 ,_SCREAMING_SNAKE_CASE = 1 ,_SCREAMING_SNAKE_CASE = None ,_SCREAMING_SNAKE_CASE = None ,_SCREAMING_SNAKE_CASE = "pil" ,_SCREAMING_SNAKE_CASE = True ,) -> Union[str, Any]:
if isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ):
_snake_case = 1
elif isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ):
_snake_case = len(_SCREAMING_SNAKE_CASE )
else:
raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(_SCREAMING_SNAKE_CASE )}""" )
_snake_case = self._execution_device
_snake_case = batch_size * num_images_per_prompt
_snake_case = guidance_scale > 1.0
_snake_case , _snake_case , _snake_case = self._encode_prompt(
_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
if isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ):
_snake_case = torch.cat(_SCREAMING_SNAKE_CASE ,dim=0 )
if isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ):
_snake_case = torch.cat(_SCREAMING_SNAKE_CASE ,dim=0 )
if do_classifier_free_guidance:
_snake_case = image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE ,dim=0 )
_snake_case = negative_image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE ,dim=0 )
_snake_case = torch.cat([negative_image_embeds, image_embeds] ,dim=0 ).to(
dtype=prompt_embeds.dtype ,device=_SCREAMING_SNAKE_CASE )
self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE ,device=_SCREAMING_SNAKE_CASE )
_snake_case = self.scheduler.timesteps
_snake_case = self.unet.config.in_channels
_snake_case , _snake_case = get_new_h_w(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,self.movq_scale_factor )
# create initial latent
_snake_case = self.prepare_latents(
(batch_size, num_channels_latents, height, width) ,text_encoder_hidden_states.dtype ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,self.scheduler ,)
for i, t in enumerate(self.progress_bar(_SCREAMING_SNAKE_CASE ) ):
# expand the latents if we are doing classifier free guidance
_snake_case = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
_snake_case = {"text_embeds": prompt_embeds, "image_embeds": image_embeds}
_snake_case = self.unet(
sample=_SCREAMING_SNAKE_CASE ,timestep=_SCREAMING_SNAKE_CASE ,encoder_hidden_states=_SCREAMING_SNAKE_CASE ,added_cond_kwargs=_SCREAMING_SNAKE_CASE ,return_dict=_SCREAMING_SNAKE_CASE ,)[0]
if do_classifier_free_guidance:
_snake_case , _snake_case = noise_pred.split(latents.shape[1] ,dim=1 )
_snake_case , _snake_case = noise_pred.chunk(2 )
_snake_case , _snake_case = variance_pred.chunk(2 )
_snake_case = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
_snake_case = torch.cat([noise_pred, variance_pred_text] ,dim=1 )
if not (
hasattr(self.scheduler.config ,"variance_type" )
and self.scheduler.config.variance_type in ["learned", "learned_range"]
):
_snake_case , _snake_case = noise_pred.split(latents.shape[1] ,dim=1 )
# compute the previous noisy sample x_t -> x_t-1
_snake_case = self.scheduler.step(
_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,generator=_SCREAMING_SNAKE_CASE ,).prev_sample
# post-processing
_snake_case = self.movq.decode(_SCREAMING_SNAKE_CASE ,force_not_quantize=_SCREAMING_SNAKE_CASE )["sample"]
if output_type not in ["pt", "np", "pil"]:
raise ValueError(f"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""" )
if output_type in ["np", "pil"]:
_snake_case = image * 0.5 + 0.5
_snake_case = image.clamp(0 ,1 )
_snake_case = image.cpu().permute(0 ,2 ,3 ,1 ).float().numpy()
if output_type == "pil":
_snake_case = self.numpy_to_pil(_SCREAMING_SNAKE_CASE )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
| 185 | 1 |
'''simple docstring'''
from ..utils import DummyObject, requires_backends
class _snake_case ( metaclass=lowerCAmelCase_ ):
"""simple docstring"""
_UpperCamelCase : Optional[Any] = ['''flax''', '''transformers''']
def __init__( self : Any , *UpperCamelCase_ : Optional[int] , **UpperCamelCase_ : str ):
requires_backends(self , ['''flax''', '''transformers'''] )
@classmethod
def __A ( cls : str , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : int ):
requires_backends(cls , ['''flax''', '''transformers'''] )
@classmethod
def __A ( cls : Dict , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : int ):
requires_backends(cls , ['''flax''', '''transformers'''] )
class _snake_case ( metaclass=lowerCAmelCase_ ):
"""simple docstring"""
_UpperCamelCase : List[str] = ['''flax''', '''transformers''']
def __init__( self : Any , *UpperCamelCase_ : Tuple , **UpperCamelCase_ : Optional[int] ):
requires_backends(self , ['''flax''', '''transformers'''] )
@classmethod
def __A ( cls : Dict , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : Optional[int] ):
requires_backends(cls , ['''flax''', '''transformers'''] )
@classmethod
def __A ( cls : Any , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : Dict ):
requires_backends(cls , ['''flax''', '''transformers'''] )
class _snake_case ( metaclass=lowerCAmelCase_ ):
"""simple docstring"""
_UpperCamelCase : Optional[Any] = ['''flax''', '''transformers''']
def __init__( self : int , *UpperCamelCase_ : str , **UpperCamelCase_ : int ):
requires_backends(self , ['''flax''', '''transformers'''] )
@classmethod
def __A ( cls : Tuple , *UpperCamelCase_ : Any , **UpperCamelCase_ : Dict ):
requires_backends(cls , ['''flax''', '''transformers'''] )
@classmethod
def __A ( cls : Optional[Any] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : Optional[int] ):
requires_backends(cls , ['''flax''', '''transformers'''] )
class _snake_case ( metaclass=lowerCAmelCase_ ):
"""simple docstring"""
_UpperCamelCase : Optional[Any] = ['''flax''', '''transformers''']
def __init__( self : Optional[Any] , *UpperCamelCase_ : Optional[int] , **UpperCamelCase_ : List[Any] ):
requires_backends(self , ['''flax''', '''transformers'''] )
@classmethod
def __A ( cls : str , *UpperCamelCase_ : Optional[int] , **UpperCamelCase_ : str ):
requires_backends(cls , ['''flax''', '''transformers'''] )
@classmethod
def __A ( cls : Any , *UpperCamelCase_ : Dict , **UpperCamelCase_ : int ):
requires_backends(cls , ['''flax''', '''transformers'''] )
| 305 |
'''simple docstring'''
import operator as op
def SCREAMING_SNAKE_CASE__ ( _SCREAMING_SNAKE_CASE ):
lowerCAmelCase_ : Union[str, Any] =[]
lowerCAmelCase_ : Tuple =lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int(x / y ) # noqa: E731 integer division operation
lowerCAmelCase_ : Any ={
'''^''': op.pow,
'''*''': op.mul,
'''/''': div,
'''+''': op.add,
'''-''': op.sub,
} # operators & their respective operation
# print table header
print('''Symbol'''.center(8 ) , '''Action'''.center(12 ) , '''Stack''' , sep=''' | ''' )
print('''-''' * (30 + len(_SCREAMING_SNAKE_CASE )) )
for x in post_fix:
if x.isdigit(): # if x in digit
stack.append(_SCREAMING_SNAKE_CASE ) # append x to stack
# output in tabular format
print(x.rjust(8 ) , ('''push(''' + x + ''')''').ljust(12 ) , ''','''.join(_SCREAMING_SNAKE_CASE ) , sep=''' | ''' )
else:
lowerCAmelCase_ : Any =stack.pop() # pop stack
# output in tabular format
print(''''''.rjust(8 ) , ('''pop(''' + b + ''')''').ljust(12 ) , ''','''.join(_SCREAMING_SNAKE_CASE ) , sep=''' | ''' )
lowerCAmelCase_ : int =stack.pop() # pop stack
# output in tabular format
print(''''''.rjust(8 ) , ('''pop(''' + a + ''')''').ljust(12 ) , ''','''.join(_SCREAMING_SNAKE_CASE ) , sep=''' | ''' )
stack.append(
str(opr[x](int(_SCREAMING_SNAKE_CASE ) , int(_SCREAMING_SNAKE_CASE ) ) ) ) # evaluate the 2 values popped from stack & push result to stack
# output in tabular format
print(
x.rjust(8 ) , ('''push(''' + a + x + b + ''')''').ljust(12 ) , ''','''.join(_SCREAMING_SNAKE_CASE ) , sep=''' | ''' , )
return int(stack[0] )
if __name__ == "__main__":
__lowercase = input('''\n\nEnter a Postfix Equation (space separated) = ''').split(''' ''')
print('''\n\tResult = ''', solve(Postfix))
| 305 | 1 |
import re
import time
from typing import Optional
import IPython.display as disp
from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length
def __lowerCAmelCase ( A_ : int ) -> List[str]:
__UpperCAmelCase = int(A_ )
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = t // 36_00, (t // 60) % 60, t % 60
return F'''{h}:{m:02d}:{s:02d}''' if h != 0 else F'''{m:02d}:{s:02d}'''
def __lowerCAmelCase ( A_ : Any , A_ : List[Any] , A_ : Any , A_ : Dict , A_ : Tuple=3_00 ) -> List[str]:
# docstyle-ignore
return F'''
<div>
{prefix}
<progress value=\'{value}\' max=\'{total}\' style=\'width:{width}px; height:20px; vertical-align: middle;\'></progress>
{label}
</div>
'''
def __lowerCAmelCase ( A_ : int ) -> Tuple:
__UpperCAmelCase = "<table border=\"1\" class=\"dataframe\">\n"
html_code += """ <thead>\n <tr style="text-align: left;">\n"""
for i in items[0]:
html_code += F''' <th>{i}</th>\n'''
html_code += " </tr>\n </thead>\n <tbody>\n"
for line in items[1:]:
html_code += " <tr>\n"
for elt in line:
__UpperCAmelCase = F'''{elt:.6f}''' if isinstance(A_ , A_ ) else str(A_ )
html_code += F''' <td>{elt}</td>\n'''
html_code += " </tr>\n"
html_code += " </tbody>\n</table><p>"
return html_code
class UpperCAmelCase__ :
"""simple docstring"""
lowerCAmelCase__ : Optional[Any] = 5
lowerCAmelCase__ : Tuple = 0.2
def __init__( self: Any , __lowerCAmelCase: int , __lowerCAmelCase: Optional[str] = None , __lowerCAmelCase: bool = True , __lowerCAmelCase: Optional["NotebookTrainingTracker"] = None , __lowerCAmelCase: int = 300 , ) -> List[Any]:
'''simple docstring'''
__UpperCAmelCase = total
__UpperCAmelCase = "" if prefix is None else prefix
__UpperCAmelCase = leave
__UpperCAmelCase = parent
__UpperCAmelCase = width
__UpperCAmelCase = None
__UpperCAmelCase = None
__UpperCAmelCase = None
def _UpperCAmelCase ( self: Tuple , __lowerCAmelCase: int , __lowerCAmelCase: bool = False , __lowerCAmelCase: str = None ) -> List[str]:
'''simple docstring'''
__UpperCAmelCase = value
if comment is not None:
__UpperCAmelCase = comment
if self.last_value is None:
__UpperCAmelCase = __UpperCAmelCase = time.time()
__UpperCAmelCase = __UpperCAmelCase = value
__UpperCAmelCase = __UpperCAmelCase = None
__UpperCAmelCase = self.warmup
__UpperCAmelCase = 1
self.update_bar(__lowerCAmelCase )
elif value <= self.last_value and not force_update:
return
elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for , self.total ):
if self.first_calls > 0:
self.first_calls -= 1
__UpperCAmelCase = time.time()
__UpperCAmelCase = current_time - self.start_time
# We could have value = self.start_value if the update is called twixe with the same start value.
if value > self.start_value:
__UpperCAmelCase = self.elapsed_time / (value - self.start_value)
else:
__UpperCAmelCase = None
if value >= self.total:
__UpperCAmelCase = self.total
__UpperCAmelCase = None
if not self.leave:
self.close()
elif self.average_time_per_item is not None:
__UpperCAmelCase = self.average_time_per_item * (self.total - value)
self.update_bar(__lowerCAmelCase )
__UpperCAmelCase = value
__UpperCAmelCase = current_time
if self.average_time_per_item is None:
__UpperCAmelCase = 1
else:
__UpperCAmelCase = max(int(self.update_every / self.average_time_per_item ) , 1 )
def _UpperCAmelCase ( self: Union[str, Any] , __lowerCAmelCase: Any , __lowerCAmelCase: List[str]=None ) -> Optional[int]:
'''simple docstring'''
__UpperCAmelCase = " " * (len(str(self.total ) ) - len(str(__lowerCAmelCase ) )) + str(__lowerCAmelCase )
if self.elapsed_time is None:
__UpperCAmelCase = F'''[{spaced_value}/{self.total} : < :'''
elif self.predicted_remaining is None:
__UpperCAmelCase = F'''[{spaced_value}/{self.total} {format_time(self.elapsed_time )}'''
else:
__UpperCAmelCase = (
F'''[{spaced_value}/{self.total} {format_time(self.elapsed_time )} <'''
F''' {format_time(self.predicted_remaining )}'''
)
self.label += F''', {1/self.average_time_per_item:.2f} it/s'''
self.label += "]" if self.comment is None or len(self.comment ) == 0 else F''', {self.comment}]'''
self.display()
def _UpperCAmelCase ( self: Any ) -> str:
'''simple docstring'''
__UpperCAmelCase = html_progress_bar(self.value , self.total , self.prefix , self.label , self.width )
if self.parent is not None:
# If this is a child bar, the parent will take care of the display.
self.parent.display()
return
if self.output is None:
__UpperCAmelCase = disp.display(disp.HTML(self.html_code ) , display_id=__lowerCAmelCase )
else:
self.output.update(disp.HTML(self.html_code ) )
def _UpperCAmelCase ( self: Union[str, Any] ) -> Optional[Any]:
'''simple docstring'''
if self.parent is None and self.output is not None:
self.output.update(disp.HTML("" ) )
class UpperCAmelCase__ ( snake_case ):
"""simple docstring"""
def __init__( self: Optional[Any] , __lowerCAmelCase: Optional[int] , __lowerCAmelCase: List[Any]=None ) -> str:
'''simple docstring'''
super().__init__(__lowerCAmelCase )
__UpperCAmelCase = None if column_names is None else [column_names]
__UpperCAmelCase = None
def _UpperCAmelCase ( self: Any ) -> List[Any]:
'''simple docstring'''
__UpperCAmelCase = html_progress_bar(self.value , self.total , self.prefix , self.label , self.width )
if self.inner_table is not None:
self.html_code += text_to_html_table(self.inner_table )
if self.child_bar is not None:
self.html_code += self.child_bar.html_code
if self.output is None:
__UpperCAmelCase = disp.display(disp.HTML(self.html_code ) , display_id=__lowerCAmelCase )
else:
self.output.update(disp.HTML(self.html_code ) )
def _UpperCAmelCase ( self: List[str] , __lowerCAmelCase: Union[str, Any] ) -> List[str]:
'''simple docstring'''
if self.inner_table is None:
__UpperCAmelCase = [list(values.keys() ), list(values.values() )]
else:
__UpperCAmelCase = self.inner_table[0]
if len(self.inner_table ) == 1:
# We give a chance to update the column names at the first iteration
for key in values.keys():
if key not in columns:
columns.append(__lowerCAmelCase )
__UpperCAmelCase = columns
self.inner_table.append([values[c] for c in columns] )
def _UpperCAmelCase ( self: str , __lowerCAmelCase: Union[str, Any] , __lowerCAmelCase: Tuple=None , __lowerCAmelCase: Optional[int]=300 ) -> List[str]:
'''simple docstring'''
__UpperCAmelCase = NotebookProgressBar(__lowerCAmelCase , prefix=__lowerCAmelCase , parent=self , width=__lowerCAmelCase )
return self.child_bar
def _UpperCAmelCase ( self: List[Any] ) -> Dict:
'''simple docstring'''
__UpperCAmelCase = None
self.display()
class UpperCAmelCase__ ( snake_case ):
"""simple docstring"""
def __init__( self: List[Any] ) -> List[str]:
'''simple docstring'''
__UpperCAmelCase = None
__UpperCAmelCase = None
__UpperCAmelCase = False
def _UpperCAmelCase ( self: int , __lowerCAmelCase: Any , __lowerCAmelCase: List[Any] , __lowerCAmelCase: Optional[int] , **__lowerCAmelCase: int ) -> Dict:
'''simple docstring'''
__UpperCAmelCase = "Epoch" if args.evaluation_strategy == IntervalStrategy.EPOCH else "Step"
__UpperCAmelCase = 0
__UpperCAmelCase = 0
__UpperCAmelCase = [self.first_column] + ["Training Loss"]
if args.evaluation_strategy != IntervalStrategy.NO:
column_names.append("Validation Loss" )
__UpperCAmelCase = NotebookTrainingTracker(state.max_steps , __lowerCAmelCase )
def _UpperCAmelCase ( self: int , __lowerCAmelCase: int , __lowerCAmelCase: Optional[Any] , __lowerCAmelCase: List[str] , **__lowerCAmelCase: Optional[Any] ) -> Optional[int]:
'''simple docstring'''
__UpperCAmelCase = int(state.epoch ) if int(state.epoch ) == state.epoch else F'''{state.epoch:.2f}'''
self.training_tracker.update(
state.global_step + 1 , comment=F'''Epoch {epoch}/{state.num_train_epochs}''' , force_update=self._force_next_update , )
__UpperCAmelCase = False
def _UpperCAmelCase ( self: int , __lowerCAmelCase: List[Any] , __lowerCAmelCase: Any , __lowerCAmelCase: Tuple , __lowerCAmelCase: List[Any]=None , **__lowerCAmelCase: Dict ) -> Dict:
'''simple docstring'''
if not has_length(__lowerCAmelCase ):
return
if self.prediction_bar is None:
if self.training_tracker is not None:
__UpperCAmelCase = self.training_tracker.add_child(len(__lowerCAmelCase ) )
else:
__UpperCAmelCase = NotebookProgressBar(len(__lowerCAmelCase ) )
self.prediction_bar.update(1 )
else:
self.prediction_bar.update(self.prediction_bar.value + 1 )
def _UpperCAmelCase ( self: Optional[Any] , __lowerCAmelCase: List[str] , __lowerCAmelCase: str , __lowerCAmelCase: str , **__lowerCAmelCase: List[Any] ) -> Optional[int]:
'''simple docstring'''
if self.prediction_bar is not None:
self.prediction_bar.close()
__UpperCAmelCase = None
def _UpperCAmelCase ( self: List[str] , __lowerCAmelCase: Tuple , __lowerCAmelCase: str , __lowerCAmelCase: str , __lowerCAmelCase: Tuple=None , **__lowerCAmelCase: List[str] ) -> Optional[Any]:
'''simple docstring'''
if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
__UpperCAmelCase = {"Training Loss": logs["loss"]}
# First column is necessarily Step sine we're not in epoch eval strategy
__UpperCAmelCase = state.global_step
self.training_tracker.write_line(__lowerCAmelCase )
def _UpperCAmelCase ( self: int , __lowerCAmelCase: Dict , __lowerCAmelCase: List[Any] , __lowerCAmelCase: Dict , __lowerCAmelCase: int=None , **__lowerCAmelCase: int ) -> Tuple:
'''simple docstring'''
if self.training_tracker is not None:
__UpperCAmelCase = {"Training Loss": "No log", "Validation Loss": "No log"}
for log in reversed(state.log_history ):
if "loss" in log:
__UpperCAmelCase = log["loss"]
break
if self.first_column == "Epoch":
__UpperCAmelCase = int(state.epoch )
else:
__UpperCAmelCase = state.global_step
__UpperCAmelCase = "eval"
for k in metrics:
if k.endswith("_loss" ):
__UpperCAmelCase = re.sub(r"\_loss$" , "" , __lowerCAmelCase )
__UpperCAmelCase = metrics.pop("total_flos" , __lowerCAmelCase )
__UpperCAmelCase = metrics.pop("epoch" , __lowerCAmelCase )
__UpperCAmelCase = metrics.pop(F'''{metric_key_prefix}_runtime''' , __lowerCAmelCase )
__UpperCAmelCase = metrics.pop(F'''{metric_key_prefix}_samples_per_second''' , __lowerCAmelCase )
__UpperCAmelCase = metrics.pop(F'''{metric_key_prefix}_steps_per_second''' , __lowerCAmelCase )
__UpperCAmelCase = metrics.pop(F'''{metric_key_prefix}_jit_compilation_time''' , __lowerCAmelCase )
for k, v in metrics.items():
if k == F'''{metric_key_prefix}_loss''':
__UpperCAmelCase = v
else:
__UpperCAmelCase = k.split("_" )
__UpperCAmelCase = " ".join([part.capitalize() for part in splits[1:]] )
__UpperCAmelCase = v
self.training_tracker.write_line(__lowerCAmelCase )
self.training_tracker.remove_child()
__UpperCAmelCase = None
# Evaluation takes a long time so we should force the next update.
__UpperCAmelCase = True
def _UpperCAmelCase ( self: List[str] , __lowerCAmelCase: str , __lowerCAmelCase: Optional[int] , __lowerCAmelCase: Optional[int] , **__lowerCAmelCase: List[str] ) -> Optional[int]:
'''simple docstring'''
self.training_tracker.update(
state.global_step , comment=F'''Epoch {int(state.epoch )}/{state.num_train_epochs}''' , force_update=__lowerCAmelCase )
__UpperCAmelCase = None
| 221 | from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_torch_available,
is_vision_available,
)
a_ = {"""configuration_beit""": ["""BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BeitConfig""", """BeitOnnxConfig"""]}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ = ["""BeitFeatureExtractor"""]
a_ = ["""BeitImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ = [
"""BEIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""BeitForImageClassification""",
"""BeitForMaskedImageModeling""",
"""BeitForSemanticSegmentation""",
"""BeitModel""",
"""BeitPreTrainedModel""",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ = [
"""FlaxBeitForImageClassification""",
"""FlaxBeitForMaskedImageModeling""",
"""FlaxBeitModel""",
"""FlaxBeitPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_beit import BeitFeatureExtractor
from .image_processing_beit import BeitImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_beit import (
BEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
BeitForImageClassification,
BeitForMaskedImageModeling,
BeitForSemanticSegmentation,
BeitModel,
BeitPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_beit import (
FlaxBeitForImageClassification,
FlaxBeitForMaskedImageModeling,
FlaxBeitModel,
FlaxBeitPreTrainedModel,
)
else:
import sys
a_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 221 | 1 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ....utils import _LazyModule
_snake_case = {"tokenization_tapex": ["TapexTokenizer"]}
if TYPE_CHECKING:
from .tokenization_tapex import TapexTokenizer
else:
import sys
_snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure)
| 659 |
"""simple docstring"""
import json
import multiprocessing
import os
import re
from collections import defaultdict
import torch
from accelerate import Accelerator
from accelerate.utils import set_seed
from arguments import HumanEvalArguments
from datasets import load_dataset, load_metric
from torch.utils.data import IterableDataset
from torch.utils.data.dataloader import DataLoader
from tqdm import tqdm
import transformers
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList
_snake_case = ["\nclass", "\ndef", "\n#", "\n@", "\nprint", "\nif"]
class _a ( SCREAMING_SNAKE_CASE_ ):
def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Optional[int]=1 ):
lowerCamelCase__ = tokenizer
lowerCamelCase__ = dataset
lowerCamelCase__ = len(SCREAMING_SNAKE_CASE__ ) if n_tasks is None else n_tasks
lowerCamelCase__ = n_copies
def __iter__( self : Any ):
lowerCamelCase__ = []
for task in range(self.n_tasks ):
# without strip, the model generate commented codes ...
prompts.append(self.tokenizer.eos_token + self.dataset[task]['prompt'].strip() )
lowerCamelCase__ = self.tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )
for task in range(self.n_tasks ):
for _ in range(self.n_copies ):
yield {
"ids": outputs.input_ids[task],
"task_id": task,
"input_len": outputs.attention_mask[task].sum(),
}
class _a ( SCREAMING_SNAKE_CASE_ ):
def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Dict ):
lowerCamelCase__ = start_length
lowerCamelCase__ = eof_strings
lowerCamelCase__ = tokenizer
def __call__( self : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , **SCREAMING_SNAKE_CASE__ : Dict ):
lowerCamelCase__ = self.tokenizer.batch_decode(input_ids[:, self.start_length :] )
lowerCamelCase__ = []
for decoded_generation in decoded_generations:
done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) )
return all(SCREAMING_SNAKE_CASE__ )
def snake_case ( _a: List[Any] )-> Dict:
'''simple docstring'''
lowerCamelCase__ = re.split('(%s)' % '|'.join(_a ) , _a )
# last string should be ""
return "".join(string_list[:-2] )
def snake_case ( _a: List[Any] , _a: Optional[int] , _a: str , _a: Union[str, Any] , _a: Dict , _a: Optional[int]=20 , **_a: Optional[int] )-> List[str]:
'''simple docstring'''
lowerCamelCase__ = defaultdict(_a ) # dict of list of generated tokens
for step, batch in tqdm(enumerate(_a ) ):
with torch.no_grad():
lowerCamelCase__ = batch['ids'].shape[-1]
lowerCamelCase__ = accelerator.unwrap_model(_a ).generate(
input_ids=batch['ids'][:, : batch['input_len']] , num_return_sequences=_a , **_a )
# each task is generated batch_size times
lowerCamelCase__ = batch['task_id'].repeat(_a )
lowerCamelCase__ = accelerator.pad_across_processes(
_a , dim=1 , pad_index=tokenizer.pad_token_id )
lowerCamelCase__ , lowerCamelCase__ = accelerator.gather((generated_tokens, generated_tasks) )
lowerCamelCase__ = generated_tokens.cpu().numpy()
lowerCamelCase__ = generated_tasks.cpu().numpy()
for task, generated_tokens in zip(_a , _a ):
gen_token_dict[task].append(_a )
lowerCamelCase__ = [[] for _ in range(_a )]
for task, generated_tokens in gen_token_dict.items():
for s in generated_tokens:
lowerCamelCase__ = tokenizer.decode(_a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a )
code_gens[task].append(remove_last_block(_a ) )
return code_gens
def snake_case ( )-> Union[str, Any]:
'''simple docstring'''
lowerCamelCase__ = HfArgumentParser(_a )
lowerCamelCase__ = parser.parse_args()
transformers.logging.set_verbosity_error()
# enables code execution in code_eval metric
lowerCamelCase__ = args.HF_ALLOW_CODE_EVAL
# make sure tokenizer plays nice with multiprocessing
lowerCamelCase__ = 'false'
if args.num_workers is None:
lowerCamelCase__ = multiprocessing.cpu_count()
# Use dataset load to feed to accelerate
lowerCamelCase__ = Accelerator()
set_seed(args.seed , device_specific=_a )
# Load model and tokenizer
lowerCamelCase__ = AutoTokenizer.from_pretrained(args.model_ckpt )
lowerCamelCase__ = tokenizer.eos_token
lowerCamelCase__ = AutoModelForCausalLM.from_pretrained(args.model_ckpt )
# Generation settings
lowerCamelCase__ = {
'do_sample': args.do_sample,
'temperature': args.temperature,
'max_new_tokens': args.max_new_tokens,
'top_p': args.top_p,
'top_k': args.top_k,
'stopping_criteria': StoppingCriteriaList([EndOfFunctionCriteria(0 , _a , _a )] ),
}
# Load evaluation dataset and metric
lowerCamelCase__ = load_dataset('openai_humaneval' )
lowerCamelCase__ = load_metric('code_eval' )
lowerCamelCase__ = args.num_tasks if args.num_tasks is not None else len(human_eval['test'] )
lowerCamelCase__ = args.n_samples // args.batch_size
lowerCamelCase__ = TokenizedDataset(_a , human_eval['test'] , n_copies=_a , n_tasks=_a )
# do not confuse args.batch_size, which is actually the num_return_sequences
lowerCamelCase__ = DataLoader(_a , batch_size=1 )
# Run a quick test to see if code evaluation is enabled
try:
lowerCamelCase__ = code_eval_metric.compute(references=[''] , predictions=[['']] )
except ValueError as exception:
print(
'Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`'
' flag to enable code evaluation.' )
raise exception
lowerCamelCase__ , lowerCamelCase__ = accelerator.prepare(_a , _a )
lowerCamelCase__ = complete_code(
_a , _a , _a , _a , n_tasks=_a , batch_size=args.batch_size , **_a , )
if accelerator.is_main_process:
lowerCamelCase__ = []
for task in tqdm(range(_a ) ):
lowerCamelCase__ = human_eval['test'][task]['test']
lowerCamelCase__ = F'check({human_eval["test"][task]["entry_point"]})'
references.append('\n' + test_func + '\n' + entry_point )
# Evaluate completions with "code_eval" metric
lowerCamelCase__ , lowerCamelCase__ = code_eval_metric.compute(
references=_a , predictions=_a , num_workers=args.num_workers )
print(F'Results: {pass_at_k}' )
# Save results to json file
with open(args.output_file , 'w' ) as fp:
json.dump(_a , _a )
# For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing
# https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script
if __name__ == "__main__":
main()
| 659 | 1 |
'''simple docstring'''
from collections.abc import Callable
from math import pi, sqrt
from random import uniform
from statistics import mean
def lowerCamelCase__ ( A : int ):
'''simple docstring'''
def is_in_circle(A : float , A : float ) -> bool:
UpperCAmelCase = sqrt((x**2) + (y**2) )
# Our circle has a radius of 1, so a distance
# greater than 1 would land outside the circle.
return distance_from_centre <= 1
# The proportion of guesses that landed in the circle
UpperCAmelCase = mean(
int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) )
for _ in range(A ) )
# The ratio of the area for circle to square is pi/4.
UpperCAmelCase = proportion * 4
print(f"""The estimated value of pi is {pi_estimate}""" )
print(f"""The numpy value of pi is {pi}""" )
print(f"""The total error is {abs(pi - pi_estimate )}""" )
def lowerCamelCase__ ( A : int , A : Callable[[float], float] , A : float = 0.0 , A : float = 1.0 , ):
'''simple docstring'''
return mean(
function_to_integrate(uniform(A , A ) ) for _ in range(A ) ) * (max_value - min_value)
def lowerCamelCase__ ( A : int , A : float = 0.0 , A : float = 1.0 ):
'''simple docstring'''
def identity_function(A : float ) -> float:
return x
UpperCAmelCase = area_under_curve_estimator(
A , A , A , A )
UpperCAmelCase = (max_value * max_value - min_value * min_value) / 2
print('''******************''' )
print(f"""Estimating area under y=x where x varies from {min_value} to {max_value}""" )
print(f"""Estimated value is {estimated_value}""" )
print(f"""Expected value is {expected_value}""" )
print(f"""Total error is {abs(estimated_value - expected_value )}""" )
print('''******************''' )
def lowerCamelCase__ ( A : int ):
'''simple docstring'''
def function_to_integrate(A : float ) -> float:
return sqrt(4.0 - x * x )
UpperCAmelCase = area_under_curve_estimator(
A , A , 0.0 , 2.0 )
print('''******************''' )
print('''Estimating pi using area_under_curve_estimator''' )
print(f"""Estimated value is {estimated_value}""" )
print(f"""Expected value is {pi}""" )
print(f"""Total error is {abs(estimated_value - pi )}""" )
print('''******************''' )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 210 |
'''simple docstring'''
import importlib
import os
import sys
# This is required to make the module import works (when the python process is running from the root of the repo)
sys.path.append(""".""")
def lowerCamelCase__ ( A : str ):
'''simple docstring'''
UpperCAmelCase = test_file.split(os.path.sep )
if components[0:2] != ["tests", "models"]:
raise ValueError(
'''`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got '''
f"""{test_file} instead.""" )
UpperCAmelCase = components[-1]
if not test_fn.endswith('''py''' ):
raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" )
if not test_fn.startswith('''test_modeling_''' ):
raise ValueError(
f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" )
UpperCAmelCase = components[:-1] + [test_fn.replace('''.py''' , '''''' )]
UpperCAmelCase = '''.'''.join(A )
return test_module_path
def lowerCamelCase__ ( A : Any ):
'''simple docstring'''
UpperCAmelCase = get_module_path(A )
UpperCAmelCase = importlib.import_module(A )
return test_module
def lowerCamelCase__ ( A : Tuple ):
'''simple docstring'''
UpperCAmelCase = []
UpperCAmelCase = get_test_module(A )
for attr in dir(A ):
if attr.endswith('''ModelTester''' ):
tester_classes.append(getattr(A , A ) )
# sort with class names
return sorted(A , key=lambda A : x.__name__ )
def lowerCamelCase__ ( A : Any ):
'''simple docstring'''
UpperCAmelCase = []
UpperCAmelCase = get_test_module(A )
for attr in dir(A ):
UpperCAmelCase = getattr(A , A )
# (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking
# `all_model_classes` is not empty (which also excludes other special classes).
UpperCAmelCase = getattr(A , '''all_model_classes''' , [] )
if len(A ) > 0:
test_classes.append(A )
# sort with class names
return sorted(A , key=lambda A : x.__name__ )
def lowerCamelCase__ ( A : int ):
'''simple docstring'''
UpperCAmelCase = get_test_classes(A )
UpperCAmelCase = set()
for test_class in test_classes:
model_classes.update(test_class.all_model_classes )
# sort with class names
return sorted(A , key=lambda A : x.__name__ )
def lowerCamelCase__ ( A : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase = test_class()
if hasattr(A , '''setUp''' ):
test.setUp()
UpperCAmelCase = None
if hasattr(A , '''model_tester''' ):
# `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case.
if test.model_tester is not None:
UpperCAmelCase = test.model_tester.__class__
return model_tester
def lowerCamelCase__ ( A : Tuple , A : int ):
'''simple docstring'''
UpperCAmelCase = get_test_classes(A )
UpperCAmelCase = []
for test_class in test_classes:
if model_class in test_class.all_model_classes:
target_test_classes.append(A )
# sort with class names
return sorted(A , key=lambda A : x.__name__ )
def lowerCamelCase__ ( A : Any , A : Tuple ):
'''simple docstring'''
UpperCAmelCase = get_test_classes_for_model(A , A )
UpperCAmelCase = []
for test_class in test_classes:
UpperCAmelCase = get_model_tester_from_test_class(A )
if tester_class is not None:
tester_classes.append(A )
# sort with class names
return sorted(A , key=lambda A : x.__name__ )
def lowerCamelCase__ ( A : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase = get_test_classes(A )
UpperCAmelCase = {test_class: get_model_tester_from_test_class(A ) for test_class in test_classes}
return test_tester_mapping
def lowerCamelCase__ ( A : Any ):
'''simple docstring'''
UpperCAmelCase = get_model_classes(A )
UpperCAmelCase = {
model_class: get_test_classes_for_model(A , A ) for model_class in model_classes
}
return model_test_mapping
def lowerCamelCase__ ( A : int ):
'''simple docstring'''
UpperCAmelCase = get_model_classes(A )
UpperCAmelCase = {
model_class: get_tester_classes_for_model(A , A ) for model_class in model_classes
}
return model_to_tester_mapping
def lowerCamelCase__ ( A : Dict ):
'''simple docstring'''
if isinstance(A , A ):
return o
elif isinstance(A , A ):
return o.__name__
elif isinstance(A , (list, tuple) ):
return [to_json(A ) for x in o]
elif isinstance(A , A ):
return {to_json(A ): to_json(A ) for k, v in o.items()}
else:
return o
| 210 | 1 |
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__snake_case = {
'''configuration_informer''': [
'''INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''InformerConfig''',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = [
'''INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''InformerForPrediction''',
'''InformerModel''',
'''InformerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_informer import (
INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
InformerForPrediction,
InformerModel,
InformerPreTrainedModel,
)
else:
import sys
__snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 704 |
import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss
from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.bert.modeling_bert import (
BERT_INPUTS_DOCSTRING,
BERT_START_DOCSTRING,
BertEmbeddings,
BertLayer,
BertPooler,
BertPreTrainedModel,
)
def _lowercase ( UpperCamelCase_ ) -> List[str]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ = torch.exp(UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ = torch.sum(UpperCamelCase_ , dim=1 ) # sum of exp(x_i)
SCREAMING_SNAKE_CASE__ = torch.sum(x * exp_x , dim=1 ) # sum of x_i * exp(x_i)
return torch.log(UpperCamelCase_ ) - B / A
class lowercase__ ( nn.Module ):
def __init__( self : Optional[int] , UpperCAmelCase_ : Any ):
super().__init__()
SCREAMING_SNAKE_CASE__ = config.output_attentions
SCREAMING_SNAKE_CASE__ = config.output_hidden_states
SCREAMING_SNAKE_CASE__ = nn.ModuleList([BertLayer(UpperCAmelCase_ ) for _ in range(config.num_hidden_layers )] )
SCREAMING_SNAKE_CASE__ = nn.ModuleList([BertHighway(UpperCAmelCase_ ) for _ in range(config.num_hidden_layers )] )
SCREAMING_SNAKE_CASE__ = [-1 for _ in range(config.num_hidden_layers )]
def A_ ( self : Tuple , UpperCAmelCase_ : Optional[int] ):
if (type(UpperCAmelCase_ ) is float) or (type(UpperCAmelCase_ ) is int):
for i in range(len(self.early_exit_entropy ) ):
SCREAMING_SNAKE_CASE__ = x
else:
SCREAMING_SNAKE_CASE__ = x
def A_ ( self : Optional[Any] , UpperCAmelCase_ : Optional[int] ):
SCREAMING_SNAKE_CASE__ = pooler.state_dict()
for highway in self.highway:
for name, param in highway.pooler.state_dict().items():
param.copy_(loaded_model[name] )
def A_ ( self : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Tuple=None , ):
SCREAMING_SNAKE_CASE__ = ()
SCREAMING_SNAKE_CASE__ = ()
SCREAMING_SNAKE_CASE__ = ()
for i, layer_module in enumerate(self.layer ):
if self.output_hidden_states:
SCREAMING_SNAKE_CASE__ = all_hidden_states + (hidden_states,)
SCREAMING_SNAKE_CASE__ = layer_module(
UpperCAmelCase_ , UpperCAmelCase_ , head_mask[i] , UpperCAmelCase_ , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = layer_outputs[0]
if self.output_attentions:
SCREAMING_SNAKE_CASE__ = all_attentions + (layer_outputs[1],)
SCREAMING_SNAKE_CASE__ = (hidden_states,)
if self.output_hidden_states:
SCREAMING_SNAKE_CASE__ = current_outputs + (all_hidden_states,)
if self.output_attentions:
SCREAMING_SNAKE_CASE__ = current_outputs + (all_attentions,)
SCREAMING_SNAKE_CASE__ = self.highway[i](UpperCAmelCase_ )
# logits, pooled_output
if not self.training:
SCREAMING_SNAKE_CASE__ = highway_exit[0]
SCREAMING_SNAKE_CASE__ = entropy(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy
SCREAMING_SNAKE_CASE__ = all_highway_exits + (highway_exit,)
if highway_entropy < self.early_exit_entropy[i]:
SCREAMING_SNAKE_CASE__ = (highway_logits,) + current_outputs[1:] + (all_highway_exits,)
raise HighwayException(UpperCAmelCase_ , i + 1 )
else:
SCREAMING_SNAKE_CASE__ = all_highway_exits + (highway_exit,)
# Add last layer
if self.output_hidden_states:
SCREAMING_SNAKE_CASE__ = all_hidden_states + (hidden_states,)
SCREAMING_SNAKE_CASE__ = (hidden_states,)
if self.output_hidden_states:
SCREAMING_SNAKE_CASE__ = outputs + (all_hidden_states,)
if self.output_attentions:
SCREAMING_SNAKE_CASE__ = outputs + (all_attentions,)
SCREAMING_SNAKE_CASE__ = outputs + (all_highway_exits,)
return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits
@add_start_docstrings(
"""The Bert Model transformer with early exiting (DeeBERT). """ , _UpperCAmelCase , )
class lowercase__ ( _UpperCAmelCase ):
def __init__( self : List[Any] , UpperCAmelCase_ : str ):
super().__init__(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = config
SCREAMING_SNAKE_CASE__ = BertEmbeddings(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = DeeBertEncoder(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = BertPooler(UpperCAmelCase_ )
self.init_weights()
def A_ ( self : Optional[int] ):
self.encoder.init_highway_pooler(self.pooler )
def A_ ( self : Optional[Any] ):
return self.embeddings.word_embeddings
def A_ ( self : List[str] , UpperCAmelCase_ : Any ):
SCREAMING_SNAKE_CASE__ = value
def A_ ( self : Any , UpperCAmelCase_ : List[str] ):
for layer, heads in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(UpperCAmelCase_ )
@add_start_docstrings_to_model_forward(UpperCAmelCase_ )
def A_ ( self : Optional[int] , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Tuple=None , ):
if input_ids is not None and inputs_embeds is not None:
raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time' )
elif input_ids is not None:
SCREAMING_SNAKE_CASE__ = input_ids.size()
elif inputs_embeds is not None:
SCREAMING_SNAKE_CASE__ = inputs_embeds.size()[:-1]
else:
raise ValueError('You have to specify either input_ids or inputs_embeds' )
SCREAMING_SNAKE_CASE__ = input_ids.device if input_ids is not None else inputs_embeds.device
if attention_mask is None:
SCREAMING_SNAKE_CASE__ = torch.ones(UpperCAmelCase_ , device=UpperCAmelCase_ )
if encoder_attention_mask is None:
SCREAMING_SNAKE_CASE__ = torch.ones(UpperCAmelCase_ , device=UpperCAmelCase_ )
if token_type_ids is None:
SCREAMING_SNAKE_CASE__ = torch.zeros(UpperCAmelCase_ , dtype=torch.long , device=UpperCAmelCase_ )
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
# ourselves in which case we just need to make it broadcastable to all heads.
SCREAMING_SNAKE_CASE__ = self.get_extended_attention_mask(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
# If a 2D ou 3D attention mask is provided for the cross-attention
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
if encoder_attention_mask.dim() == 3:
SCREAMING_SNAKE_CASE__ = encoder_attention_mask[:, None, :, :]
if encoder_attention_mask.dim() == 2:
SCREAMING_SNAKE_CASE__ = encoder_attention_mask[:, None, None, :]
SCREAMING_SNAKE_CASE__ = encoder_extended_attention_mask.to(
dtype=next(self.parameters() ).dtype ) # fp16 compatibility
SCREAMING_SNAKE_CASE__ = (1.0 - encoder_extended_attention_mask) * -10_000.0
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
SCREAMING_SNAKE_CASE__ = self.get_head_mask(UpperCAmelCase_ , self.config.num_hidden_layers )
SCREAMING_SNAKE_CASE__ = self.embeddings(
input_ids=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , inputs_embeds=UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = self.encoder(
UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , head_mask=UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ , encoder_attention_mask=UpperCAmelCase_ , )
SCREAMING_SNAKE_CASE__ = encoder_outputs[0]
SCREAMING_SNAKE_CASE__ = self.pooler(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = (
sequence_output,
pooled_output,
) + encoder_outputs[
1:
] # add hidden_states and attentions if they are here
return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits
class lowercase__ ( _UpperCAmelCase ):
def __init__( self : Tuple , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[int] ):
SCREAMING_SNAKE_CASE__ = message
SCREAMING_SNAKE_CASE__ = exit_layer # start from 1!
class lowercase__ ( nn.Module ):
def __init__( self : int , UpperCAmelCase_ : Union[str, Any] ):
super().__init__()
SCREAMING_SNAKE_CASE__ = BertPooler(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = nn.Dropout(config.hidden_dropout_prob )
SCREAMING_SNAKE_CASE__ = nn.Linear(config.hidden_size , config.num_labels )
def A_ ( self : Dict , UpperCAmelCase_ : Dict ):
# Pooler
SCREAMING_SNAKE_CASE__ = encoder_outputs[0]
SCREAMING_SNAKE_CASE__ = self.pooler(UpperCAmelCase_ )
# "return" pooler_output
# BertModel
SCREAMING_SNAKE_CASE__ = (pooler_input, pooler_output) + encoder_outputs[1:]
# "return" bmodel_output
# Dropout and classification
SCREAMING_SNAKE_CASE__ = bmodel_output[1]
SCREAMING_SNAKE_CASE__ = self.dropout(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = self.classifier(UpperCAmelCase_ )
return logits, pooled_output
@add_start_docstrings(
"""Bert Model (with early exiting - DeeBERT) with a classifier on top,
also takes care of multi-layer training. """ , _UpperCAmelCase , )
class lowercase__ ( _UpperCAmelCase ):
def __init__( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] ):
super().__init__(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = config.num_labels
SCREAMING_SNAKE_CASE__ = config.num_hidden_layers
SCREAMING_SNAKE_CASE__ = DeeBertModel(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = nn.Dropout(config.hidden_dropout_prob )
SCREAMING_SNAKE_CASE__ = nn.Linear(config.hidden_size , self.config.num_labels )
self.init_weights()
@add_start_docstrings_to_model_forward(UpperCAmelCase_ )
def A_ ( self : List[Any] , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : int=-1 , UpperCAmelCase_ : Optional[int]=False , ):
SCREAMING_SNAKE_CASE__ = self.num_layers
try:
SCREAMING_SNAKE_CASE__ = self.bert(
UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , head_mask=UpperCAmelCase_ , inputs_embeds=UpperCAmelCase_ , )
# sequence_output, pooled_output, (hidden_states), (attentions), highway exits
SCREAMING_SNAKE_CASE__ = outputs[1]
SCREAMING_SNAKE_CASE__ = self.dropout(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = self.classifier(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = (logits,) + outputs[2:] # add hidden states and attention if they are here
except HighwayException as e:
SCREAMING_SNAKE_CASE__ = e.message
SCREAMING_SNAKE_CASE__ = e.exit_layer
SCREAMING_SNAKE_CASE__ = outputs[0]
if not self.training:
SCREAMING_SNAKE_CASE__ = entropy(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = []
SCREAMING_SNAKE_CASE__ = []
if labels is not None:
if self.num_labels == 1:
# We are doing regression
SCREAMING_SNAKE_CASE__ = MSELoss()
SCREAMING_SNAKE_CASE__ = loss_fct(logits.view(-1 ) , labels.view(-1 ) )
else:
SCREAMING_SNAKE_CASE__ = CrossEntropyLoss()
SCREAMING_SNAKE_CASE__ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
# work with highway exits
SCREAMING_SNAKE_CASE__ = []
for highway_exit in outputs[-1]:
SCREAMING_SNAKE_CASE__ = highway_exit[0]
if not self.training:
highway_logits_all.append(UpperCAmelCase_ )
highway_entropy.append(highway_exit[2] )
if self.num_labels == 1:
# We are doing regression
SCREAMING_SNAKE_CASE__ = MSELoss()
SCREAMING_SNAKE_CASE__ = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) )
else:
SCREAMING_SNAKE_CASE__ = CrossEntropyLoss()
SCREAMING_SNAKE_CASE__ = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
highway_losses.append(UpperCAmelCase_ )
if train_highway:
SCREAMING_SNAKE_CASE__ = (sum(highway_losses[:-1] ),) + outputs
# exclude the final highway, of course
else:
SCREAMING_SNAKE_CASE__ = (loss,) + outputs
if not self.training:
SCREAMING_SNAKE_CASE__ = outputs + ((original_entropy, highway_entropy), exit_layer)
if output_layer >= 0:
SCREAMING_SNAKE_CASE__ = (
(outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
) # use the highway of the last layer
return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
| 400 | 0 |
import inspect
import unittest
from huggingface_hub import hf_hub_download
from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_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 ASTForAudioClassification, ASTModel
from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_torchaudio_available():
import torchaudio
from transformers import ASTFeatureExtractor
class _lowerCamelCase:
def __init__( self, lowerCamelCase, lowerCamelCase=13, lowerCamelCase=2, lowerCamelCase=24, lowerCamelCase=16, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=32, lowerCamelCase=5, lowerCamelCase=4, lowerCamelCase=37, lowerCamelCase="gelu", lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=10, lowerCamelCase=0.0_2, lowerCamelCase=None, lowerCamelCase=2, lowerCamelCase=2, ) -> Union[str, Any]:
"""simple docstring"""
_lowercase : List[Any] = parent
_lowercase : List[Any] = batch_size
_lowercase : List[Any] = patch_size
_lowercase : Optional[int] = max_length
_lowercase : Any = num_mel_bins
_lowercase : List[Any] = is_training
_lowercase : Any = use_labels
_lowercase : int = hidden_size
_lowercase : Any = num_hidden_layers
_lowercase : Optional[Any] = num_attention_heads
_lowercase : Any = intermediate_size
_lowercase : Any = hidden_act
_lowercase : str = hidden_dropout_prob
_lowercase : Tuple = attention_probs_dropout_prob
_lowercase : Optional[int] = type_sequence_label_size
_lowercase : str = initializer_range
_lowercase : Dict = scope
_lowercase : Union[str, Any] = frequency_stride
_lowercase : Optional[int] = time_stride
# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
_lowercase : Optional[Any] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
_lowercase : Optional[int] = (self.max_length - self.patch_size) // self.time_stride + 1
_lowercase : Optional[Any] = frequency_out_dimension * time_out_dimension
_lowercase : List[Any] = num_patches + 2
def UpperCamelCase ( self) -> str:
"""simple docstring"""
_lowercase : Union[str, Any] = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins])
_lowercase : Optional[int] = None
if self.use_labels:
_lowercase : List[Any] = ids_tensor([self.batch_size], self.type_sequence_label_size)
_lowercase : Optional[Any] = self.get_config()
return config, input_values, labels
def UpperCamelCase ( self) -> Union[str, Any]:
"""simple docstring"""
return ASTConfig(
patch_size=self.patch_size, max_length=self.max_length, num_mel_bins=self.num_mel_bins, 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=__UpperCAmelCase, initializer_range=self.initializer_range, frequency_stride=self.frequency_stride, time_stride=self.time_stride, )
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> int:
"""simple docstring"""
_lowercase : Tuple = ASTModel(config=__UpperCAmelCase)
model.to(__UpperCAmelCase)
model.eval()
_lowercase : Optional[Any] = model(__UpperCAmelCase)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
def UpperCamelCase ( self) -> Optional[int]:
"""simple docstring"""
_lowercase : Union[str, Any] = self.prepare_config_and_inputs()
(
(
_lowercase
) , (
_lowercase
) , (
_lowercase
) ,
) : Any = config_and_inputs
_lowercase : Tuple = {'input_values': input_values}
return config, inputs_dict
@require_torch
class _lowerCamelCase( _UpperCAmelCase, _UpperCAmelCase, unittest.TestCase ):
lowercase_ : Dict = (
(
ASTModel,
ASTForAudioClassification,
)
if is_torch_available()
else ()
)
lowercase_ : Dict = (
{"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel}
if is_torch_available()
else {}
)
lowercase_ : str = False
lowercase_ : str = False
lowercase_ : Dict = False
lowercase_ : Optional[int] = False
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> List[str]:
"""simple docstring"""
if pipeline_test_casse_name == "AudioClassificationPipelineTests":
return True
return False
def UpperCamelCase ( self) -> List[str]:
"""simple docstring"""
_lowercase : Optional[Any] = ASTModelTester(self)
_lowercase : Tuple = ConfigTester(self, config_class=__UpperCAmelCase, has_text_modality=__UpperCAmelCase, hidden_size=37)
def UpperCamelCase ( self) -> Union[str, Any]:
"""simple docstring"""
self.config_tester.run_common_tests()
@unittest.skip(reason='AST does not use inputs_embeds')
def UpperCamelCase ( self) -> Tuple:
"""simple docstring"""
pass
def UpperCamelCase ( self) -> Any:
"""simple docstring"""
_lowercase , _lowercase : Any = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_lowercase : Tuple = model_class(__UpperCAmelCase)
self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
_lowercase : str = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__UpperCAmelCase, nn.Linear))
def UpperCamelCase ( self) -> List[Any]:
"""simple docstring"""
_lowercase , _lowercase : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_lowercase : int = model_class(__UpperCAmelCase)
_lowercase : str = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_lowercase : List[Any] = [*signature.parameters.keys()]
_lowercase : int = ['input_values']
self.assertListEqual(arg_names[:1], __UpperCAmelCase)
def UpperCamelCase ( self) -> Any:
"""simple docstring"""
_lowercase : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__UpperCAmelCase)
@slow
def UpperCamelCase ( self) -> Union[str, Any]:
"""simple docstring"""
for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_lowercase : Optional[Any] = ASTModel.from_pretrained(__UpperCAmelCase)
self.assertIsNotNone(__UpperCAmelCase)
def UpperCamelCase_( ) -> Dict:
_lowercase : Tuple = hf_hub_download(
repo_id='nielsr/audio-spectogram-transformer-checkpoint' , filename='sample_audio.flac' , repo_type='dataset' )
_lowercase , _lowercase : Optional[int] = torchaudio.load(UpperCamelCase_ )
return audio, sampling_rate
@require_torch
@require_torchaudio
class _lowerCamelCase( unittest.TestCase ):
@cached_property
def UpperCamelCase ( self) -> List[str]:
"""simple docstring"""
return (
ASTFeatureExtractor.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593')
if is_torchaudio_available()
else None
)
@slow
def UpperCamelCase ( self) -> Optional[int]:
"""simple docstring"""
_lowercase : Optional[Any] = self.default_feature_extractor
_lowercase : Optional[int] = ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593').to(__UpperCAmelCase)
_lowercase : Tuple = self.default_feature_extractor
_lowercase , _lowercase : Optional[Any] = prepare_audio()
_lowercase : Dict = audio.squeeze().numpy()
_lowercase : int = feature_extractor(__UpperCAmelCase, sampling_rate=__UpperCAmelCase, return_tensors='pt').to(__UpperCAmelCase)
# forward pass
with torch.no_grad():
_lowercase : Tuple = model(**__UpperCAmelCase)
# verify the logits
_lowercase : Dict = torch.Size((1, 5_27))
self.assertEqual(outputs.logits.shape, __UpperCAmelCase)
_lowercase : Dict = torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]).to(__UpperCAmelCase)
self.assertTrue(torch.allclose(outputs.logits[0, :3], __UpperCAmelCase, atol=1E-4))
| 89 |
from __future__ import annotations
from collections.abc import Callable
def _a ( UpperCamelCase_ : Callable[[int | float], int | float] , UpperCamelCase_ : int | float , UpperCamelCase_ : int | float , UpperCamelCase_ : int = 100 , ) -> float:
"""simple docstring"""
lowerCAmelCase__ = x_start
lowerCAmelCase__ = fnc(UpperCamelCase_ )
lowerCAmelCase__ = 0.0
for _ in range(UpperCamelCase_ ):
# Approximates small segments of curve as linear and solve
# for trapezoidal area
lowerCAmelCase__ = (x_end - x_start) / steps + xa
lowerCAmelCase__ = fnc(UpperCamelCase_ )
area += abs(fxa + fxa ) * (xa - xa) / 2
# Increment step
lowerCAmelCase__ = xa
lowerCAmelCase__ = fxa
return area
if __name__ == "__main__":
def _a ( UpperCamelCase_ : Union[str, Any] ) -> Dict:
"""simple docstring"""
return x**3 + x**2
print('''f(x) = x^3 + x^2''')
print('''The area between the curve, x = -5, x = 5 and the x axis is:''')
a_ = 10
while i <= 10_0000:
print(F"with {i} steps: {trapezoidal_area(f, -5, 5, i)}")
i *= 10
| 339 | 0 |
'''simple docstring'''
import requests
lowercase ='https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey='
def lowerCamelCase__ ( __lowerCamelCase : str ):
'''simple docstring'''
_UpperCAmelCase : List[str] =requests.get(_NEWS_API + bbc_news_api_key ).json()
# each article in the list is a dict
for i, article in enumerate(bbc_news_page['articles'] , 1 ):
print(f"{i}.) {article['title']}" )
if __name__ == "__main__":
fetch_bbc_news(bbc_news_api_key='<Your BBC News API key goes here>')
| 715 |
'''simple docstring'''
import unittest
from transformers.testing_utils import CaptureStdout
from transformers.tools.python_interpreter import evaluate
def lowerCamelCase__ ( __lowerCamelCase : Optional[Any] ):
'''simple docstring'''
return x + 2
class __magic_name__ ( unittest.TestCase ):
def lowerCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCAmelCase : Optional[int] ='x = 3'
_UpperCAmelCase : Optional[int] ={}
_UpperCAmelCase : List[Any] =evaluate(snake_case , {} , state=snake_case)
assert result == 3
self.assertDictEqual(snake_case , {'x': 3})
_UpperCAmelCase : Optional[int] ='x = y'
_UpperCAmelCase : str ={'y': 5}
_UpperCAmelCase : Optional[Any] =evaluate(snake_case , {} , state=snake_case)
# evaluate returns the value of the last assignment.
assert result == 5
self.assertDictEqual(snake_case , {'x': 5, 'y': 5})
def lowerCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCAmelCase : int ='y = add_two(x)'
_UpperCAmelCase : Optional[int] ={'x': 3}
_UpperCAmelCase : Optional[Any] =evaluate(snake_case , {'add_two': add_two} , state=snake_case)
assert result == 5
self.assertDictEqual(snake_case , {'x': 3, 'y': 5})
# Won't work without the tool
with CaptureStdout() as out:
_UpperCAmelCase : Union[str, Any] =evaluate(snake_case , {} , state=snake_case)
assert result is None
assert "tried to execute add_two" in out.out
def lowerCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCAmelCase : int ='x = 3'
_UpperCAmelCase : List[str] ={}
_UpperCAmelCase : str =evaluate(snake_case , {} , state=snake_case)
assert result == 3
self.assertDictEqual(snake_case , {'x': 3})
def lowerCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCAmelCase : Any ='test_dict = {\'x\': x, \'y\': add_two(x)}'
_UpperCAmelCase : List[str] ={'x': 3}
_UpperCAmelCase : Tuple =evaluate(snake_case , {'add_two': add_two} , state=snake_case)
self.assertDictEqual(snake_case , {'x': 3, 'y': 5})
self.assertDictEqual(snake_case , {'x': 3, 'test_dict': {'x': 3, 'y': 5}})
def lowerCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCAmelCase : Tuple ='x = 3\ny = 5'
_UpperCAmelCase : Any ={}
_UpperCAmelCase : Optional[int] =evaluate(snake_case , {} , state=snake_case)
# evaluate returns the value of the last assignment.
assert result == 5
self.assertDictEqual(snake_case , {'x': 3, 'y': 5})
def lowerCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCAmelCase : Tuple ='text = f\'This is x: {x}.\''
_UpperCAmelCase : Union[str, Any] ={'x': 3}
_UpperCAmelCase : Optional[Any] =evaluate(snake_case , {} , state=snake_case)
# evaluate returns the value of the last assignment.
assert result == "This is x: 3."
self.assertDictEqual(snake_case , {'x': 3, 'text': 'This is x: 3.'})
def lowerCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCAmelCase : Tuple ='if x <= 3:\n y = 2\nelse:\n y = 5'
_UpperCAmelCase : Any ={'x': 3}
_UpperCAmelCase : Dict =evaluate(snake_case , {} , state=snake_case)
# evaluate returns the value of the last assignment.
assert result == 2
self.assertDictEqual(snake_case , {'x': 3, 'y': 2})
_UpperCAmelCase : str ={'x': 8}
_UpperCAmelCase : int =evaluate(snake_case , {} , state=snake_case)
# evaluate returns the value of the last assignment.
assert result == 5
self.assertDictEqual(snake_case , {'x': 8, 'y': 5})
def lowerCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCAmelCase : Optional[Any] ='test_list = [x, add_two(x)]'
_UpperCAmelCase : int ={'x': 3}
_UpperCAmelCase : str =evaluate(snake_case , {'add_two': add_two} , state=snake_case)
self.assertListEqual(snake_case , [3, 5])
self.assertDictEqual(snake_case , {'x': 3, 'test_list': [3, 5]})
def lowerCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCAmelCase : List[Any] ='y = x'
_UpperCAmelCase : Any ={'x': 3}
_UpperCAmelCase : List[Any] =evaluate(snake_case , {} , state=snake_case)
assert result == 3
self.assertDictEqual(snake_case , {'x': 3, 'y': 3})
def lowerCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCAmelCase : List[Any] ='test_list = [x, add_two(x)]\ntest_list[1]'
_UpperCAmelCase : List[Any] ={'x': 3}
_UpperCAmelCase : int =evaluate(snake_case , {'add_two': add_two} , state=snake_case)
assert result == 5
self.assertDictEqual(snake_case , {'x': 3, 'test_list': [3, 5]})
_UpperCAmelCase : List[Any] ='test_dict = {\'x\': x, \'y\': add_two(x)}\ntest_dict[\'y\']'
_UpperCAmelCase : Union[str, Any] ={'x': 3}
_UpperCAmelCase : List[Any] =evaluate(snake_case , {'add_two': add_two} , state=snake_case)
assert result == 5
self.assertDictEqual(snake_case , {'x': 3, 'test_dict': {'x': 3, 'y': 5}})
def lowerCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCAmelCase : Tuple ='x = 0\nfor i in range(3):\n x = i'
_UpperCAmelCase : Optional[Any] ={}
_UpperCAmelCase : Dict =evaluate(snake_case , {'range': range} , state=snake_case)
assert result == 2
self.assertDictEqual(snake_case , {'x': 2, 'i': 2})
| 331 | 0 |
from collections import OrderedDict
from typing import List, 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/efficientnet-b7""": """https://huggingface.co/google/efficientnet-b7/resolve/main/config.json""",
}
class UpperCAmelCase ( A_ ):
A__ : str = "efficientnet"
def __init__(self : str , snake_case__ : int = 3 , snake_case__ : int = 6_00 , snake_case__ : float = 2.0 , snake_case__ : float = 3.1 , snake_case__ : int = 8 , snake_case__ : List[int] = [3, 3, 5, 3, 5, 5, 3] , snake_case__ : List[int] = [32, 16, 24, 40, 80, 1_12, 1_92] , snake_case__ : List[int] = [16, 24, 40, 80, 1_12, 1_92, 3_20] , snake_case__ : List[int] = [] , snake_case__ : List[int] = [1, 2, 2, 2, 1, 2, 1] , snake_case__ : List[int] = [1, 2, 2, 3, 3, 4, 1] , snake_case__ : List[int] = [1, 6, 6, 6, 6, 6, 6] , snake_case__ : float = 0.25 , snake_case__ : str = "swish" , snake_case__ : int = 25_60 , snake_case__ : str = "mean" , snake_case__ : float = 0.02 , snake_case__ : float = 0.001 , snake_case__ : float = 0.99 , snake_case__ : float = 0.5 , snake_case__ : float = 0.2 , **snake_case__ : Optional[Any] , ) -> Tuple:
'''simple docstring'''
super().__init__(**snake_case__ )
snake_case : Tuple = num_channels
snake_case : Optional[Any] = image_size
snake_case : str = width_coefficient
snake_case : Optional[Any] = depth_coefficient
snake_case : List[Any] = depth_divisor
snake_case : str = kernel_sizes
snake_case : int = in_channels
snake_case : Any = out_channels
snake_case : Optional[Any] = depthwise_padding
snake_case : Any = strides
snake_case : List[str] = num_block_repeats
snake_case : Optional[int] = expand_ratios
snake_case : Tuple = squeeze_expansion_ratio
snake_case : Optional[Any] = hidden_act
snake_case : str = hidden_dim
snake_case : Optional[int] = pooling_type
snake_case : List[str] = initializer_range
snake_case : List[Any] = batch_norm_eps
snake_case : str = batch_norm_momentum
snake_case : Dict = dropout_rate
snake_case : List[Any] = drop_connect_rate
snake_case : Optional[int] = sum(snake_case__ ) * 4
class UpperCAmelCase ( A_ ):
A__ : List[str] = version.parse("1.11" )
@property
def _SCREAMING_SNAKE_CASE (self : List[Any] ) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
return OrderedDict(
[
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
] )
@property
def _SCREAMING_SNAKE_CASE (self : Union[str, Any] ) -> float:
'''simple docstring'''
return 1e-5
| 204 |
from __future__ import annotations
from collections.abc import Callable
from typing import Any, Generic, TypeVar
__lowerCamelCase = TypeVar("""T""")
class UpperCAmelCase ( Generic[T] ):
def __init__(self : int , snake_case__ : list[T] , snake_case__ : Callable[[T, T], T] ) -> None:
'''simple docstring'''
snake_case : Any | T = None
snake_case : int = len(snake_case__ )
snake_case : list[T] = [any_type for _ in range(self.N )] + arr
snake_case : str = fnc
self.build()
def _SCREAMING_SNAKE_CASE (self : Union[str, Any] ) -> None:
'''simple docstring'''
for p in range(self.N - 1 , 0 , -1 ):
snake_case : int = self.fn(self.st[p * 2] , self.st[p * 2 + 1] )
def _SCREAMING_SNAKE_CASE (self : Dict , snake_case__ : int , snake_case__ : T ) -> None:
'''simple docstring'''
p += self.N
snake_case : int = v
while p > 1:
snake_case : List[str] = p // 2
snake_case : Tuple = self.fn(self.st[p * 2] , self.st[p * 2 + 1] )
def _SCREAMING_SNAKE_CASE (self : Optional[Any] , snake_case__ : int , snake_case__ : int ) -> T | None: # noqa: E741
'''simple docstring'''
snake_case , snake_case : Optional[int] = 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(snake_case__ , self.st[l] )
if r % 2 == 0:
snake_case : int = self.st[r] if res is None else self.fn(snake_case__ , self.st[r] )
snake_case , snake_case : str = (l + 1) // 2, (r - 1) // 2
return res
if __name__ == "__main__":
from functools import reduce
__lowerCamelCase = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12]
__lowerCamelCase = {
0: 7,
1: 2,
2: 6,
3: -14,
4: 5,
5: 4,
6: 7,
7: -10,
8: 9,
9: 10,
10: 12,
11: 1,
}
__lowerCamelCase = SegmentTree(test_array, min)
__lowerCamelCase = SegmentTree(test_array, max)
__lowerCamelCase = SegmentTree(test_array, lambda a, b: a + b)
def UpperCamelCase ( ):
for i in range(len(__lowerCamelCase ) ):
for j in range(__lowerCamelCase , len(__lowerCamelCase ) ):
snake_case : int = reduce(__lowerCamelCase , test_array[i : j + 1] )
snake_case : Tuple = reduce(__lowerCamelCase , test_array[i : j + 1] )
snake_case : Union[str, Any] = reduce(lambda __lowerCamelCase , __lowerCamelCase : a + b , test_array[i : j + 1] )
assert min_range == min_segment_tree.query(__lowerCamelCase , __lowerCamelCase )
assert max_range == max_segment_tree.query(__lowerCamelCase , __lowerCamelCase )
assert sum_range == sum_segment_tree.query(__lowerCamelCase , __lowerCamelCase )
test_all_segments()
for index, value in test_updates.items():
__lowerCamelCase = value
min_segment_tree.update(index, value)
max_segment_tree.update(index, value)
sum_segment_tree.update(index, value)
test_all_segments()
| 204 | 1 |
import argparse
import os
import torch
from transformers import (
XLNetConfig,
XLNetForQuestionAnswering,
XLNetForSequenceClassification,
XLNetLMHeadModel,
load_tf_weights_in_xlnet,
)
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
lowercase : Optional[int] = {
"cola": 2,
"mnli": 3,
"mrpc": 2,
"sst-2": 2,
"sts-b": 1,
"qqp": 2,
"qnli": 2,
"rte": 2,
"wnli": 2,
}
logging.set_verbosity_info()
def snake_case__ ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=None ):
# Initialise PyTorch model
A : List[str] = XLNetConfig.from_json_file(__UpperCamelCase )
A : List[Any] = finetuning_task.lower() if finetuning_task is not None else ''''''
if finetuning_task in GLUE_TASKS_NUM_LABELS:
print(F'Building PyTorch XLNetForSequenceClassification model from configuration: {config}' )
A : Dict = finetuning_task
A : Dict = GLUE_TASKS_NUM_LABELS[finetuning_task]
A : Tuple = XLNetForSequenceClassification(__UpperCamelCase )
elif "squad" in finetuning_task:
A : Dict = finetuning_task
A : int = XLNetForQuestionAnswering(__UpperCamelCase )
else:
A : int = XLNetLMHeadModel(__UpperCamelCase )
# Load weights from tf checkpoint
load_tf_weights_in_xlnet(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
# Save pytorch-model
A : List[Any] = os.path.join(__UpperCamelCase , __UpperCamelCase )
A : str = os.path.join(__UpperCamelCase , __UpperCamelCase )
print(F'Save PyTorch model to {os.path.abspath(__UpperCamelCase )}' )
torch.save(model.state_dict() , __UpperCamelCase )
print(F'Save configuration file to {os.path.abspath(__UpperCamelCase )}' )
with open(__UpperCamelCase , '''w''' , encoding='''utf-8''' ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
lowercase : Optional[int] = 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(
"--xlnet_config_file",
default=None,
type=str,
required=True,
help=(
"The config json file corresponding to the pre-trained XLNet model. \n"
"This specifies the model architecture."
),
)
parser.add_argument(
"--pytorch_dump_folder_path",
default=None,
type=str,
required=True,
help="Path to the folder to store the PyTorch model or dataset/vocab.",
)
parser.add_argument(
"--finetuning_task",
default=None,
type=str,
help="Name of a task on which the XLNet TensorFlow model was fine-tuned",
)
lowercase : Union[str, Any] = parser.parse_args()
print(args)
convert_xlnet_checkpoint_to_pytorch(
args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task
)
| 708 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
lowercase : int = {
"configuration_gpt_bigcode": ["GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTBigCodeConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase : Optional[Any] = [
"GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST",
"GPTBigCodeForSequenceClassification",
"GPTBigCodeForTokenClassification",
"GPTBigCodeForCausalLM",
"GPTBigCodeModel",
"GPTBigCodePreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_bigcode import (
GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTBigCodeForCausalLM,
GPTBigCodeForSequenceClassification,
GPTBigCodeForTokenClassification,
GPTBigCodeModel,
GPTBigCodePreTrainedModel,
)
else:
import sys
lowercase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 423 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.