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
|
---|---|---|---|---|
import logging
import os
import threading
import time
try:
import warnings
except ImportError:
lowerCAmelCase : str = None
try:
import msvcrt
except ImportError:
lowerCAmelCase : Optional[int] = None
try:
import fcntl
except ImportError:
lowerCAmelCase : List[str] = None
# Backward compatibility
# ------------------------------------------------
try:
TimeoutError
except NameError:
lowerCAmelCase : Union[str, Any] = OSError
# Data
# ------------------------------------------------
lowerCAmelCase : Union[str, Any] = [
"""Timeout""",
"""BaseFileLock""",
"""WindowsFileLock""",
"""UnixFileLock""",
"""SoftFileLock""",
"""FileLock""",
]
lowerCAmelCase : List[Any] = """3.0.12"""
lowerCAmelCase : Union[str, Any] = None
def A_ ( ):
global _logger
SCREAMING_SNAKE_CASE_: Any = _logger or logging.getLogger(__name__ )
return _logger
class __lowercase ( UpperCAmelCase_ ):
"""simple docstring"""
def __init__( self : Optional[Any] , lowerCAmelCase__ : List[str]):
SCREAMING_SNAKE_CASE_: int = lock_file
return None
def __str__( self : Union[str, Any]):
SCREAMING_SNAKE_CASE_: str = F"The file lock '{self.lock_file}' could not be acquired."
return temp
class __lowercase :
"""simple docstring"""
def __init__( self : Tuple , lowerCAmelCase__ : str):
SCREAMING_SNAKE_CASE_: Tuple = lock
return None
def __enter__( self : Dict):
return self.lock
def __exit__( self : List[Any] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : str , lowerCAmelCase__ : Tuple):
self.lock.release()
return None
class __lowercase :
"""simple docstring"""
def __init__( self : Optional[int] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[int]=-1 , lowerCAmelCase__ : Optional[Any]=None):
SCREAMING_SNAKE_CASE_: Optional[Any] = max_filename_length if max_filename_length is not None else 255
# Hash the filename if it's too long
SCREAMING_SNAKE_CASE_: List[Any] = self.hash_filename_if_too_long(lowerCAmelCase__ , lowerCAmelCase__)
# The path to the lock file.
SCREAMING_SNAKE_CASE_: List[Any] = lock_file
# The file descriptor for the *_lock_file* as it is returned by the
# os.open() function.
# This file lock is only NOT None, if the object currently holds the
# lock.
SCREAMING_SNAKE_CASE_: Union[str, Any] = None
# The default timeout value.
SCREAMING_SNAKE_CASE_: List[str] = timeout
# We use this lock primarily for the lock counter.
SCREAMING_SNAKE_CASE_: Optional[int] = threading.Lock()
# The lock counter is used for implementing the nested locking
# mechanism. Whenever the lock is acquired, the counter is increased and
# the lock is only released, when this value is 0 again.
SCREAMING_SNAKE_CASE_: int = 0
return None
@property
def _SCREAMING_SNAKE_CASE ( self : Optional[int]):
return self._lock_file
@property
def _SCREAMING_SNAKE_CASE ( self : Tuple):
return self._timeout
@timeout.setter
def _SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase__ : Tuple):
SCREAMING_SNAKE_CASE_: Tuple = float(lowerCAmelCase__)
return None
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]):
raise NotImplementedError()
def _SCREAMING_SNAKE_CASE ( self : int):
raise NotImplementedError()
@property
def _SCREAMING_SNAKE_CASE ( self : List[Any]):
return self._lock_file_fd is not None
def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase__ : str=None , lowerCAmelCase__ : int=0.05):
# Use the default timeout, if no timeout is provided.
if timeout is None:
SCREAMING_SNAKE_CASE_: Dict = self.timeout
# Increment the number right at the beginning.
# We can still undo it, if something fails.
with self._thread_lock:
self._lock_counter += 1
SCREAMING_SNAKE_CASE_: int = id(self)
SCREAMING_SNAKE_CASE_: List[str] = self._lock_file
SCREAMING_SNAKE_CASE_: str = time.time()
try:
while True:
with self._thread_lock:
if not self.is_locked:
logger().debug(F"Attempting to acquire lock {lock_id} on {lock_filename}")
self._acquire()
if self.is_locked:
logger().debug(F"Lock {lock_id} acquired on {lock_filename}")
break
elif timeout >= 0 and time.time() - start_time > timeout:
logger().debug(F"Timeout on acquiring lock {lock_id} on {lock_filename}")
raise Timeout(self._lock_file)
else:
logger().debug(
F"Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...")
time.sleep(lowerCAmelCase__)
except: # noqa
# Something did go wrong, so decrement the counter.
with self._thread_lock:
SCREAMING_SNAKE_CASE_: Optional[int] = max(0 , self._lock_counter - 1)
raise
return _Acquire_ReturnProxy(lock=self)
def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase__ : Optional[int]=False):
with self._thread_lock:
if self.is_locked:
self._lock_counter -= 1
if self._lock_counter == 0 or force:
SCREAMING_SNAKE_CASE_: Optional[int] = id(self)
SCREAMING_SNAKE_CASE_: Tuple = self._lock_file
logger().debug(F"Attempting to release lock {lock_id} on {lock_filename}")
self._release()
SCREAMING_SNAKE_CASE_: int = 0
logger().debug(F"Lock {lock_id} released on {lock_filename}")
return None
def __enter__( self : Tuple):
self.acquire()
return self
def __exit__( self : Tuple , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : Dict):
self.release()
return None
def __del__( self : List[Any]):
self.release(force=lowerCAmelCase__)
return None
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : str , lowerCAmelCase__ : int):
SCREAMING_SNAKE_CASE_: List[str] = os.path.basename(lowerCAmelCase__)
if len(lowerCAmelCase__) > max_length and max_length > 0:
SCREAMING_SNAKE_CASE_: Optional[int] = os.path.dirname(lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: int = str(hash(lowerCAmelCase__))
SCREAMING_SNAKE_CASE_: Tuple = filename[: max_length - len(lowerCAmelCase__) - 8] + "..." + hashed_filename + ".lock"
return os.path.join(lowerCAmelCase__ , lowerCAmelCase__)
else:
return path
class __lowercase ( UpperCAmelCase_ ):
"""simple docstring"""
def __init__( self : Optional[int] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Tuple=-1 , lowerCAmelCase__ : Dict=None):
from .file_utils import relative_to_absolute_path
super().__init__(lowerCAmelCase__ , timeout=lowerCAmelCase__ , max_filename_length=lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: int = "\\\\?\\" + relative_to_absolute_path(self.lock_file)
def _SCREAMING_SNAKE_CASE ( self : Tuple):
SCREAMING_SNAKE_CASE_: Union[str, Any] = os.O_RDWR | os.O_CREAT | os.O_TRUNC
try:
SCREAMING_SNAKE_CASE_: Tuple = os.open(self._lock_file , lowerCAmelCase__)
except OSError:
pass
else:
try:
msvcrt.locking(lowerCAmelCase__ , msvcrt.LK_NBLCK , 1)
except OSError:
os.close(lowerCAmelCase__)
else:
SCREAMING_SNAKE_CASE_: Any = fd
return None
def _SCREAMING_SNAKE_CASE ( self : Optional[int]):
SCREAMING_SNAKE_CASE_: int = self._lock_file_fd
SCREAMING_SNAKE_CASE_: Dict = None
msvcrt.locking(lowerCAmelCase__ , msvcrt.LK_UNLCK , 1)
os.close(lowerCAmelCase__)
try:
os.remove(self._lock_file)
# Probably another instance of the application
# that acquired the file lock.
except OSError:
pass
return None
class __lowercase ( UpperCAmelCase_ ):
"""simple docstring"""
def __init__( self : List[str] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict=-1 , lowerCAmelCase__ : int=None):
SCREAMING_SNAKE_CASE_: List[str] = os.statvfs(os.path.dirname(lowerCAmelCase__)).f_namemax
super().__init__(lowerCAmelCase__ , timeout=lowerCAmelCase__ , max_filename_length=lowerCAmelCase__)
def _SCREAMING_SNAKE_CASE ( self : Optional[Any]):
SCREAMING_SNAKE_CASE_: str = os.O_RDWR | os.O_CREAT | os.O_TRUNC
SCREAMING_SNAKE_CASE_: List[str] = os.open(self._lock_file , lowerCAmelCase__)
try:
fcntl.flock(lowerCAmelCase__ , fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
os.close(lowerCAmelCase__)
else:
SCREAMING_SNAKE_CASE_: Union[str, Any] = fd
return None
def _SCREAMING_SNAKE_CASE ( self : Optional[int]):
# Do not remove the lockfile:
#
# https://github.com/benediktschmitt/py-filelock/issues/31
# https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
SCREAMING_SNAKE_CASE_: int = self._lock_file_fd
SCREAMING_SNAKE_CASE_: str = None
fcntl.flock(lowerCAmelCase__ , fcntl.LOCK_UN)
os.close(lowerCAmelCase__)
return None
class __lowercase ( UpperCAmelCase_ ):
"""simple docstring"""
def _SCREAMING_SNAKE_CASE ( self : Dict):
SCREAMING_SNAKE_CASE_: Dict = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
try:
SCREAMING_SNAKE_CASE_: List[str] = os.open(self._lock_file , lowerCAmelCase__)
except OSError:
pass
else:
SCREAMING_SNAKE_CASE_: Optional[int] = fd
return None
def _SCREAMING_SNAKE_CASE ( self : Tuple):
os.close(self._lock_file_fd)
SCREAMING_SNAKE_CASE_: Optional[Any] = None
try:
os.remove(self._lock_file)
# The file is already deleted and that's what we want.
except OSError:
pass
return None
lowerCAmelCase : List[str] = None
if msvcrt:
lowerCAmelCase : Optional[Any] = WindowsFileLock
elif fcntl:
lowerCAmelCase : List[str] = UnixFileLock
else:
lowerCAmelCase : Dict = SoftFileLock
if warnings is not None:
warnings.warn("""only soft file lock is available""")
| 671 |
from itertools import count
def A_ ( _UpperCAmelCase = 50 ):
SCREAMING_SNAKE_CASE_: Union[str, Any] = [1] * min_block_length
for n in count(_UpperCAmelCase ):
fill_count_functions.append(1 )
for block_length in range(_UpperCAmelCase , 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] > 1_00_00_00:
break
return n
if __name__ == "__main__":
print(f'''{solution() = }''')
| 671 | 1 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
snake_case = logging.get_logger(__name__)
snake_case = {
"""xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/config.json""",
"""xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/config.json""",
"""xlm-roberta-large-finetuned-conll02-dutch""": (
"""https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json"""
),
"""xlm-roberta-large-finetuned-conll02-spanish""": (
"""https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json"""
),
"""xlm-roberta-large-finetuned-conll03-english""": (
"""https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json"""
),
"""xlm-roberta-large-finetuned-conll03-german""": (
"""https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json"""
),
}
class A_ ( UpperCAmelCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : List[str] = '''xlm-roberta'''
def __init__( self : Union[str, Any] ,__A : Dict=3_0522 ,__A : Union[str, Any]=768 ,__A : Dict=12 ,__A : Union[str, Any]=12 ,__A : List[str]=3072 ,__A : Dict="gelu" ,__A : List[Any]=0.1 ,__A : Optional[int]=0.1 ,__A : Any=512 ,__A : int=2 ,__A : str=0.02 ,__A : List[Any]=1e-12 ,__A : Optional[Any]=1 ,__A : List[Any]=0 ,__A : List[Any]=2 ,__A : Tuple="absolute" ,__A : str=True ,__A : Tuple=None ,**__A : int ,) -> List[str]:
super().__init__(pad_token_id=__A ,bos_token_id=__A ,eos_token_id=__A ,**__A )
_lowercase = vocab_size
_lowercase = hidden_size
_lowercase = num_hidden_layers
_lowercase = num_attention_heads
_lowercase = hidden_act
_lowercase = intermediate_size
_lowercase = hidden_dropout_prob
_lowercase = attention_probs_dropout_prob
_lowercase = max_position_embeddings
_lowercase = type_vocab_size
_lowercase = initializer_range
_lowercase = layer_norm_eps
_lowercase = position_embedding_type
_lowercase = use_cache
_lowercase = classifier_dropout
class A_ ( UpperCAmelCase ):
"""simple docstring"""
@property
def __UpperCAmelCase ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]:
if self.task == "multiple-choice":
_lowercase = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
_lowercase = {0: 'batch', 1: 'sequence'}
return OrderedDict(
[
('input_ids', dynamic_axis),
('attention_mask', dynamic_axis),
] )
| 535 |
from itertools import count
def SCREAMING_SNAKE_CASE__ ( snake_case__ :int = 50 ) -> int:
_lowercase = [1] * min_block_length
for n in count(snake_case__ ):
fill_count_functions.append(1 )
for block_length in range(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] > 100_0000:
break
return n
if __name__ == "__main__":
print(F"""{solution() = }""")
| 535 | 1 |
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging
if TYPE_CHECKING:
from ...processing_utils import ProcessorMixin
from ...utils import TensorType
lowerCAmelCase__ = logging.get_logger(__name__)
lowerCAmelCase__ = {
'''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''',
}
class snake_case__(_UpperCamelCase ):
"""simple docstring"""
lowercase_ = """layoutlmv3"""
def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE : List[str]=50_265 , SCREAMING_SNAKE_CASE : Dict=768 , SCREAMING_SNAKE_CASE : Any=12 , SCREAMING_SNAKE_CASE : List[str]=12 , SCREAMING_SNAKE_CASE : int=3_072 , SCREAMING_SNAKE_CASE : str="gelu" , SCREAMING_SNAKE_CASE : str=0.1 , SCREAMING_SNAKE_CASE : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE : Tuple=512 , SCREAMING_SNAKE_CASE : Optional[int]=2 , SCREAMING_SNAKE_CASE : Optional[int]=0.02 , SCREAMING_SNAKE_CASE : Dict=1E-5 , SCREAMING_SNAKE_CASE : Any=1 , SCREAMING_SNAKE_CASE : Dict=0 , SCREAMING_SNAKE_CASE : Union[str, Any]=2 , SCREAMING_SNAKE_CASE : Union[str, Any]=1_024 , SCREAMING_SNAKE_CASE : Dict=128 , SCREAMING_SNAKE_CASE : Optional[Any]=128 , SCREAMING_SNAKE_CASE : Tuple=True , SCREAMING_SNAKE_CASE : Optional[Any]=32 , SCREAMING_SNAKE_CASE : int=128 , SCREAMING_SNAKE_CASE : Any=64 , SCREAMING_SNAKE_CASE : Optional[int]=256 , SCREAMING_SNAKE_CASE : List[str]=True , SCREAMING_SNAKE_CASE : Tuple=True , SCREAMING_SNAKE_CASE : str=True , SCREAMING_SNAKE_CASE : Union[str, Any]=224 , SCREAMING_SNAKE_CASE : Any=3 , SCREAMING_SNAKE_CASE : Any=16 , SCREAMING_SNAKE_CASE : Union[str, Any]=None , **SCREAMING_SNAKE_CASE : Union[str, Any] , ):
super().__init__(
vocab_size=SCREAMING_SNAKE_CASE , hidden_size=SCREAMING_SNAKE_CASE , num_hidden_layers=SCREAMING_SNAKE_CASE , num_attention_heads=SCREAMING_SNAKE_CASE , intermediate_size=SCREAMING_SNAKE_CASE , hidden_act=SCREAMING_SNAKE_CASE , hidden_dropout_prob=SCREAMING_SNAKE_CASE , attention_probs_dropout_prob=SCREAMING_SNAKE_CASE , max_position_embeddings=SCREAMING_SNAKE_CASE , type_vocab_size=SCREAMING_SNAKE_CASE , initializer_range=SCREAMING_SNAKE_CASE , layer_norm_eps=SCREAMING_SNAKE_CASE , pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , )
lowercase__ : str = max_ad_position_embeddings
lowercase__ : str = coordinate_size
lowercase__ : int = shape_size
lowercase__ : str = has_relative_attention_bias
lowercase__ : Tuple = rel_pos_bins
lowercase__ : Any = max_rel_pos
lowercase__ : Optional[Any] = has_spatial_attention_bias
lowercase__ : Union[str, Any] = rel_ad_pos_bins
lowercase__ : List[str] = max_rel_ad_pos
lowercase__ : int = text_embed
lowercase__ : Optional[int] = visual_embed
lowercase__ : Optional[Any] = input_size
lowercase__ : Any = num_channels
lowercase__ : List[str] = patch_size
lowercase__ : Dict = classifier_dropout
class snake_case__(_UpperCamelCase ):
"""simple docstring"""
lowercase_ = version.parse("""1.12""" )
@property
def snake_case ( self : str ):
# The order of inputs is different for question answering and sequence classification
if self.task in ["question-answering", "sequence-classification"]:
return OrderedDict(
[
("input_ids", {0: "batch", 1: "sequence"}),
("attention_mask", {0: "batch", 1: "sequence"}),
("bbox", {0: "batch", 1: "sequence"}),
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
] )
else:
return OrderedDict(
[
("input_ids", {0: "batch", 1: "sequence"}),
("bbox", {0: "batch", 1: "sequence"}),
("attention_mask", {0: "batch", 1: "sequence"}),
("pixel_values", {0: "batch", 1: "num_channels"}),
] )
@property
def snake_case ( self : int ):
return 1E-5
@property
def snake_case ( self : Union[str, Any] ):
return 12
def snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE : "ProcessorMixin" , SCREAMING_SNAKE_CASE : int = -1 , SCREAMING_SNAKE_CASE : int = -1 , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE : int = 3 , SCREAMING_SNAKE_CASE : int = 40 , SCREAMING_SNAKE_CASE : int = 40 , ):
setattr(processor.image_processor , "apply_ocr" , SCREAMING_SNAKE_CASE )
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
lowercase__ : Union[str, Any] = compute_effective_axis_dimension(
SCREAMING_SNAKE_CASE , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 )
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
lowercase__ : str = processor.tokenizer.num_special_tokens_to_add(SCREAMING_SNAKE_CASE )
lowercase__ : Tuple = compute_effective_axis_dimension(
SCREAMING_SNAKE_CASE , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=SCREAMING_SNAKE_CASE )
# Generate dummy inputs according to compute batch and sequence
lowercase__ : Any = [[" ".join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size
# Generate dummy bounding boxes
lowercase__ : Optional[int] = [[[48, 84, 73, 128]]] * batch_size
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
# batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
lowercase__ : Dict = self._generate_dummy_images(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
lowercase__ : Tuple = dict(
processor(
SCREAMING_SNAKE_CASE , text=SCREAMING_SNAKE_CASE , boxes=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , ) )
return inputs
| 496 |
import argparse
import torch
from torch import nn
from transformers import MBartConfig, MBartForConditionalGeneration
def __lowerCamelCase ( lowerCamelCase__ ):
"""simple docstring"""
lowercase__ : Optional[int] = [
"encoder.version",
"decoder.version",
"model.encoder.version",
"model.decoder.version",
"_float_tensor",
"decoder.output_projection.weight",
]
for k in ignore_keys:
state_dict.pop(lowerCamelCase__ , lowerCamelCase__ )
def __lowerCamelCase ( lowerCamelCase__ ):
"""simple docstring"""
lowercase__ , lowercase__ : str = emb.weight.shape
lowercase__ : List[str] = nn.Linear(lowerCamelCase__ , lowerCamelCase__ , bias=lowerCamelCase__ )
lowercase__ : List[Any] = emb.weight.data
return lin_layer
def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__="facebook/mbart-large-en-ro" , lowerCamelCase__=False , lowerCamelCase__=False ):
"""simple docstring"""
lowercase__ : int = torch.load(lowerCamelCase__ , map_location="cpu" )["model"]
remove_ignore_keys_(lowerCamelCase__ )
lowercase__ : Tuple = state_dict["encoder.embed_tokens.weight"].shape[0]
lowercase__ : Optional[Any] = MBartConfig.from_pretrained(lowerCamelCase__ , vocab_size=lowerCamelCase__ )
if mbart_aa and finetuned:
lowercase__ : str = "relu"
lowercase__ : Optional[int] = state_dict["decoder.embed_tokens.weight"]
lowercase__ : Optional[Any] = MBartForConditionalGeneration(lowerCamelCase__ )
model.model.load_state_dict(lowerCamelCase__ )
if finetuned:
lowercase__ : Optional[Any] = make_linear_from_emb(model.model.shared )
return model
if __name__ == "__main__":
lowerCAmelCase__ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.'''
)
parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument(
'''--hf_config''',
default='''facebook/mbart-large-cc25''',
type=str,
help='''Which huggingface architecture to use: mbart-large''',
)
parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''')
parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''')
lowerCAmelCase__ = parser.parse_args()
lowerCAmelCase__ = convert_fairseq_mbart_checkpoint_from_disk(
args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa
)
model.save_pretrained(args.pytorch_dump_folder_path)
| 496 | 1 |
"""simple docstring"""
def __A ( a_ :int , a_ :int) -> str:
if a < 0 or b < 0:
raise ValueError('''the value of both inputs must be positive''')
__a : Any = str(bin(a_))[2:] # remove the leading "0b"
__a : Optional[Any] = str(bin(a_))[2:] # remove the leading "0b"
__a : int = max(len(a_) , len(a_))
return "0b" + "".join(
str(int(char_a == '''1''' and char_b == '''1'''))
for char_a, char_b in zip(a_binary.zfill(a_) , b_binary.zfill(a_)))
if __name__ == "__main__":
import doctest
doctest.testmod()
| 101 |
"""simple docstring"""
from typing import List, Optional
from ...configuration_utils import PretrainedConfig
from ...utils import logging
A = logging.get_logger(__name__)
A = {
'''huggingface/autoformer-tourism-monthly''': '''https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json''',
}
class __lowercase ( _UpperCamelCase ):
'''simple docstring'''
__lowerCAmelCase = '''autoformer'''
__lowerCAmelCase = {
'''hidden_size''': '''d_model''',
'''num_attention_heads''': '''encoder_attention_heads''',
'''num_hidden_layers''': '''encoder_layers''',
}
def __init__( self , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = "student_t" , _UpperCAmelCase = "nll" , _UpperCAmelCase = 1 , _UpperCAmelCase = [1, 2, 3, 4, 5, 6, 7] , _UpperCAmelCase = True , _UpperCAmelCase = 0 , _UpperCAmelCase = 0 , _UpperCAmelCase = 0 , _UpperCAmelCase = 0 , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = 64 , _UpperCAmelCase = 2 , _UpperCAmelCase = 2 , _UpperCAmelCase = 2 , _UpperCAmelCase = 2 , _UpperCAmelCase = 32 , _UpperCAmelCase = 32 , _UpperCAmelCase = "gelu" , _UpperCAmelCase = 0.1 , _UpperCAmelCase = 0.1 , _UpperCAmelCase = 0.1 , _UpperCAmelCase = 0.1 , _UpperCAmelCase = 0.1 , _UpperCAmelCase = 100 , _UpperCAmelCase = 0.0_2 , _UpperCAmelCase = True , _UpperCAmelCase=True , _UpperCAmelCase = 10 , _UpperCAmelCase = 25 , _UpperCAmelCase = 3 , **_UpperCAmelCase , ):
# time series specific configuration
__a : Optional[int] = prediction_length
__a : Optional[int] = context_length if context_length is not None else prediction_length
__a : Union[str, Any] = distribution_output
__a : str = loss
__a : Optional[Any] = input_size
__a : str = num_time_features
__a : Optional[Any] = lags_sequence
__a : Any = scaling
__a : Optional[Any] = num_dynamic_real_features
__a : str = num_static_real_features
__a : Any = num_static_categorical_features
if cardinality is not None and num_static_categorical_features > 0:
if len(_UpperCAmelCase ) != num_static_categorical_features:
raise ValueError(
'''The cardinality should be a list of the same length as `num_static_categorical_features`''' )
__a : List[str] = cardinality
else:
__a : Any = [0]
if embedding_dimension is not None and num_static_categorical_features > 0:
if len(_UpperCAmelCase ) != num_static_categorical_features:
raise ValueError(
'''The embedding dimension should be a list of the same length as `num_static_categorical_features`''' )
__a : Any = embedding_dimension
else:
__a : Tuple = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality]
__a : Union[str, Any] = num_parallel_samples
# Transformer architecture configuration
__a : Union[str, Any] = input_size * len(self.lags_sequence ) + self._number_of_features
__a : List[Any] = d_model
__a : List[str] = encoder_attention_heads
__a : Union[str, Any] = decoder_attention_heads
__a : Optional[int] = encoder_ffn_dim
__a : List[str] = decoder_ffn_dim
__a : List[str] = encoder_layers
__a : Optional[int] = decoder_layers
__a : Union[str, Any] = dropout
__a : Union[str, Any] = attention_dropout
__a : Optional[Any] = activation_dropout
__a : List[str] = encoder_layerdrop
__a : Any = decoder_layerdrop
__a : Union[str, Any] = activation_function
__a : Union[str, Any] = init_std
__a : List[str] = use_cache
# Autoformer
__a : int = label_length
__a : List[Any] = moving_average
__a : str = autocorrelation_factor
super().__init__(is_encoder_decoder=_UpperCAmelCase , **_UpperCAmelCase )
@property
def _lowerCamelCase ( self ):
return (
sum(self.embedding_dimension )
+ self.num_dynamic_real_features
+ self.num_time_features
+ self.num_static_real_features
+ self.input_size * 2 # the log1p(abs(loc)) and log(scale) features
)
| 101 | 1 |
import tempfile
import torch
from diffusers import (
DEISMultistepScheduler,
DPMSolverMultistepScheduler,
DPMSolverSinglestepScheduler,
UniPCMultistepScheduler,
)
from .test_schedulers import SchedulerCommonTest
class __lowercase ( UpperCAmelCase_ ):
"""simple docstring"""
_UpperCAmelCase : List[str] = (DPMSolverSinglestepScheduler,)
_UpperCAmelCase : Tuple = (('''num_inference_steps''', 25),)
def _SCREAMING_SNAKE_CASE ( self : List[str] , **lowerCAmelCase__ : Union[str, Any]):
SCREAMING_SNAKE_CASE_: Optional[Any] = {
"num_train_timesteps": 1000,
"beta_start": 0.0001,
"beta_end": 0.02,
"beta_schedule": "linear",
"solver_order": 2,
"prediction_type": "epsilon",
"thresholding": False,
"sample_max_value": 1.0,
"algorithm_type": "dpmsolver++",
"solver_type": "midpoint",
"lambda_min_clipped": -float("inf"),
"variance_type": None,
}
config.update(**lowerCAmelCase__)
return config
def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase__ : Union[str, Any]=0 , **lowerCAmelCase__ : List[str]):
SCREAMING_SNAKE_CASE_: Optional[Any] = dict(self.forward_default_kwargs)
SCREAMING_SNAKE_CASE_: Dict = kwargs.pop("num_inference_steps" , lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Any = self.dummy_sample
SCREAMING_SNAKE_CASE_: List[Any] = 0.1 * sample
SCREAMING_SNAKE_CASE_: Dict = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
SCREAMING_SNAKE_CASE_: Any = self.get_scheduler_config(**lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: List[str] = scheduler_class(**lowerCAmelCase__)
scheduler.set_timesteps(lowerCAmelCase__)
# copy over dummy past residuals
SCREAMING_SNAKE_CASE_: List[Any] = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: int = scheduler_class.from_pretrained(lowerCAmelCase__)
new_scheduler.set_timesteps(lowerCAmelCase__)
# copy over dummy past residuals
SCREAMING_SNAKE_CASE_: Optional[Any] = dummy_past_residuals[: new_scheduler.config.solver_order]
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] = sample, sample
for t in range(lowerCAmelCase__ , time_step + scheduler.config.solver_order + 1):
SCREAMING_SNAKE_CASE_: Dict = scheduler.step(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__).prev_sample
SCREAMING_SNAKE_CASE_: 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 _SCREAMING_SNAKE_CASE ( self : int):
pass
def _SCREAMING_SNAKE_CASE ( self : List[str] , lowerCAmelCase__ : Union[str, Any]=0 , **lowerCAmelCase__ : Optional[int]):
SCREAMING_SNAKE_CASE_: int = dict(self.forward_default_kwargs)
SCREAMING_SNAKE_CASE_: Dict = kwargs.pop("num_inference_steps" , lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Union[str, Any] = self.dummy_sample
SCREAMING_SNAKE_CASE_: int = 0.1 * sample
SCREAMING_SNAKE_CASE_: List[str] = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
SCREAMING_SNAKE_CASE_: Tuple = self.get_scheduler_config()
SCREAMING_SNAKE_CASE_: Union[str, Any] = scheduler_class(**lowerCAmelCase__)
scheduler.set_timesteps(lowerCAmelCase__)
# copy over dummy past residuals (must be after setting timesteps)
SCREAMING_SNAKE_CASE_: List[str] = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Any = 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)
SCREAMING_SNAKE_CASE_: int = dummy_past_residuals[: new_scheduler.config.solver_order]
SCREAMING_SNAKE_CASE_: int = scheduler.step(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__).prev_sample
SCREAMING_SNAKE_CASE_: Optional[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"
def _SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase__ : str=None , **lowerCAmelCase__ : int):
if scheduler is None:
SCREAMING_SNAKE_CASE_: Optional[int] = self.scheduler_classes[0]
SCREAMING_SNAKE_CASE_: Optional[int] = self.get_scheduler_config(**lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: List[Any] = scheduler_class(**lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Optional[int] = self.scheduler_classes[0]
SCREAMING_SNAKE_CASE_: Union[str, Any] = self.get_scheduler_config(**lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Optional[Any] = scheduler_class(**lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: int = 10
SCREAMING_SNAKE_CASE_: List[str] = self.dummy_model()
SCREAMING_SNAKE_CASE_: Dict = self.dummy_sample_deter
scheduler.set_timesteps(lowerCAmelCase__)
for i, t in enumerate(scheduler.timesteps):
SCREAMING_SNAKE_CASE_: int = model(lowerCAmelCase__ , lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: int = scheduler.step(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__).prev_sample
return sample
def _SCREAMING_SNAKE_CASE ( self : Dict):
SCREAMING_SNAKE_CASE_: Dict = DPMSolverSinglestepScheduler(**self.get_scheduler_config())
SCREAMING_SNAKE_CASE_: str = 50
SCREAMING_SNAKE_CASE_: Dict = self.dummy_model()
SCREAMING_SNAKE_CASE_: int = self.dummy_sample_deter
scheduler.set_timesteps(lowerCAmelCase__)
# make sure that the first t is uneven
for i, t in enumerate(scheduler.timesteps[3:]):
SCREAMING_SNAKE_CASE_: Any = model(lowerCAmelCase__ , lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: str = scheduler.step(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__).prev_sample
SCREAMING_SNAKE_CASE_: Dict = torch.mean(torch.abs(lowerCAmelCase__))
assert abs(result_mean.item() - 0.2574) < 1E-3
def _SCREAMING_SNAKE_CASE ( self : str):
for timesteps in [25, 50, 100, 999, 1000]:
self.check_over_configs(num_train_timesteps=lowerCAmelCase__)
def _SCREAMING_SNAKE_CASE ( self : List[str]):
# make sure that iterating over schedulers with same config names gives same results
# for defaults
SCREAMING_SNAKE_CASE_: str = DPMSolverSinglestepScheduler(**self.get_scheduler_config())
SCREAMING_SNAKE_CASE_: List[Any] = self.full_loop(scheduler=lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Optional[Any] = torch.mean(torch.abs(lowerCAmelCase__))
assert abs(result_mean.item() - 0.2791) < 1E-3
SCREAMING_SNAKE_CASE_: Dict = DEISMultistepScheduler.from_config(scheduler.config)
SCREAMING_SNAKE_CASE_: Optional[Any] = DPMSolverMultistepScheduler.from_config(scheduler.config)
SCREAMING_SNAKE_CASE_: Tuple = UniPCMultistepScheduler.from_config(scheduler.config)
SCREAMING_SNAKE_CASE_: List[Any] = DPMSolverSinglestepScheduler.from_config(scheduler.config)
SCREAMING_SNAKE_CASE_: Optional[int] = self.full_loop(scheduler=lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Union[str, Any] = torch.mean(torch.abs(lowerCAmelCase__))
assert abs(result_mean.item() - 0.2791) < 1E-3
def _SCREAMING_SNAKE_CASE ( self : Optional[Any]):
self.check_over_configs(thresholding=lowerCAmelCase__)
for order in [1, 2, 3]:
for solver_type in ["midpoint", "heun"]:
for threshold in [0.5, 1.0, 2.0]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
thresholding=lowerCAmelCase__ , prediction_type=lowerCAmelCase__ , sample_max_value=lowerCAmelCase__ , algorithm_type="dpmsolver++" , solver_order=lowerCAmelCase__ , solver_type=lowerCAmelCase__ , )
def _SCREAMING_SNAKE_CASE ( self : List[Any]):
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(prediction_type=lowerCAmelCase__)
def _SCREAMING_SNAKE_CASE ( self : List[Any]):
for algorithm_type in ["dpmsolver", "dpmsolver++"]:
for solver_type in ["midpoint", "heun"]:
for order in [1, 2, 3]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
solver_order=lowerCAmelCase__ , solver_type=lowerCAmelCase__ , prediction_type=lowerCAmelCase__ , algorithm_type=lowerCAmelCase__ , )
SCREAMING_SNAKE_CASE_: Optional[Any] = self.full_loop(
solver_order=lowerCAmelCase__ , solver_type=lowerCAmelCase__ , prediction_type=lowerCAmelCase__ , algorithm_type=lowerCAmelCase__ , )
assert not torch.isnan(lowerCAmelCase__).any(), "Samples have nan numbers"
def _SCREAMING_SNAKE_CASE ( self : List[Any]):
self.check_over_configs(lower_order_final=lowerCAmelCase__)
self.check_over_configs(lower_order_final=lowerCAmelCase__)
def _SCREAMING_SNAKE_CASE ( self : int):
self.check_over_configs(lambda_min_clipped=-float("inf"))
self.check_over_configs(lambda_min_clipped=-5.1)
def _SCREAMING_SNAKE_CASE ( self : Any):
self.check_over_configs(variance_type=lowerCAmelCase__)
self.check_over_configs(variance_type="learned_range")
def _SCREAMING_SNAKE_CASE ( self : Optional[Any]):
for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]:
self.check_over_forward(num_inference_steps=lowerCAmelCase__ , time_step=0)
def _SCREAMING_SNAKE_CASE ( self : List[Any]):
SCREAMING_SNAKE_CASE_: Optional[Any] = self.full_loop()
SCREAMING_SNAKE_CASE_: List[Any] = torch.mean(torch.abs(lowerCAmelCase__))
assert abs(result_mean.item() - 0.2791) < 1E-3
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]):
SCREAMING_SNAKE_CASE_: Dict = self.full_loop(use_karras_sigmas=lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Optional[Any] = torch.mean(torch.abs(lowerCAmelCase__))
assert abs(result_mean.item() - 0.2248) < 1E-3
def _SCREAMING_SNAKE_CASE ( self : List[str]):
SCREAMING_SNAKE_CASE_: List[Any] = self.full_loop(prediction_type="v_prediction")
SCREAMING_SNAKE_CASE_: int = torch.mean(torch.abs(lowerCAmelCase__))
assert abs(result_mean.item() - 0.1453) < 1E-3
def _SCREAMING_SNAKE_CASE ( self : Optional[Any]):
SCREAMING_SNAKE_CASE_: Dict = self.full_loop(prediction_type="v_prediction" , use_karras_sigmas=lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Tuple = torch.mean(torch.abs(lowerCAmelCase__))
assert abs(result_mean.item() - 0.0649) < 1E-3
def _SCREAMING_SNAKE_CASE ( self : Dict):
SCREAMING_SNAKE_CASE_: str = self.scheduler_classes[0]
SCREAMING_SNAKE_CASE_: List[Any] = self.get_scheduler_config(thresholding=lowerCAmelCase__ , dynamic_thresholding_ratio=0)
SCREAMING_SNAKE_CASE_: Tuple = scheduler_class(**lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: str = 10
SCREAMING_SNAKE_CASE_: Optional[int] = self.dummy_model()
SCREAMING_SNAKE_CASE_: int = self.dummy_sample_deter.half()
scheduler.set_timesteps(lowerCAmelCase__)
for i, t in enumerate(scheduler.timesteps):
SCREAMING_SNAKE_CASE_: List[Any] = model(lowerCAmelCase__ , lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Optional[int] = scheduler.step(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__).prev_sample
assert sample.dtype == torch.floataa
| 671 |
import re
def A_ ( _UpperCAmelCase ):
return [char.split() for char in re.split(R"[^ a-z A-Z 0-9 \s]" , str_ )]
def A_ ( _UpperCAmelCase ):
SCREAMING_SNAKE_CASE_: int = split_input(str_ )
return "".join(
["".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] )
def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ):
try:
SCREAMING_SNAKE_CASE_: List[Any] = split_input(_UpperCAmelCase )
if upper:
SCREAMING_SNAKE_CASE_: List[str] = "".join(
[
separator.join([char.upper() for char in sub_str] )
for sub_str in string_split
] )
else:
SCREAMING_SNAKE_CASE_: Optional[int] = "".join(
[
separator.join([char.lower() for char in sub_str] )
for sub_str in string_split
] )
return res_str
except IndexError:
return "not valid string"
def A_ ( _UpperCAmelCase ):
return to_simple_case(_UpperCAmelCase )
def A_ ( _UpperCAmelCase ):
try:
SCREAMING_SNAKE_CASE_: Optional[int] = to_simple_case(_UpperCAmelCase )
return res_str[0].lower() + res_str[1:]
except IndexError:
return "not valid string"
def A_ ( _UpperCAmelCase , _UpperCAmelCase ):
return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "_" )
def A_ ( _UpperCAmelCase , _UpperCAmelCase ):
return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "-" )
if __name__ == "__main__":
__import__("""doctest""").testmod()
| 671 | 1 |
from collections.abc import Callable
from math import pi, sqrt
from random import uniform
from statistics import mean
def __UpperCAmelCase ( lowerCamelCase_ : int ) -> Union[str, Any]:
"""simple docstring"""
def is_in_circle(lowerCamelCase_ : float , lowerCamelCase_ : float ) -> bool:
SCREAMING_SNAKE_CASE_ : Any = 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
SCREAMING_SNAKE_CASE_ : Optional[int] = mean(
int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) )
for _ in range(lowerCamelCase_ ) )
# The ratio of the area for circle to square is pi/4.
SCREAMING_SNAKE_CASE_ : Tuple = 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 __UpperCAmelCase ( lowerCamelCase_ : int , lowerCamelCase_ : Callable[[float], float] , lowerCamelCase_ : float = 0.0 , lowerCamelCase_ : float = 1.0 , ) -> float:
"""simple docstring"""
return mean(
function_to_integrate(uniform(lowerCamelCase_ , lowerCamelCase_ ) ) for _ in range(lowerCamelCase_ ) ) * (max_value - min_value)
def __UpperCAmelCase ( lowerCamelCase_ : int , lowerCamelCase_ : float = 0.0 , lowerCamelCase_ : float = 1.0 ) -> None:
"""simple docstring"""
def identity_function(lowerCamelCase_ : float ) -> float:
return x
SCREAMING_SNAKE_CASE_ : str = area_under_curve_estimator(
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = (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 __UpperCAmelCase ( lowerCamelCase_ : int ) -> None:
"""simple docstring"""
def function_to_integrate(lowerCamelCase_ : float ) -> float:
return sqrt(4.0 - x * x )
SCREAMING_SNAKE_CASE_ : Dict = area_under_curve_estimator(
lowerCamelCase_ , lowerCamelCase_ , 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()
| 702 |
from collections.abc import Callable
from math import pi, sqrt
from random import uniform
from statistics import mean
def __UpperCAmelCase ( lowerCamelCase_ : int ) -> Union[str, Any]:
"""simple docstring"""
def is_in_circle(lowerCamelCase_ : float , lowerCamelCase_ : float ) -> bool:
SCREAMING_SNAKE_CASE_ : Any = 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
SCREAMING_SNAKE_CASE_ : Optional[int] = mean(
int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) )
for _ in range(lowerCamelCase_ ) )
# The ratio of the area for circle to square is pi/4.
SCREAMING_SNAKE_CASE_ : Tuple = 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 __UpperCAmelCase ( lowerCamelCase_ : int , lowerCamelCase_ : Callable[[float], float] , lowerCamelCase_ : float = 0.0 , lowerCamelCase_ : float = 1.0 , ) -> float:
"""simple docstring"""
return mean(
function_to_integrate(uniform(lowerCamelCase_ , lowerCamelCase_ ) ) for _ in range(lowerCamelCase_ ) ) * (max_value - min_value)
def __UpperCAmelCase ( lowerCamelCase_ : int , lowerCamelCase_ : float = 0.0 , lowerCamelCase_ : float = 1.0 ) -> None:
"""simple docstring"""
def identity_function(lowerCamelCase_ : float ) -> float:
return x
SCREAMING_SNAKE_CASE_ : str = area_under_curve_estimator(
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = (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 __UpperCAmelCase ( lowerCamelCase_ : int ) -> None:
"""simple docstring"""
def function_to_integrate(lowerCamelCase_ : float ) -> float:
return sqrt(4.0 - x * x )
SCREAMING_SNAKE_CASE_ : Dict = area_under_curve_estimator(
lowerCamelCase_ , lowerCamelCase_ , 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()
| 685 | 0 |
from __future__ import annotations
import numpy as np
def UpperCamelCase_ ( __a ) -> Any:
return np.maximum(0 , __a )
if __name__ == "__main__":
print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
| 37 |
import json
from typing import Dict, List, Optional, Tuple, Union
from tokenizers import pre_tokenizers, processors
from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_led import LEDTokenizer
UpperCamelCase : Union[str, Any] = logging.get_logger(__name__)
UpperCamelCase : Optional[Any] = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}
UpperCamelCase : Optional[Any] = {
"""vocab_file""": {
"""allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json""",
},
"""merges_file""": {
"""allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt""",
},
"""tokenizer_file""": {
"""allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json""",
},
}
UpperCamelCase : Dict = {
"""allenai/led-base-16384""": 1_6384,
}
class A__ ( A__ ):
"""simple docstring"""
_lowercase = VOCAB_FILES_NAMES
_lowercase = PRETRAINED_VOCAB_FILES_MAP
_lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_lowercase = LEDTokenizer
_lowercase = ['input_ids', 'attention_mask']
def __init__( self : Tuple , lowerCamelCase__ : Any=None , lowerCamelCase__ : List[str]=None , lowerCamelCase__ : Any=None , lowerCamelCase__ : int="replace" , lowerCamelCase__ : Union[str, Any]="<s>" , lowerCamelCase__ : Union[str, Any]="</s>" , lowerCamelCase__ : Tuple="</s>" , lowerCamelCase__ : Optional[int]="<s>" , lowerCamelCase__ : str="<unk>" , lowerCamelCase__ : Any="<pad>" , lowerCamelCase__ : Any="<mask>" , lowerCamelCase__ : Optional[int]=False , lowerCamelCase__ : int=True , **lowerCamelCase__ : Union[str, Any] , ):
super().__init__(
lowerCamelCase__ , lowerCamelCase__ , tokenizer_file=lowerCamelCase__ , errors=lowerCamelCase__ , bos_token=lowerCamelCase__ , eos_token=lowerCamelCase__ , sep_token=lowerCamelCase__ , cls_token=lowerCamelCase__ , unk_token=lowerCamelCase__ , pad_token=lowerCamelCase__ , mask_token=lowerCamelCase__ , add_prefix_space=lowerCamelCase__ , trim_offsets=lowerCamelCase__ , **lowerCamelCase__ , )
a__ : List[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get("add_prefix_space" , lowerCamelCase__ ) != add_prefix_space:
a__ : List[str] = getattr(lowerCamelCase__ , pre_tok_state.pop("type" ) )
a__ : Optional[Any] = add_prefix_space
a__ : List[str] = pre_tok_class(**lowerCamelCase__ )
a__ : Optional[int] = add_prefix_space
# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
a__ : Any = "post_processor"
a__ : str = getattr(self.backend_tokenizer , lowerCamelCase__ , lowerCamelCase__ )
if tokenizer_component_instance:
a__ : Any = json.loads(tokenizer_component_instance.__getstate__() )
# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
if "sep" in state:
a__ : Optional[Any] = tuple(state["sep"] )
if "cls" in state:
a__ : Optional[Any] = tuple(state["cls"] )
a__ : Optional[int] = False
if state.get("add_prefix_space" , lowerCamelCase__ ) != add_prefix_space:
a__ : Dict = add_prefix_space
a__ : int = True
if state.get("trim_offsets" , lowerCamelCase__ ) != trim_offsets:
a__ : List[Any] = trim_offsets
a__ : List[str] = True
if changes_to_apply:
a__ : int = getattr(lowerCamelCase__ , state.pop("type" ) )
a__ : int = component_class(**lowerCamelCase__ )
setattr(self.backend_tokenizer , lowerCamelCase__ , lowerCamelCase__ )
@property
# Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED
def _UpperCamelCase( self : Union[str, Any] ):
if self._mask_token is None:
if self.verbose:
logger.error("Using mask_token, but it is not set yet." )
return None
return str(self._mask_token )
@mask_token.setter
def _UpperCamelCase( self : Optional[int] , lowerCamelCase__ : Union[str, Any] ):
a__ : Any = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else value
a__ : Union[str, Any] = value
def _UpperCamelCase( self : Any , *lowerCamelCase__ : Optional[int] , **lowerCamelCase__ : Optional[Any] ):
a__ : List[str] = kwargs.get("is_split_into_words" , lowerCamelCase__ )
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
"to use it with pretokenized inputs." )
return super()._batch_encode_plus(*lowerCamelCase__ , **lowerCamelCase__ )
def _UpperCamelCase( self : Any , *lowerCamelCase__ : Dict , **lowerCamelCase__ : Optional[Any] ):
a__ : Dict = kwargs.get("is_split_into_words" , lowerCamelCase__ )
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
"to use it with pretokenized inputs." )
return super()._encode_plus(*lowerCamelCase__ , **lowerCamelCase__ )
def _UpperCamelCase( self : Optional[int] , lowerCamelCase__ : str , lowerCamelCase__ : Optional[str] = None ):
a__ : List[str] = self._tokenizer.model.save(lowerCamelCase__ , name=lowerCamelCase__ )
return tuple(lowerCamelCase__ )
def _UpperCamelCase( self : Dict , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Optional[Any]=None ):
a__ : Any = [self.bos_token_id] + token_ids_a + [self.eos_token_id]
if token_ids_a is None:
return output
return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
def _UpperCamelCase( self : Tuple , lowerCamelCase__ : List[int] , lowerCamelCase__ : Optional[List[int]] = None ):
a__ : List[str] = [self.sep_token_id]
a__ : int = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def _UpperCamelCase( self : Dict , lowerCamelCase__ : Union[Dict[str, EncodedInput], BatchEncoding] , lowerCamelCase__ : Optional[int] = None , lowerCamelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , lowerCamelCase__ : Optional[int] = None , lowerCamelCase__ : Optional[bool] = None , ):
a__ : str = super()._pad(
encoded_inputs=lowerCamelCase__ , max_length=lowerCamelCase__ , padding_strategy=lowerCamelCase__ , pad_to_multiple_of=lowerCamelCase__ , return_attention_mask=lowerCamelCase__ , )
# Load from model defaults
if return_attention_mask is None:
a__ : Optional[int] = "attention_mask" in self.model_input_names
if return_attention_mask and "global_attention_mask" in encoded_inputs:
a__ : Tuple = encoded_inputs[self.model_input_names[0]]
# `global_attention_mask` need to have the same length as other (sequential) inputs.
a__ : Dict = len(encoded_inputs["global_attention_mask"] ) != len(lowerCamelCase__ )
if needs_to_be_padded:
a__ : Union[str, Any] = len(lowerCamelCase__ ) - len(encoded_inputs["global_attention_mask"] )
if self.padding_side == "right":
# Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
a__ : List[Any] = (
encoded_inputs["global_attention_mask"] + [-1] * difference
)
elif self.padding_side == "left":
a__ : Any = [-1] * difference + encoded_inputs[
"global_attention_mask"
]
else:
raise ValueError("Invalid padding strategy:" + str(self.padding_side ) )
return encoded_inputs
| 37 | 1 |
"""simple docstring"""
import json
import os
import unittest
from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer
from transformers.testing_utils import slow
from ...test_tokenization_common import TokenizerTesterMixin
class snake_case_( a__ , unittest.TestCase ):
__UpperCamelCase = BioGptTokenizer
__UpperCamelCase = False
def lowerCamelCase__ ( self : Union[str, Any] ):
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
lowerCAmelCase : Any = [
'''l''',
'''o''',
'''w''',
'''e''',
'''r''',
'''s''',
'''t''',
'''i''',
'''d''',
'''n''',
'''w</w>''',
'''r</w>''',
'''t</w>''',
'''lo''',
'''low''',
'''er</w>''',
'''low</w>''',
'''lowest</w>''',
'''newer</w>''',
'''wider</w>''',
'''<unk>''',
]
lowerCAmelCase : Union[str, Any] = dict(zip(UpperCamelCase_ , range(len(UpperCamelCase_ ) ) ) )
lowerCAmelCase : List[str] = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', '''''']
lowerCAmelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
lowerCAmelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] )
with open(self.vocab_file , '''w''' ) as fp:
fp.write(json.dumps(UpperCamelCase_ ) )
with open(self.merges_file , '''w''' ) as fp:
fp.write('''\n'''.join(UpperCamelCase_ ) )
def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : Dict ):
lowerCAmelCase : List[str] = '''lower newer'''
lowerCAmelCase : List[str] = '''lower newer'''
return input_text, output_text
def lowerCamelCase__ ( self : Union[str, Any] ):
lowerCAmelCase : Dict = BioGptTokenizer(self.vocab_file , self.merges_file )
lowerCAmelCase : List[str] = '''lower'''
lowerCAmelCase : Tuple = ['''low''', '''er</w>''']
lowerCAmelCase : Dict = tokenizer.tokenize(UpperCamelCase_ )
self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ )
lowerCAmelCase : List[str] = tokens + ['''<unk>''']
lowerCAmelCase : Tuple = [1_4, 1_5, 2_0]
self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase_ ) , UpperCamelCase_ )
@slow
def lowerCamelCase__ ( self : Union[str, Any] ):
lowerCAmelCase : List[Any] = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' )
lowerCAmelCase : Dict = tokenizer.encode('''sequence builders''' , add_special_tokens=UpperCamelCase_ )
lowerCAmelCase : Tuple = tokenizer.encode('''multi-sequence build''' , add_special_tokens=UpperCamelCase_ )
lowerCAmelCase : str = tokenizer.build_inputs_with_special_tokens(UpperCamelCase_ )
lowerCAmelCase : Any = tokenizer.build_inputs_with_special_tokens(UpperCamelCase_ , UpperCamelCase_ )
self.assertTrue(encoded_sentence == [2] + text )
self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
| 700 |
"""simple docstring"""
from __future__ import annotations
from PIL import Image
# Define glider example
snake_case__ : int = [
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[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],
]
# Define blinker example
snake_case__ : Any = [[0, 1, 0], [0, 1, 0], [0, 1, 0]]
def _snake_case ( _snake_case : list[list[int]] ):
lowerCAmelCase : Union[str, Any] = []
for i in range(len(_snake_case ) ):
lowerCAmelCase : Any = []
for j in range(len(cells[i] ) ):
# Get the number of live neighbours
lowerCAmelCase : Optional[int] = 0
if i > 0 and j > 0:
neighbour_count += cells[i - 1][j - 1]
if i > 0:
neighbour_count += cells[i - 1][j]
if i > 0 and j < len(cells[i] ) - 1:
neighbour_count += cells[i - 1][j + 1]
if j > 0:
neighbour_count += cells[i][j - 1]
if j < len(cells[i] ) - 1:
neighbour_count += cells[i][j + 1]
if i < len(_snake_case ) - 1 and j > 0:
neighbour_count += cells[i + 1][j - 1]
if i < len(_snake_case ) - 1:
neighbour_count += cells[i + 1][j]
if i < len(_snake_case ) - 1 and j < len(cells[i] ) - 1:
neighbour_count += cells[i + 1][j + 1]
# Rules of the game of life (excerpt from Wikipedia):
# 1. Any live cell with two or three live neighbours survives.
# 2. Any dead cell with three live neighbours becomes a live cell.
# 3. All other live cells die in the next generation.
# Similarly, all other dead cells stay dead.
lowerCAmelCase : str = cells[i][j] == 1
if (
(alive and 2 <= neighbour_count <= 3)
or not alive
and neighbour_count == 3
):
next_generation_row.append(1 )
else:
next_generation_row.append(0 )
next_generation.append(_snake_case )
return next_generation
def _snake_case ( _snake_case : list[list[int]] , _snake_case : int ):
lowerCAmelCase : int = []
for _ in range(_snake_case ):
# Create output image
lowerCAmelCase : Union[str, Any] = Image.new('''RGB''' , (len(cells[0] ), len(_snake_case )) )
lowerCAmelCase : Union[str, Any] = img.load()
# Save cells to image
for x in range(len(_snake_case ) ):
for y in range(len(cells[0] ) ):
lowerCAmelCase : Optional[int] = 255 - cells[y][x] * 255
lowerCAmelCase : List[Any] = (colour, colour, colour)
# Save image
images.append(_snake_case )
lowerCAmelCase : Union[str, Any] = new_generation(_snake_case )
return images
if __name__ == "__main__":
snake_case__ : Union[str, Any] = generate_images(GLIDER, 16)
images[0].save('''out.gif''', save_all=True, append_images=images[1:])
| 637 | 0 |
'''simple docstring'''
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments
def UpperCAmelCase_ ( ):
"""simple docstring"""
lowerCAmelCase__ : Tuple = HfArgumentParser(lowerCamelCase_ )
lowerCAmelCase__ : Dict = parser.parse_args_into_dataclasses()[0]
lowerCAmelCase__ : Optional[Any] = TensorFlowBenchmark(args=lowerCamelCase_ )
try:
lowerCAmelCase__ : Optional[Any] = parser.parse_args_into_dataclasses()[0]
except ValueError as e:
lowerCAmelCase__ : str = "Arg --no_{0} is no longer used, please use --no-{0} instead."
lowerCAmelCase__ : str = " ".join(str(lowerCamelCase_ ).split(" " )[:-1] )
lowerCAmelCase__ : str = ""
lowerCAmelCase__ : int = eval(str(lowerCamelCase_ ).split(" " )[-1] )
lowerCAmelCase__ : Union[str, Any] = []
for arg in depreciated_args:
# arg[2:] removes '--'
if arg[2:] in TensorFlowBenchmark.deprecated_args:
# arg[5:] removes '--no_'
full_error_msg += arg_error_msg.format(arg[5:] )
else:
wrong_args.append(lowerCamelCase_ )
if len(lowerCamelCase_ ) > 0:
lowerCAmelCase__ : Union[str, Any] = full_error_msg + begin_error_msg + str(lowerCamelCase_ )
raise ValueError(lowerCamelCase_ )
benchmark.run()
if __name__ == "__main__":
main()
| 378 |
'''simple docstring'''
import warnings
from functools import wraps
from typing import Callable
def UpperCAmelCase_ ( lowerCamelCase_ ):
"""simple docstring"""
@wraps(lowerCamelCase_ )
def _inner_fn(*lowerCamelCase_ , **lowerCamelCase_ ):
warnings.warn(
(f'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') , lowerCamelCase_ , )
return fn(*lowerCamelCase_ , **lowerCamelCase_ )
return _inner_fn
| 378 | 1 |
import unittest
from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
__lowerCAmelCase = get_tests_dir("fixtures/test_sentencepiece.model")
@require_sentencepiece
class __SCREAMING_SNAKE_CASE ( _lowercase , unittest.TestCase):
__SCREAMING_SNAKE_CASE : str = XLMProphetNetTokenizer
__SCREAMING_SNAKE_CASE : Union[str, Any] = False
__SCREAMING_SNAKE_CASE : List[str] = True
def UpperCAmelCase__ ( self : Union[str, Any] ):
super().setUp()
# We have a SentencePiece fixture for testing
_UpperCAmelCase = XLMProphetNetTokenizer(A_ , keep_accents=A_ )
tokenizer.save_pretrained(self.tmpdirname )
def UpperCAmelCase__ ( self : int ):
_UpperCAmelCase = "[PAD]"
_UpperCAmelCase = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(A_ ) , A_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(A_ ) , A_ )
def UpperCAmelCase__ ( self : int ):
_UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "[PAD]" )
self.assertEqual(vocab_keys[1] , "[CLS]" )
self.assertEqual(vocab_keys[-1] , "j" )
self.assertEqual(len(A_ ) , 1_012 )
def UpperCAmelCase__ ( self : Optional[int] ):
self.assertEqual(self.get_tokenizer().vocab_size , 1_012 )
def UpperCAmelCase__ ( self : Union[str, Any] ):
_UpperCAmelCase = XLMProphetNetTokenizer(A_ , keep_accents=A_ )
_UpperCAmelCase = tokenizer.tokenize("This is a test" )
self.assertListEqual(A_ , ["▁This", "▁is", "▁a", "▁t", "est"] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(A_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , )
_UpperCAmelCase = 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",
"é",
".",
] , )
_UpperCAmelCase = tokenizer.convert_tokens_to_ids(A_ )
self.assertListEqual(
A_ , [
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4]
] , )
_UpperCAmelCase = 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 UpperCAmelCase__ ( self : Union[str, Any] ):
return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased" )
@slow
def UpperCAmelCase__ ( self : Optional[int] ):
_UpperCAmelCase = "Hello World!"
_UpperCAmelCase = [35_389, 6_672, 49, 2]
self.assertListEqual(A_ , self.big_tokenizer.encode(A_ ) )
@slow
def UpperCAmelCase__ ( self : Dict ):
# fmt: off
_UpperCAmelCase = {"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=A_ , model_name="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
| 700 |
import json
import os
import shutil
import warnings
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import List
from ..utils import logging
from . import BaseTransformersCLICommand
try:
from cookiecutter.main import cookiecutter
__lowerCAmelCase = True
except ImportError:
__lowerCAmelCase = False
__lowerCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name
def __lowerCamelCase ( _lowerCAmelCase ) -> str:
return AddNewModelCommand(args.testing , args.testing_file , path=args.path )
class __SCREAMING_SNAKE_CASE ( lowercase):
@staticmethod
def UpperCAmelCase__ ( __UpperCamelCase : ArgumentParser ):
_UpperCAmelCase = parser.add_parser("add-new-model" )
add_new_model_parser.add_argument("--testing" , action="store_true" , help="If in testing mode." )
add_new_model_parser.add_argument("--testing_file" , type=__UpperCamelCase , help="Configuration file on which to run." )
add_new_model_parser.add_argument(
"--path" , type=__UpperCamelCase , help="Path to cookiecutter. Should only be used for testing purposes." )
add_new_model_parser.set_defaults(func=__UpperCamelCase )
def __init__( self : List[Any] , __UpperCamelCase : bool , __UpperCamelCase : str , __UpperCamelCase : List[str]=None , *__UpperCamelCase : List[Any] ):
_UpperCAmelCase = testing
_UpperCAmelCase = testing_file
_UpperCAmelCase = path
def UpperCAmelCase__ ( self : List[Any] ):
warnings.warn(
"The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. "
"It is not actively maintained anymore, so might give a result that won't pass all tests and quality "
"checks, you should use `transformers-cli add-new-model-like` instead." )
if not _has_cookiecutter:
raise ImportError(
"Model creation dependencies are required to use the `add_new_model` command. Install them by running "
"the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n" )
# Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory
_UpperCAmelCase = [directory for directory in os.listdir() if "cookiecutter-template-" == directory[:22]]
if len(__UpperCamelCase ) > 0:
raise ValueError(
"Several directories starting with `cookiecutter-template-` in current working directory. "
"Please clean your directory by removing all folders starting with `cookiecutter-template-` or "
"change your working directory." )
_UpperCAmelCase = (
Path(__UpperCamelCase ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent
)
_UpperCAmelCase = path_to_transformer_root / "templates" / "adding_a_new_model"
# Execute cookiecutter
if not self._testing:
cookiecutter(str(__UpperCamelCase ) )
else:
with open(self._testing_file , "r" ) as configuration_file:
_UpperCAmelCase = json.load(__UpperCamelCase )
cookiecutter(
str(path_to_cookiecutter if self._path is None else self._path ) , no_input=__UpperCamelCase , extra_context=__UpperCamelCase , )
_UpperCAmelCase = [directory for directory in os.listdir() if "cookiecutter-template-" in directory[:22]][0]
# Retrieve configuration
with open(directory + "/configuration.json" , "r" ) as configuration_file:
_UpperCAmelCase = json.load(__UpperCamelCase )
_UpperCAmelCase = configuration["lowercase_modelname"]
_UpperCAmelCase = configuration["generate_tensorflow_pytorch_and_flax"]
os.remove(F'''{directory}/configuration.json''' )
_UpperCAmelCase = "PyTorch" in generate_tensorflow_pytorch_and_flax
_UpperCAmelCase = "TensorFlow" in generate_tensorflow_pytorch_and_flax
_UpperCAmelCase = "Flax" in generate_tensorflow_pytorch_and_flax
_UpperCAmelCase = F'''{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}'''
os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase )
os.makedirs(F'''{path_to_transformer_root}/tests/models/{lowercase_model_name}''' , exist_ok=__UpperCamelCase )
# Tests require submodules as they have parent imports
with open(F'''{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py''' , "w" ):
pass
shutil.move(
F'''{directory}/__init__.py''' , F'''{model_dir}/__init__.py''' , )
shutil.move(
F'''{directory}/configuration_{lowercase_model_name}.py''' , F'''{model_dir}/configuration_{lowercase_model_name}.py''' , )
def remove_copy_lines(__UpperCamelCase : str ):
with open(__UpperCamelCase , "r" ) as f:
_UpperCAmelCase = f.readlines()
with open(__UpperCamelCase , "w" ) as f:
for line in lines:
if "# Copied from transformers." not in line:
f.write(__UpperCamelCase )
if output_pytorch:
if not self._testing:
remove_copy_lines(F'''{directory}/modeling_{lowercase_model_name}.py''' )
shutil.move(
F'''{directory}/modeling_{lowercase_model_name}.py''' , F'''{model_dir}/modeling_{lowercase_model_name}.py''' , )
shutil.move(
F'''{directory}/test_modeling_{lowercase_model_name}.py''' , F'''{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py''' , )
else:
os.remove(F'''{directory}/modeling_{lowercase_model_name}.py''' )
os.remove(F'''{directory}/test_modeling_{lowercase_model_name}.py''' )
if output_tensorflow:
if not self._testing:
remove_copy_lines(F'''{directory}/modeling_tf_{lowercase_model_name}.py''' )
shutil.move(
F'''{directory}/modeling_tf_{lowercase_model_name}.py''' , F'''{model_dir}/modeling_tf_{lowercase_model_name}.py''' , )
shutil.move(
F'''{directory}/test_modeling_tf_{lowercase_model_name}.py''' , F'''{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py''' , )
else:
os.remove(F'''{directory}/modeling_tf_{lowercase_model_name}.py''' )
os.remove(F'''{directory}/test_modeling_tf_{lowercase_model_name}.py''' )
if output_flax:
if not self._testing:
remove_copy_lines(F'''{directory}/modeling_flax_{lowercase_model_name}.py''' )
shutil.move(
F'''{directory}/modeling_flax_{lowercase_model_name}.py''' , F'''{model_dir}/modeling_flax_{lowercase_model_name}.py''' , )
shutil.move(
F'''{directory}/test_modeling_flax_{lowercase_model_name}.py''' , F'''{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py''' , )
else:
os.remove(F'''{directory}/modeling_flax_{lowercase_model_name}.py''' )
os.remove(F'''{directory}/test_modeling_flax_{lowercase_model_name}.py''' )
shutil.move(
F'''{directory}/{lowercase_model_name}.md''' , F'''{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md''' , )
shutil.move(
F'''{directory}/tokenization_{lowercase_model_name}.py''' , F'''{model_dir}/tokenization_{lowercase_model_name}.py''' , )
shutil.move(
F'''{directory}/tokenization_fast_{lowercase_model_name}.py''' , F'''{model_dir}/tokenization_{lowercase_model_name}_fast.py''' , )
from os import fdopen, remove
from shutil import copymode, move
from tempfile import mkstemp
def replace(__UpperCamelCase : str , __UpperCamelCase : str , __UpperCamelCase : List[str] ):
# Create temp file
_UpperCAmelCase , _UpperCAmelCase = mkstemp()
_UpperCAmelCase = False
with fdopen(__UpperCamelCase , "w" ) as new_file:
with open(__UpperCamelCase ) as old_file:
for line in old_file:
new_file.write(__UpperCamelCase )
if line_to_copy_below in line:
_UpperCAmelCase = True
for line_to_copy in lines_to_copy:
new_file.write(__UpperCamelCase )
if not line_found:
raise ValueError(F'''Line {line_to_copy_below} was not found in file.''' )
# Copy the file permissions from the old file to the new file
copymode(__UpperCamelCase , __UpperCamelCase )
# Remove original file
remove(__UpperCamelCase )
# Move new file
move(__UpperCamelCase , __UpperCamelCase )
def skip_units(__UpperCamelCase : List[Any] ):
return (
("generating PyTorch" in line and not output_pytorch)
or ("generating TensorFlow" in line and not output_tensorflow)
or ("generating Flax" in line and not output_flax)
)
def replace_in_files(__UpperCamelCase : Union[str, Any] ):
with open(__UpperCamelCase ) as datafile:
_UpperCAmelCase = []
_UpperCAmelCase = False
_UpperCAmelCase = False
for line in datafile:
if "# To replace in: " in line and "##" not in line:
_UpperCAmelCase = line.split("\"" )[1]
_UpperCAmelCase = skip_units(__UpperCamelCase )
elif "# Below: " in line and "##" not in line:
_UpperCAmelCase = line.split("\"" )[1]
_UpperCAmelCase = skip_units(__UpperCamelCase )
elif "# End." in line and "##" not in line:
if not skip_file and not skip_snippet:
replace(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
_UpperCAmelCase = []
elif "# Replace with" in line and "##" not in line:
_UpperCAmelCase = []
elif "##" not in line:
lines_to_copy.append(__UpperCamelCase )
remove(__UpperCamelCase )
replace_in_files(F'''{directory}/to_replace_{lowercase_model_name}.py''' )
os.rmdir(__UpperCamelCase )
| 129 | 0 |
"""simple docstring"""
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
lowerCAmelCase_ : List[str] = {
'''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:
lowerCAmelCase_ : Optional[Any] = [
'''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
lowerCAmelCase_ : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 673 |
"""simple docstring"""
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCAmelCase_ : int = logging.get_logger(__name__)
lowerCAmelCase_ : Any = {
'''facebook/wav2vec2-base-960h''': '''https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json''',
# See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2
}
class UpperCamelCase_ ( a_ ):
_A : int = 'wav2vec2'
def __init__( self , snake_case__=32 , snake_case__=7_68 , snake_case__=12 , snake_case__=12 , snake_case__=30_72 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=0.1 , snake_case__=0.0 , snake_case__=0.0 , snake_case__=0.1 , snake_case__=0.1 , snake_case__=0.02 , snake_case__=1e-5 , snake_case__="group" , snake_case__="gelu" , snake_case__=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , snake_case__=(5, 2, 2, 2, 2, 2, 2) , snake_case__=(10, 3, 3, 3, 3, 2, 2) , snake_case__=False , snake_case__=1_28 , snake_case__=16 , snake_case__=False , snake_case__=True , snake_case__=0.05 , snake_case__=10 , snake_case__=2 , snake_case__=0.0 , snake_case__=10 , snake_case__=0 , snake_case__=3_20 , snake_case__=2 , snake_case__=0.1 , snake_case__=1_00 , snake_case__=2_56 , snake_case__=2_56 , snake_case__=0.1 , snake_case__="sum" , snake_case__=False , snake_case__=False , snake_case__=2_56 , snake_case__=(5_12, 5_12, 5_12, 5_12, 15_00) , snake_case__=(5, 3, 3, 1, 1) , snake_case__=(1, 2, 3, 1, 1) , snake_case__=5_12 , snake_case__=0 , snake_case__=1 , snake_case__=2 , snake_case__=False , snake_case__=3 , snake_case__=2 , snake_case__=3 , snake_case__=None , snake_case__=None , **snake_case__ , ) -> Optional[Any]:
"""simple docstring"""
super().__init__(**snake_case__ , pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ )
UpperCAmelCase = hidden_size
UpperCAmelCase = feat_extract_norm
UpperCAmelCase = feat_extract_activation
UpperCAmelCase = list(snake_case__ )
UpperCAmelCase = list(snake_case__ )
UpperCAmelCase = list(snake_case__ )
UpperCAmelCase = conv_bias
UpperCAmelCase = num_conv_pos_embeddings
UpperCAmelCase = num_conv_pos_embedding_groups
UpperCAmelCase = len(self.conv_dim )
UpperCAmelCase = num_hidden_layers
UpperCAmelCase = intermediate_size
UpperCAmelCase = hidden_act
UpperCAmelCase = num_attention_heads
UpperCAmelCase = hidden_dropout
UpperCAmelCase = attention_dropout
UpperCAmelCase = activation_dropout
UpperCAmelCase = feat_proj_dropout
UpperCAmelCase = final_dropout
UpperCAmelCase = layerdrop
UpperCAmelCase = layer_norm_eps
UpperCAmelCase = initializer_range
UpperCAmelCase = vocab_size
UpperCAmelCase = do_stable_layer_norm
UpperCAmelCase = use_weighted_layer_sum
if (
(len(self.conv_stride ) != self.num_feat_extract_layers)
or (len(self.conv_kernel ) != self.num_feat_extract_layers)
or (len(self.conv_dim ) != self.num_feat_extract_layers)
):
raise ValueError(
"""Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="""
""" `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="""
f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,'''
f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
UpperCAmelCase = apply_spec_augment
UpperCAmelCase = mask_time_prob
UpperCAmelCase = mask_time_length
UpperCAmelCase = mask_time_min_masks
UpperCAmelCase = mask_feature_prob
UpperCAmelCase = mask_feature_length
UpperCAmelCase = mask_feature_min_masks
# parameters for pretraining with codevector quantized representations
UpperCAmelCase = num_codevectors_per_group
UpperCAmelCase = num_codevector_groups
UpperCAmelCase = contrastive_logits_temperature
UpperCAmelCase = feat_quantizer_dropout
UpperCAmelCase = num_negatives
UpperCAmelCase = codevector_dim
UpperCAmelCase = proj_codevector_dim
UpperCAmelCase = diversity_loss_weight
# ctc loss
UpperCAmelCase = ctc_loss_reduction
UpperCAmelCase = ctc_zero_infinity
# adapter
UpperCAmelCase = add_adapter
UpperCAmelCase = adapter_kernel_size
UpperCAmelCase = adapter_stride
UpperCAmelCase = num_adapter_layers
UpperCAmelCase = output_hidden_size or hidden_size
UpperCAmelCase = adapter_attn_dim
# SequenceClassification-specific parameter. Feel free to ignore for other classes.
UpperCAmelCase = classifier_proj_size
# XVector-specific parameters. Feel free to ignore for other classes.
UpperCAmelCase = list(snake_case__ )
UpperCAmelCase = list(snake_case__ )
UpperCAmelCase = list(snake_case__ )
UpperCAmelCase = xvector_output_dim
@property
def UpperCamelCase_ ( self ) -> Optional[Any]:
"""simple docstring"""
return functools.reduce(operator.mul , self.conv_stride , 1 )
| 673 | 1 |
"""simple docstring"""
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
a_ = logging.get_logger(__name__)
a_ = {
"""facebook/data2vec-vision-base-ft""": (
"""https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json"""
),
}
class A_(SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
a_ : int = 'data2vec-vision'
def __init__( self , A=768 , A=12 , A=12 , A=3072 , A="gelu" , A=0.0 , A=0.0 , A=0.0_2 , A=1E-12 , A=224 , A=16 , A=3 , A=False , A=False , A=False , A=False , A=0.1 , A=0.1 , A=True , A=[3, 5, 7, 11] , A=[1, 2, 3, 6] , A=True , A=0.4 , A=256 , A=1 , A=False , A=255 , **A , ):
super().__init__(**A )
_lowerCamelCase : Dict = hidden_size
_lowerCamelCase : int = num_hidden_layers
_lowerCamelCase : Union[str, Any] = num_attention_heads
_lowerCamelCase : Union[str, Any] = intermediate_size
_lowerCamelCase : List[str] = hidden_act
_lowerCamelCase : List[str] = hidden_dropout_prob
_lowerCamelCase : Dict = attention_probs_dropout_prob
_lowerCamelCase : Optional[int] = initializer_range
_lowerCamelCase : Optional[Any] = layer_norm_eps
_lowerCamelCase : int = image_size
_lowerCamelCase : Tuple = patch_size
_lowerCamelCase : List[Any] = num_channels
_lowerCamelCase : Optional[Any] = use_mask_token
_lowerCamelCase : str = use_absolute_position_embeddings
_lowerCamelCase : Union[str, Any] = use_relative_position_bias
_lowerCamelCase : int = use_shared_relative_position_bias
_lowerCamelCase : Any = layer_scale_init_value
_lowerCamelCase : List[str] = drop_path_rate
_lowerCamelCase : Optional[Any] = use_mean_pooling
# decode head attributes (semantic segmentation)
_lowerCamelCase : Any = out_indices
_lowerCamelCase : Union[str, Any] = pool_scales
# auxiliary head attributes (semantic segmentation)
_lowerCamelCase : Tuple = use_auxiliary_head
_lowerCamelCase : Any = auxiliary_loss_weight
_lowerCamelCase : Any = auxiliary_channels
_lowerCamelCase : str = auxiliary_num_convs
_lowerCamelCase : str = auxiliary_concat_input
_lowerCamelCase : Any = semantic_loss_ignore_index
class A_(SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
a_ : Dict = version.parse("""1.11""" )
@property
def _lowerCAmelCase ( self ):
return OrderedDict(
[
('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
] )
@property
def _lowerCAmelCase ( self ):
return 1E-4
| 701 |
"""simple docstring"""
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import CLIPImageProcessor, CLIPProcessor
@require_vision
class A_(unittest.TestCase ):
"""simple docstring"""
def _lowerCAmelCase ( self ):
_lowerCamelCase : Optional[int] = tempfile.mkdtemp()
# fmt: off
_lowerCamelCase : List[str] = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>']
# fmt: on
_lowerCamelCase : Optional[Any] = dict(zip(A , range(len(A ) ) ) )
_lowerCamelCase : Optional[int] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', '']
_lowerCamelCase : Optional[Any] = {'unk_token': '<unk>'}
_lowerCamelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] )
_lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] )
with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp:
fp.write(json.dumps(A ) + '\n' )
with open(self.merges_file , 'w' , encoding='utf-8' ) as fp:
fp.write('\n'.join(A ) )
_lowerCamelCase : Any = {
'do_resize': True,
'size': 20,
'do_center_crop': True,
'crop_size': 18,
'do_normalize': True,
'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3],
'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1],
}
_lowerCamelCase : List[Any] = os.path.join(self.tmpdirname , A )
with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp:
json.dump(A , A )
def _lowerCAmelCase ( self , **A ):
return CLIPTokenizer.from_pretrained(self.tmpdirname , **A )
def _lowerCAmelCase ( self , **A ):
return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **A )
def _lowerCAmelCase ( self , **A ):
return CLIPImageProcessor.from_pretrained(self.tmpdirname , **A )
def _lowerCAmelCase ( self ):
shutil.rmtree(self.tmpdirname )
def _lowerCAmelCase ( self ):
_lowerCamelCase : Optional[int] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
_lowerCamelCase : List[Any] = [Image.fromarray(np.moveaxis(A , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def _lowerCAmelCase ( self ):
_lowerCamelCase : Optional[Any] = self.get_tokenizer()
_lowerCamelCase : Optional[int] = self.get_rust_tokenizer()
_lowerCamelCase : List[str] = self.get_image_processor()
_lowerCamelCase : str = CLIPProcessor(tokenizer=A , image_processor=A )
processor_slow.save_pretrained(self.tmpdirname )
_lowerCamelCase : Union[str, Any] = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=A )
_lowerCamelCase : Dict = CLIPProcessor(tokenizer=A , image_processor=A )
processor_fast.save_pretrained(self.tmpdirname )
_lowerCamelCase : Dict = CLIPProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() )
self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() )
self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() )
self.assertIsInstance(processor_slow.tokenizer , A )
self.assertIsInstance(processor_fast.tokenizer , A )
self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertIsInstance(processor_slow.image_processor , A )
self.assertIsInstance(processor_fast.image_processor , A )
def _lowerCAmelCase ( self ):
_lowerCamelCase : str = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
_lowerCamelCase : int = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' )
_lowerCamelCase : str = self.get_image_processor(do_normalize=A , padding_value=1.0 )
_lowerCamelCase : Dict = CLIPProcessor.from_pretrained(
self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=A , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , A )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , A )
def _lowerCAmelCase ( self ):
_lowerCamelCase : List[str] = self.get_image_processor()
_lowerCamelCase : str = self.get_tokenizer()
_lowerCamelCase : Any = CLIPProcessor(tokenizer=A , image_processor=A )
_lowerCamelCase : str = self.prepare_image_inputs()
_lowerCamelCase : List[Any] = image_processor(A , return_tensors='np' )
_lowerCamelCase : int = processor(images=A , return_tensors='np' )
for key in input_image_proc.keys():
self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 )
def _lowerCAmelCase ( self ):
_lowerCamelCase : Dict = self.get_image_processor()
_lowerCamelCase : List[Any] = self.get_tokenizer()
_lowerCamelCase : Dict = CLIPProcessor(tokenizer=A , image_processor=A )
_lowerCamelCase : Optional[Any] = 'lower newer'
_lowerCamelCase : Union[str, Any] = processor(text=A )
_lowerCamelCase : Tuple = tokenizer(A )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def _lowerCAmelCase ( self ):
_lowerCamelCase : str = self.get_image_processor()
_lowerCamelCase : List[str] = self.get_tokenizer()
_lowerCamelCase : List[Any] = CLIPProcessor(tokenizer=A , image_processor=A )
_lowerCamelCase : Any = 'lower newer'
_lowerCamelCase : Any = self.prepare_image_inputs()
_lowerCamelCase : Optional[int] = processor(text=A , images=A )
self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] )
# test if it raises when no input is passed
with pytest.raises(A ):
processor()
def _lowerCAmelCase ( self ):
_lowerCamelCase : Optional[int] = self.get_image_processor()
_lowerCamelCase : List[Any] = self.get_tokenizer()
_lowerCamelCase : Optional[int] = CLIPProcessor(tokenizer=A , image_processor=A )
_lowerCamelCase : Dict = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
_lowerCamelCase : int = processor.batch_decode(A )
_lowerCamelCase : Dict = tokenizer.batch_decode(A )
self.assertListEqual(A , A )
def _lowerCAmelCase ( self ):
_lowerCamelCase : Any = self.get_image_processor()
_lowerCamelCase : int = self.get_tokenizer()
_lowerCamelCase : int = CLIPProcessor(tokenizer=A , image_processor=A )
_lowerCamelCase : str = 'lower newer'
_lowerCamelCase : List[str] = self.prepare_image_inputs()
_lowerCamelCase : Optional[int] = processor(text=A , images=A )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 349 | 0 |
"""simple docstring"""
from collections import defaultdict
def snake_case_ ( A_ : int ):
'''simple docstring'''
_lowerCamelCase : List[Any] = 1
_lowerCamelCase : List[Any] = True
for v in tree[start]:
if v not in visited:
ret += dfs(A_ )
if ret % 2 == 0:
cuts.append(A_ )
return ret
def snake_case_ ( ):
'''simple docstring'''
dfs(1 )
if __name__ == "__main__":
lowerCAmelCase__ , lowerCAmelCase__ = 10, 9
lowerCAmelCase__ = defaultdict(list)
lowerCAmelCase__ = {}
lowerCAmelCase__ = []
lowerCAmelCase__ = 0
lowerCAmelCase__ = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)]
for u, v in edges:
tree[u].append(v)
tree[v].append(u)
even_tree()
print(len(cuts) - 1)
| 83 |
'''simple docstring'''
import sys
lowerCAmelCase_ : List[str] = (
"73167176531330624919225119674426574742355349194934"
"96983520312774506326239578318016984801869478851843"
"85861560789112949495459501737958331952853208805511"
"12540698747158523863050715693290963295227443043557"
"66896648950445244523161731856403098711121722383113"
"62229893423380308135336276614282806444486645238749"
"30358907296290491560440772390713810515859307960866"
"70172427121883998797908792274921901699720888093776"
"65727333001053367881220235421809751254540594752243"
"52584907711670556013604839586446706324415722155397"
"53697817977846174064955149290862569321978468622482"
"83972241375657056057490261407972968652414535100474"
"82166370484403199890008895243450658541227588666881"
"16427171479924442928230863465674813919123162824586"
"17866458359124566529476545682848912883142607690042"
"24219022671055626321111109370544217506941658960408"
"07198403850962455444362981230987879927244284909188"
"84580156166097919133875499200524063689912560717606"
"05886116467109405077541002256983155200055935729725"
"71636269561882670428252483600823257530420752963450"
)
def _lowerCamelCase (__lowerCamelCase : str = N ) -> int:
a__ = -sys.maxsize - 1
for i in range(len(__lowerCamelCase ) - 12 ):
a__ = 1
for j in range(13 ):
product *= int(n[i + j] )
if product > largest_product:
a__ = product
return largest_product
if __name__ == "__main__":
print(f"""{solution() = }""")
| 489 | 0 |
from jiwer import compute_measures
import datasets
__a = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n'
__a = '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n'
__a = '\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = ["this is the prediction", "there is an other sample"]\n >>> references = ["this is the reference", "there is another one"]\n >>> wer = datasets.load_metric("wer")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class __a( datasets.Metric ):
"""simple docstring"""
def a__ ( self ) -> List[Any]:
return datasets.MetricInfo(
description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features(
{
'''predictions''': datasets.Value('''string''' ,id='''sequence''' ),
'''references''': datasets.Value('''string''' ,id='''sequence''' ),
} ) ,codebase_urls=['''https://github.com/jitsi/jiwer/'''] ,reference_urls=[
'''https://en.wikipedia.org/wiki/Word_error_rate''',
] ,)
def a__ ( self ,_SCREAMING_SNAKE_CASE=None ,_SCREAMING_SNAKE_CASE=None ,_SCREAMING_SNAKE_CASE=False ) -> int:
if concatenate_texts:
return compute_measures(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )["wer"]
else:
UpperCAmelCase_ : int = 0
UpperCAmelCase_ : Dict = 0
for prediction, reference in zip(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ):
UpperCAmelCase_ : Union[str, Any] = compute_measures(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
total += measures["substitutions"] + measures["deletions"] + measures["hits"]
return incorrect / total
| 300 |
import json
import os
import shutil
import tempfile
import unittest
from multiprocessing import get_context
from pathlib import Path
import datasets
import numpy as np
from datasets import load_dataset
from parameterized import parameterized
from transformers import AutoProcessor
from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available
from ..wavaveca.test_feature_extraction_wavaveca import floats_list
if is_pyctcdecode_available():
from huggingface_hub import snapshot_download
from pyctcdecode import BeamSearchDecoderCTC
from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM
from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput
if is_torch_available():
from transformers import WavaVecaForCTC
@require_pyctcdecode
class __a( unittest.TestCase ):
"""simple docstring"""
def a__ ( self ) -> List[Any]:
UpperCAmelCase_ : Dict = '''| <pad> <unk> <s> </s> a b c d e f g h i j k'''.split()
UpperCAmelCase_ : int = dict(zip(_SCREAMING_SNAKE_CASE ,range(len(_SCREAMING_SNAKE_CASE ) ) ) )
UpperCAmelCase_ : List[Any] = {
'''unk_token''': '''<unk>''',
'''bos_token''': '''<s>''',
'''eos_token''': '''</s>''',
}
UpperCAmelCase_ : Dict = {
'''feature_size''': 1,
'''padding_value''': 0.0,
'''sampling_rate''': 16_000,
'''return_attention_mask''': False,
'''do_normalize''': True,
}
UpperCAmelCase_ : str = tempfile.mkdtemp()
UpperCAmelCase_ : Optional[Any] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['''vocab_file'''] )
UpperCAmelCase_ : List[str] = os.path.join(self.tmpdirname ,_SCREAMING_SNAKE_CASE )
with open(self.vocab_file ,'''w''' ,encoding='''utf-8''' ) as fp:
fp.write(json.dumps(_SCREAMING_SNAKE_CASE ) + '''\n''' )
with open(self.feature_extraction_file ,'''w''' ,encoding='''utf-8''' ) as fp:
fp.write(json.dumps(_SCREAMING_SNAKE_CASE ) + '''\n''' )
# load decoder from hub
UpperCAmelCase_ : str = '''hf-internal-testing/ngram-beam-search-decoder'''
def a__ ( self ,**_SCREAMING_SNAKE_CASE ) -> Dict:
UpperCAmelCase_ : int = self.add_kwargs_tokens_map.copy()
kwargs.update(_SCREAMING_SNAKE_CASE )
return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname ,**_SCREAMING_SNAKE_CASE )
def a__ ( self ,**_SCREAMING_SNAKE_CASE ) -> Any:
return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname ,**_SCREAMING_SNAKE_CASE )
def a__ ( self ,**_SCREAMING_SNAKE_CASE ) -> Dict:
return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name ,**_SCREAMING_SNAKE_CASE )
def a__ ( self ) -> int:
shutil.rmtree(self.tmpdirname )
def a__ ( self ) -> int:
UpperCAmelCase_ : Union[str, Any] = self.get_tokenizer()
UpperCAmelCase_ : List[str] = self.get_feature_extractor()
UpperCAmelCase_ : Tuple = self.get_decoder()
UpperCAmelCase_ : Tuple = WavaVecaProcessorWithLM(tokenizer=_SCREAMING_SNAKE_CASE ,feature_extractor=_SCREAMING_SNAKE_CASE ,decoder=_SCREAMING_SNAKE_CASE )
processor.save_pretrained(self.tmpdirname )
UpperCAmelCase_ : List[str] = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname )
# tokenizer
self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer.get_vocab() )
self.assertIsInstance(processor.tokenizer ,_SCREAMING_SNAKE_CASE )
# feature extractor
self.assertEqual(processor.feature_extractor.to_json_string() ,feature_extractor.to_json_string() )
self.assertIsInstance(processor.feature_extractor ,_SCREAMING_SNAKE_CASE )
# decoder
self.assertEqual(processor.decoder._alphabet.labels ,decoder._alphabet.labels )
self.assertEqual(
processor.decoder.model_container[decoder._model_key]._unigram_set ,decoder.model_container[decoder._model_key]._unigram_set ,)
self.assertIsInstance(processor.decoder ,_SCREAMING_SNAKE_CASE )
def a__ ( self ) -> Tuple:
UpperCAmelCase_ : Tuple = WavaVecaProcessorWithLM(
tokenizer=self.get_tokenizer() ,feature_extractor=self.get_feature_extractor() ,decoder=self.get_decoder() )
processor.save_pretrained(self.tmpdirname )
# make sure that error is thrown when decoder alphabet doesn't match
UpperCAmelCase_ : Optional[int] = WavaVecaProcessorWithLM.from_pretrained(
self.tmpdirname ,alpha=5.0 ,beta=3.0 ,score_boundary=-7.0 ,unk_score_offset=3 )
# decoder
self.assertEqual(processor.language_model.alpha ,5.0 )
self.assertEqual(processor.language_model.beta ,3.0 )
self.assertEqual(processor.language_model.score_boundary ,-7.0 )
self.assertEqual(processor.language_model.unk_score_offset ,3 )
def a__ ( self ) -> Dict:
UpperCAmelCase_ : str = self.get_tokenizer()
# add token to trigger raise
tokenizer.add_tokens(['''xx'''] )
with self.assertRaisesRegex(_SCREAMING_SNAKE_CASE ,'''include''' ):
WavaVecaProcessorWithLM(
tokenizer=_SCREAMING_SNAKE_CASE ,feature_extractor=self.get_feature_extractor() ,decoder=self.get_decoder() )
def a__ ( self ) -> Optional[int]:
UpperCAmelCase_ : Any = self.get_feature_extractor()
UpperCAmelCase_ : Union[str, Any] = self.get_tokenizer()
UpperCAmelCase_ : List[str] = self.get_decoder()
UpperCAmelCase_ : Optional[Any] = WavaVecaProcessorWithLM(tokenizer=_SCREAMING_SNAKE_CASE ,feature_extractor=_SCREAMING_SNAKE_CASE ,decoder=_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Dict = floats_list((3, 1_000) )
UpperCAmelCase_ : Any = feature_extractor(_SCREAMING_SNAKE_CASE ,return_tensors='''np''' )
UpperCAmelCase_ : Any = processor(_SCREAMING_SNAKE_CASE ,return_tensors='''np''' )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1e-2 )
def a__ ( self ) -> List[str]:
UpperCAmelCase_ : Union[str, Any] = self.get_feature_extractor()
UpperCAmelCase_ : List[Any] = self.get_tokenizer()
UpperCAmelCase_ : Optional[Any] = self.get_decoder()
UpperCAmelCase_ : str = WavaVecaProcessorWithLM(tokenizer=_SCREAMING_SNAKE_CASE ,feature_extractor=_SCREAMING_SNAKE_CASE ,decoder=_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Any = '''This is a test string'''
UpperCAmelCase_ : Optional[int] = processor(text=_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Any = tokenizer(_SCREAMING_SNAKE_CASE )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] ,encoded_processor[key] )
def a__ ( self ,_SCREAMING_SNAKE_CASE=(2, 10, 16) ,_SCREAMING_SNAKE_CASE=77 ) -> int:
np.random.seed(_SCREAMING_SNAKE_CASE )
return np.random.rand(*_SCREAMING_SNAKE_CASE )
def a__ ( self ) -> Dict:
UpperCAmelCase_ : int = self.get_feature_extractor()
UpperCAmelCase_ : Any = self.get_tokenizer()
UpperCAmelCase_ : Optional[Any] = self.get_decoder()
UpperCAmelCase_ : List[Any] = WavaVecaProcessorWithLM(tokenizer=_SCREAMING_SNAKE_CASE ,feature_extractor=_SCREAMING_SNAKE_CASE ,decoder=_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : str = self._get_dummy_logits(shape=(10, 16) ,seed=13 )
UpperCAmelCase_ : Optional[Any] = processor.decode(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : int = decoder.decode_beams(_SCREAMING_SNAKE_CASE )[0]
self.assertEqual(decoded_decoder[0] ,decoded_processor.text )
self.assertEqual('''</s> <s> </s>''' ,decoded_processor.text )
self.assertEqual(decoded_decoder[-2] ,decoded_processor.logit_score )
self.assertEqual(decoded_decoder[-1] ,decoded_processor.lm_score )
@parameterized.expand([[None], ['''fork'''], ['''spawn''']] )
def a__ ( self ,_SCREAMING_SNAKE_CASE ) -> Optional[Any]:
UpperCAmelCase_ : Dict = self.get_feature_extractor()
UpperCAmelCase_ : Optional[Any] = self.get_tokenizer()
UpperCAmelCase_ : Tuple = self.get_decoder()
UpperCAmelCase_ : List[Any] = WavaVecaProcessorWithLM(tokenizer=_SCREAMING_SNAKE_CASE ,feature_extractor=_SCREAMING_SNAKE_CASE ,decoder=_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Optional[int] = self._get_dummy_logits()
# note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM.
# otherwise, the LM won't be available to the pool's sub-processes.
# manual logic used to allow parameterized test for both pool=None and pool=Pool(...)
if pool_context is None:
UpperCAmelCase_ : Dict = processor.batch_decode(_SCREAMING_SNAKE_CASE )
else:
with get_context(_SCREAMING_SNAKE_CASE ).Pool() as pool:
UpperCAmelCase_ : str = processor.batch_decode(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : List[Any] = list(_SCREAMING_SNAKE_CASE )
with get_context('''fork''' ).Pool() as p:
UpperCAmelCase_ : List[str] = decoder.decode_beams_batch(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_ : str = [], [], []
for beams in decoded_beams:
texts_decoder.append(beams[0][0] )
logit_scores_decoder.append(beams[0][-2] )
lm_scores_decoder.append(beams[0][-1] )
self.assertListEqual(_SCREAMING_SNAKE_CASE ,decoded_processor.text )
self.assertListEqual(['''<s> <s> </s>''', '''<s> <s> <s>'''] ,decoded_processor.text )
self.assertListEqual(_SCREAMING_SNAKE_CASE ,decoded_processor.logit_score )
self.assertListEqual(_SCREAMING_SNAKE_CASE ,decoded_processor.lm_score )
def a__ ( self ) -> Optional[Any]:
UpperCAmelCase_ : List[Any] = self.get_feature_extractor()
UpperCAmelCase_ : List[Any] = self.get_tokenizer()
UpperCAmelCase_ : Tuple = self.get_decoder()
UpperCAmelCase_ : Any = WavaVecaProcessorWithLM(tokenizer=_SCREAMING_SNAKE_CASE ,feature_extractor=_SCREAMING_SNAKE_CASE ,decoder=_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Optional[Any] = self._get_dummy_logits()
UpperCAmelCase_ : List[Any] = 15
UpperCAmelCase_ : Optional[Any] = -20.0
UpperCAmelCase_ : Tuple = -4.0
UpperCAmelCase_ : Union[str, Any] = processor.batch_decode(
_SCREAMING_SNAKE_CASE ,beam_width=_SCREAMING_SNAKE_CASE ,beam_prune_logp=_SCREAMING_SNAKE_CASE ,token_min_logp=_SCREAMING_SNAKE_CASE ,)
UpperCAmelCase_ : List[Any] = decoded_processor_out.text
UpperCAmelCase_ : int = list(_SCREAMING_SNAKE_CASE )
with get_context('''fork''' ).Pool() as pool:
UpperCAmelCase_ : List[str] = decoder.decode_beams_batch(
_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,beam_width=_SCREAMING_SNAKE_CASE ,beam_prune_logp=_SCREAMING_SNAKE_CASE ,token_min_logp=_SCREAMING_SNAKE_CASE ,)
UpperCAmelCase_ : str = [d[0][0] for d in decoded_decoder_out]
UpperCAmelCase_ : Union[str, Any] = [d[0][2] for d in decoded_decoder_out]
UpperCAmelCase_ : Dict = [d[0][3] for d in decoded_decoder_out]
self.assertListEqual(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
self.assertListEqual(['''</s> <s> <s>''', '''<s> <s> <s>'''] ,_SCREAMING_SNAKE_CASE )
self.assertTrue(np.array_equal(_SCREAMING_SNAKE_CASE ,decoded_processor_out.logit_score ) )
self.assertTrue(np.allclose([-20.0_54, -18.4_47] ,_SCREAMING_SNAKE_CASE ,atol=1e-3 ) )
self.assertTrue(np.array_equal(_SCREAMING_SNAKE_CASE ,decoded_processor_out.lm_score ) )
self.assertTrue(np.allclose([-15.5_54, -13.94_74] ,_SCREAMING_SNAKE_CASE ,atol=1e-3 ) )
def a__ ( self ) -> List[str]:
UpperCAmelCase_ : List[Any] = self.get_feature_extractor()
UpperCAmelCase_ : List[Any] = self.get_tokenizer()
UpperCAmelCase_ : Optional[int] = self.get_decoder()
UpperCAmelCase_ : Optional[Any] = WavaVecaProcessorWithLM(tokenizer=_SCREAMING_SNAKE_CASE ,feature_extractor=_SCREAMING_SNAKE_CASE ,decoder=_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Optional[Any] = self._get_dummy_logits()
UpperCAmelCase_ : List[Any] = 2.0
UpperCAmelCase_ : Optional[int] = 5.0
UpperCAmelCase_ : List[Any] = -20.0
UpperCAmelCase_ : List[str] = True
UpperCAmelCase_ : str = processor.batch_decode(
_SCREAMING_SNAKE_CASE ,alpha=_SCREAMING_SNAKE_CASE ,beta=_SCREAMING_SNAKE_CASE ,unk_score_offset=_SCREAMING_SNAKE_CASE ,lm_score_boundary=_SCREAMING_SNAKE_CASE ,)
UpperCAmelCase_ : Tuple = decoded_processor_out.text
UpperCAmelCase_ : Optional[Any] = list(_SCREAMING_SNAKE_CASE )
decoder.reset_params(
alpha=_SCREAMING_SNAKE_CASE ,beta=_SCREAMING_SNAKE_CASE ,unk_score_offset=_SCREAMING_SNAKE_CASE ,lm_score_boundary=_SCREAMING_SNAKE_CASE ,)
with get_context('''fork''' ).Pool() as pool:
UpperCAmelCase_ : Optional[int] = decoder.decode_beams_batch(
_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,)
UpperCAmelCase_ : List[str] = [d[0][0] for d in decoded_decoder_out]
self.assertListEqual(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
self.assertListEqual(['''<s> </s> <s> </s> </s>''', '''</s> </s> <s> </s> </s>'''] ,_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Any = processor.decoder.model_container[processor.decoder._model_key]
self.assertEqual(lm_model.alpha ,2.0 )
self.assertEqual(lm_model.beta ,5.0 )
self.assertEqual(lm_model.unk_score_offset ,-20.0 )
self.assertEqual(lm_model.score_boundary ,_SCREAMING_SNAKE_CASE )
def a__ ( self ) -> List[str]:
UpperCAmelCase_ : Dict = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' )
UpperCAmelCase_ : Tuple = processor.decoder.model_container[processor.decoder._model_key]
UpperCAmelCase_ : Dict = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute()
UpperCAmelCase_ : Any = os.listdir(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : List[Any] = ['''alphabet.json''', '''language_model''']
downloaded_decoder_files.sort()
expected_decoder_files.sort()
# test that only decoder relevant files from
# https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main
# are downloaded and none of the rest (e.g. README.md, ...)
self.assertListEqual(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
def a__ ( self ) -> List[Any]:
UpperCAmelCase_ : int = snapshot_download('''hf-internal-testing/processor_with_lm''' )
UpperCAmelCase_ : List[str] = WavaVecaProcessorWithLM.from_pretrained(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Optional[Any] = processor.decoder.model_container[processor.decoder._model_key]
UpperCAmelCase_ : List[str] = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute()
UpperCAmelCase_ : List[Any] = os.listdir(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : str = os.listdir(_SCREAMING_SNAKE_CASE )
local_decoder_files.sort()
expected_decoder_files.sort()
# test that both decoder form hub and local files in cache are the same
self.assertListEqual(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
def a__ ( self ) -> Optional[Any]:
UpperCAmelCase_ : str = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' )
UpperCAmelCase_ : Optional[Any] = AutoProcessor.from_pretrained('''hf-internal-testing/processor_with_lm''' )
UpperCAmelCase_ : Tuple = floats_list((3, 1_000) )
UpperCAmelCase_ : Optional[Any] = processor_wavaveca(_SCREAMING_SNAKE_CASE ,return_tensors='''np''' )
UpperCAmelCase_ : List[str] = processor_auto(_SCREAMING_SNAKE_CASE ,return_tensors='''np''' )
for key in input_wavaveca.keys():
self.assertAlmostEqual(input_wavaveca[key].sum() ,input_auto[key].sum() ,delta=1e-2 )
UpperCAmelCase_ : Any = self._get_dummy_logits()
UpperCAmelCase_ : int = processor_wavaveca.batch_decode(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Tuple = processor_auto.batch_decode(_SCREAMING_SNAKE_CASE )
self.assertListEqual(decoded_wavaveca.text ,decoded_auto.text )
def a__ ( self ) -> List[str]:
UpperCAmelCase_ : Union[str, Any] = self.get_feature_extractor()
UpperCAmelCase_ : Union[str, Any] = self.get_tokenizer()
UpperCAmelCase_ : Any = self.get_decoder()
UpperCAmelCase_ : Optional[Any] = WavaVecaProcessorWithLM(tokenizer=_SCREAMING_SNAKE_CASE ,feature_extractor=_SCREAMING_SNAKE_CASE ,decoder=_SCREAMING_SNAKE_CASE )
self.assertListEqual(
processor.model_input_names ,feature_extractor.model_input_names ,msg='''`processor` and `feature_extractor` model input names do not match''' ,)
@staticmethod
def a__ ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Tuple:
UpperCAmelCase_ : int = [d[key] for d in offsets]
return retrieved_list
def a__ ( self ) -> Optional[int]:
UpperCAmelCase_ : List[str] = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' )
UpperCAmelCase_ : Union[str, Any] = self._get_dummy_logits()[0]
UpperCAmelCase_ : Tuple = processor.decode(_SCREAMING_SNAKE_CASE ,output_word_offsets=_SCREAMING_SNAKE_CASE )
# check Wav2Vec2CTCTokenizerOutput keys for word
self.assertEqual(len(outputs.keys() ) ,4 )
self.assertTrue('''text''' in outputs )
self.assertTrue('''word_offsets''' in outputs )
self.assertTrue(isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) )
self.assertEqual(''' '''.join(self.get_from_offsets(outputs['''word_offsets'''] ,'''word''' ) ) ,outputs.text )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] ,'''word''' ) ,['''<s>''', '''<s>''', '''</s>'''] )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] ,'''start_offset''' ) ,[0, 2, 4] )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] ,'''end_offset''' ) ,[1, 3, 5] )
def a__ ( self ) -> Optional[int]:
UpperCAmelCase_ : Optional[Any] = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' )
UpperCAmelCase_ : int = self._get_dummy_logits()
UpperCAmelCase_ : List[str] = processor.batch_decode(_SCREAMING_SNAKE_CASE ,output_word_offsets=_SCREAMING_SNAKE_CASE )
# check Wav2Vec2CTCTokenizerOutput keys for word
self.assertEqual(len(outputs.keys() ) ,4 )
self.assertTrue('''text''' in outputs )
self.assertTrue('''word_offsets''' in outputs )
self.assertTrue(isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) )
self.assertListEqual(
[''' '''.join(self.get_from_offsets(_SCREAMING_SNAKE_CASE ,'''word''' ) ) for o in outputs['''word_offsets''']] ,outputs.text )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] ,'''word''' ) ,['''<s>''', '''<s>''', '''</s>'''] )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] ,'''start_offset''' ) ,[0, 2, 4] )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] ,'''end_offset''' ) ,[1, 3, 5] )
@slow
@require_torch
@require_torchaudio
def a__ ( self ) -> Union[str, Any]:
import torch
UpperCAmelCase_ : List[str] = load_dataset('''common_voice''' ,'''en''' ,split='''train''' ,streaming=_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Dict = ds.cast_column('''audio''' ,datasets.Audio(sampling_rate=16_000 ) )
UpperCAmelCase_ : Tuple = iter(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Union[str, Any] = next(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Any = AutoProcessor.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' )
UpperCAmelCase_ : Dict = WavaVecaForCTC.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' )
# compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train
UpperCAmelCase_ : List[str] = processor(sample['''audio''']['''array'''] ,return_tensors='''pt''' ).input_values
with torch.no_grad():
UpperCAmelCase_ : List[str] = model(_SCREAMING_SNAKE_CASE ).logits.cpu().numpy()
UpperCAmelCase_ : str = processor.decode(logits[0] ,output_word_offsets=_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Tuple = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate
UpperCAmelCase_ : Any = [
{
'''start_time''': d['''start_offset'''] * time_offset,
'''end_time''': d['''end_offset'''] * time_offset,
'''word''': d['''word'''],
}
for d in output['''word_offsets''']
]
UpperCAmelCase_ : Any = '''WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL'''
# output words
self.assertEqual(''' '''.join(self.get_from_offsets(_SCREAMING_SNAKE_CASE ,'''word''' ) ) ,_SCREAMING_SNAKE_CASE )
self.assertEqual(''' '''.join(self.get_from_offsets(_SCREAMING_SNAKE_CASE ,'''word''' ) ) ,output.text )
# output times
UpperCAmelCase_ : List[Any] = torch.tensor(self.get_from_offsets(_SCREAMING_SNAKE_CASE ,'''start_time''' ) )
UpperCAmelCase_ : str = torch.tensor(self.get_from_offsets(_SCREAMING_SNAKE_CASE ,'''end_time''' ) )
# fmt: off
UpperCAmelCase_ : str = torch.tensor([1.41_99, 1.65_99, 2.25_99, 3.0, 3.24, 3.59_99, 3.79_99, 4.09_99, 4.26, 4.94, 5.28, 5.65_99, 5.78, 5.94, 6.32, 6.53_99, 6.65_99] )
UpperCAmelCase_ : Optional[int] = torch.tensor([1.53_99, 1.89_99, 2.9, 3.16, 3.53_99, 3.72, 4.01_99, 4.17_99, 4.76, 5.15_99, 5.55_99, 5.69_99, 5.86, 6.19_99, 6.38, 6.61_99, 6.94] )
# fmt: on
self.assertTrue(torch.allclose(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,atol=0.01 ) )
self.assertTrue(torch.allclose(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,atol=0.01 ) )
| 300 | 1 |
import tempfile
import unittest
import numpy as np
from diffusers import (
DDIMScheduler,
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
OnnxStableDiffusionPipeline,
PNDMScheduler,
)
from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu
from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin
if is_onnx_available():
import onnxruntime as ort
class a__ ( snake_case , unittest.TestCase ):
"""simple docstring"""
__lowerCamelCase = 'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'
def UpperCamelCase ( self , lowercase=0 ) -> Optional[Any]:
'''simple docstring'''
A__ = np.random.RandomState(lowercase )
A__ = {
"prompt": "A painting of a squirrel eating a burger",
"generator": generator,
"num_inference_steps": 2,
"guidance_scale": 7.5,
"output_type": "numpy",
}
return inputs
def UpperCamelCase ( self ) -> Optional[int]:
'''simple docstring'''
A__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
pipe.set_progress_bar_config(disable=lowercase )
A__ = self.get_dummy_inputs()
A__ = pipe(**lowercase ).images
A__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
A__ = np.array([0.6_5072, 0.5_8492, 0.4_8219, 0.5_5521, 0.5_3180, 0.5_5939, 0.5_0697, 0.3_9800, 0.4_6455] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def UpperCamelCase ( self ) -> List[Any]:
'''simple docstring'''
A__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
A__ = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=lowercase )
pipe.set_progress_bar_config(disable=lowercase )
A__ = self.get_dummy_inputs()
A__ = pipe(**lowercase ).images
A__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
A__ = np.array([0.6_5863, 0.5_9425, 0.4_9326, 0.5_6313, 0.5_3875, 0.5_6627, 0.5_1065, 0.3_9777, 0.4_6330] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def UpperCamelCase ( self ) -> Any:
'''simple docstring'''
A__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
A__ = LMSDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=lowercase )
A__ = self.get_dummy_inputs()
A__ = pipe(**lowercase ).images
A__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
A__ = np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def UpperCamelCase ( self ) -> int:
'''simple docstring'''
A__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
A__ = EulerDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=lowercase )
A__ = self.get_dummy_inputs()
A__ = pipe(**lowercase ).images
A__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
A__ = np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def UpperCamelCase ( self ) -> Dict:
'''simple docstring'''
A__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
A__ = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=lowercase )
A__ = self.get_dummy_inputs()
A__ = pipe(**lowercase ).images
A__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
A__ = np.array([0.5_3817, 0.6_0812, 0.4_7384, 0.4_9530, 0.5_1894, 0.4_9814, 0.4_7984, 0.3_8958, 0.4_4271] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def UpperCamelCase ( self ) -> str:
'''simple docstring'''
A__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
A__ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=lowercase )
A__ = self.get_dummy_inputs()
A__ = pipe(**lowercase ).images
A__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
A__ = np.array([0.5_3895, 0.6_0808, 0.4_7933, 0.4_9608, 0.5_1886, 0.4_9950, 0.4_8053, 0.3_8957, 0.4_4200] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def UpperCamelCase ( self ) -> Dict:
'''simple docstring'''
A__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
pipe.set_progress_bar_config(disable=lowercase )
A__ = self.get_dummy_inputs()
A__ = 3 * [inputs["prompt"]]
# forward
A__ = pipe(**lowercase )
A__ = output.images[0, -3:, -3:, -1]
A__ = self.get_dummy_inputs()
A__ = 3 * [inputs.pop("prompt" )]
A__ = pipe.tokenizer(
lowercase , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=lowercase , return_tensors="np" , )
A__ = text_inputs["input_ids"]
A__ = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0]
A__ = prompt_embeds
# forward
A__ = pipe(**lowercase )
A__ = output.images[0, -3:, -3:, -1]
assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4
def UpperCamelCase ( self ) -> List[Any]:
'''simple docstring'''
A__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
pipe.set_progress_bar_config(disable=lowercase )
A__ = self.get_dummy_inputs()
A__ = 3 * ["this is a negative prompt"]
A__ = negative_prompt
A__ = 3 * [inputs["prompt"]]
# forward
A__ = pipe(**lowercase )
A__ = output.images[0, -3:, -3:, -1]
A__ = self.get_dummy_inputs()
A__ = 3 * [inputs.pop("prompt" )]
A__ = []
for p in [prompt, negative_prompt]:
A__ = pipe.tokenizer(
lowercase , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=lowercase , return_tensors="np" , )
A__ = text_inputs["input_ids"]
embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] )
A__ , A__ = embeds
# forward
A__ = pipe(**lowercase )
A__ = output.images[0, -3:, -3:, -1]
assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4
@nightly
@require_onnxruntime
@require_torch_gpu
class a__ ( unittest.TestCase ):
"""simple docstring"""
@property
def UpperCamelCase ( self ) -> int:
'''simple docstring'''
return (
"CUDAExecutionProvider",
{
"gpu_mem_limit": "15000000000", # 15GB
"arena_extend_strategy": "kSameAsRequested",
},
)
@property
def UpperCamelCase ( self ) -> Optional[Any]:
'''simple docstring'''
A__ = ort.SessionOptions()
A__ = False
return options
def UpperCamelCase ( self ) -> int:
'''simple docstring'''
A__ = OnnxStableDiffusionPipeline.from_pretrained(
"CompVis/stable-diffusion-v1-4" , revision="onnx" , safety_checker=lowercase , feature_extractor=lowercase , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=lowercase )
A__ = "A painting of a squirrel eating a burger"
np.random.seed(0 )
A__ = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=10 , output_type="np" )
A__ = output.images
A__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
A__ = np.array([0.0452, 0.0390, 0.0087, 0.0350, 0.0617, 0.0364, 0.0544, 0.0523, 0.0720] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
def UpperCamelCase ( self ) -> str:
'''simple docstring'''
A__ = DDIMScheduler.from_pretrained(
"runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" )
A__ = OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=lowercase , safety_checker=lowercase , feature_extractor=lowercase , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=lowercase )
A__ = "open neural network exchange"
A__ = np.random.RandomState(0 )
A__ = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=lowercase , output_type="np" )
A__ = output.images
A__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
A__ = np.array([0.2867, 0.1974, 0.1481, 0.7294, 0.7251, 0.6667, 0.4194, 0.5642, 0.6486] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
def UpperCamelCase ( self ) -> Union[str, Any]:
'''simple docstring'''
A__ = LMSDiscreteScheduler.from_pretrained(
"runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" )
A__ = OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=lowercase , safety_checker=lowercase , feature_extractor=lowercase , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=lowercase )
A__ = "open neural network exchange"
A__ = np.random.RandomState(0 )
A__ = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=lowercase , output_type="np" )
A__ = output.images
A__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
A__ = np.array([0.2306, 0.1959, 0.1593, 0.6549, 0.6394, 0.5408, 0.5065, 0.6010, 0.6161] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
def UpperCamelCase ( self ) -> int:
'''simple docstring'''
A__ = 0
def test_callback_fn(lowercase , lowercase , lowercase ) -> None:
A__ = True
nonlocal number_of_steps
number_of_steps += 1
if step == 0:
assert latents.shape == (1, 4, 64, 64)
A__ = latents[0, -3:, -3:, -1]
A__ = np.array(
[-0.6772, -0.3835, -1.2456, 0.1905, -1.0974, 0.6967, -1.9353, 0.0178, 1.0167] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3
elif step == 5:
assert latents.shape == (1, 4, 64, 64)
A__ = latents[0, -3:, -3:, -1]
A__ = np.array(
[-0.3351, 0.2241, -0.1837, -0.2325, -0.6577, 0.3393, -0.0241, 0.5899, 1.3875] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3
A__ = False
A__ = OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=lowercase , feature_extractor=lowercase , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=lowercase )
A__ = "Andromeda galaxy in a bottle"
A__ = np.random.RandomState(0 )
pipe(
prompt=lowercase , num_inference_steps=5 , guidance_scale=7.5 , generator=lowercase , callback=lowercase , callback_steps=1 , )
assert test_callback_fn.has_been_called
assert number_of_steps == 6
def UpperCamelCase ( self ) -> Any:
'''simple docstring'''
A__ = OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=lowercase , feature_extractor=lowercase , provider=self.gpu_provider , sess_options=self.gpu_options , )
assert isinstance(lowercase , lowercase )
assert pipe.safety_checker is None
A__ = pipe("example prompt" , num_inference_steps=2 ).images[0]
assert image is not None
# check that there's no error when saving a pipeline with one of the models being None
with tempfile.TemporaryDirectory() as tmpdirname:
pipe.save_pretrained(lowercase )
A__ = OnnxStableDiffusionPipeline.from_pretrained(lowercase )
# sanity check that the pipeline still works
assert pipe.safety_checker is None
A__ = pipe("example prompt" , num_inference_steps=2 ).images[0]
assert image is not None
| 514 |
from __future__ import annotations
import copy
import inspect
import unittest
import numpy as np
from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
LayoutLMvaConfig,
TFLayoutLMvaForQuestionAnswering,
TFLayoutLMvaForSequenceClassification,
TFLayoutLMvaForTokenClassification,
TFLayoutLMvaModel,
)
if is_vision_available():
from PIL import Image
from transformers import LayoutLMvaImageProcessor
class a__ :
"""simple docstring"""
def __init__( self , lowercase , lowercase=2 , lowercase=3 , lowercase=4 , lowercase=2 , lowercase=7 , lowercase=True , lowercase=True , lowercase=True , lowercase=True , lowercase=99 , lowercase=36 , lowercase=2 , lowercase=4 , lowercase=37 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=512 , lowercase=16 , lowercase=2 , lowercase=0.02 , lowercase=6 , lowercase=6 , lowercase=3 , lowercase=4 , lowercase=None , lowercase=1000 , ) -> Any:
'''simple docstring'''
A__ = parent
A__ = batch_size
A__ = num_channels
A__ = image_size
A__ = patch_size
A__ = is_training
A__ = use_input_mask
A__ = use_token_type_ids
A__ = use_labels
A__ = vocab_size
A__ = hidden_size
A__ = num_hidden_layers
A__ = num_attention_heads
A__ = intermediate_size
A__ = hidden_act
A__ = hidden_dropout_prob
A__ = attention_probs_dropout_prob
A__ = max_position_embeddings
A__ = type_vocab_size
A__ = type_sequence_label_size
A__ = initializer_range
A__ = coordinate_size
A__ = shape_size
A__ = num_labels
A__ = num_choices
A__ = scope
A__ = range_bbox
# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
A__ = text_seq_length
A__ = (image_size // patch_size) ** 2 + 1
A__ = self.text_seq_length + self.image_seq_length
def UpperCamelCase ( self ) -> Optional[int]:
'''simple docstring'''
A__ = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size )
A__ = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox )
A__ = bbox.numpy()
# Ensure that bbox is legal
for i in range(bbox.shape[0] ):
for j in range(bbox.shape[1] ):
if bbox[i, j, 3] < bbox[i, j, 1]:
A__ = bbox[i, j, 3]
A__ = bbox[i, j, 1]
A__ = tmp_coordinate
if bbox[i, j, 2] < bbox[i, j, 0]:
A__ = bbox[i, j, 2]
A__ = bbox[i, j, 0]
A__ = tmp_coordinate
A__ = tf.constant(lowercase )
A__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
A__ = None
if self.use_input_mask:
A__ = random_attention_mask([self.batch_size, self.text_seq_length] )
A__ = None
if self.use_token_type_ids:
A__ = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size )
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.text_seq_length] , self.num_labels )
A__ = LayoutLMvaConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , )
return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels
def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[Any]:
'''simple docstring'''
A__ = TFLayoutLMvaModel(config=lowercase )
# text + image
A__ = model(lowercase , pixel_values=lowercase , training=lowercase )
A__ = model(
lowercase , bbox=lowercase , pixel_values=lowercase , attention_mask=lowercase , token_type_ids=lowercase , training=lowercase , )
A__ = model(lowercase , bbox=lowercase , pixel_values=lowercase , training=lowercase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
# text only
A__ = model(lowercase , training=lowercase )
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) )
# image only
A__ = model({"pixel_values": pixel_values} , training=lowercase )
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) )
def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[int]:
'''simple docstring'''
A__ = self.num_labels
A__ = TFLayoutLMvaForSequenceClassification(config=lowercase )
A__ = model(
lowercase , bbox=lowercase , pixel_values=lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase , training=lowercase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Union[str, Any]:
'''simple docstring'''
A__ = self.num_labels
A__ = TFLayoutLMvaForTokenClassification(config=lowercase )
A__ = model(
lowercase , bbox=lowercase , pixel_values=lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase , training=lowercase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) )
def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> str:
'''simple docstring'''
A__ = 2
A__ = TFLayoutLMvaForQuestionAnswering(config=lowercase )
A__ = model(
lowercase , bbox=lowercase , pixel_values=lowercase , attention_mask=lowercase , token_type_ids=lowercase , start_positions=lowercase , end_positions=lowercase , training=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 UpperCamelCase ( self ) -> str:
'''simple docstring'''
A__ = self.prepare_config_and_inputs()
((A__) , (A__) , (A__) , (A__) , (A__) , (A__) , (A__) , (A__)) = config_and_inputs
A__ = {
"input_ids": input_ids,
"bbox": bbox,
"pixel_values": pixel_values,
"token_type_ids": token_type_ids,
"attention_mask": input_mask,
}
return config, inputs_dict
@require_tf
class a__ ( snake_case , snake_case , unittest.TestCase ):
"""simple docstring"""
__lowerCamelCase = (
(
TFLayoutLMvaModel,
TFLayoutLMvaForQuestionAnswering,
TFLayoutLMvaForSequenceClassification,
TFLayoutLMvaForTokenClassification,
)
if is_tf_available()
else ()
)
__lowerCamelCase = (
{'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
if is_tf_available()
else {}
)
__lowerCamelCase = False
__lowerCamelCase = False
__lowerCamelCase = False
def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase ) -> str:
'''simple docstring'''
return True
def UpperCamelCase ( self , lowercase , lowercase , lowercase=False ) -> dict:
'''simple docstring'''
A__ = copy.deepcopy(lowercase )
if model_class in get_values(lowercase ):
A__ = {
k: tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) )
if isinstance(lowercase , tf.Tensor ) and v.ndim > 0
else v
for k, v in inputs_dict.items()
}
if return_labels:
if model_class in get_values(lowercase ):
A__ = tf.ones(self.model_tester.batch_size , dtype=tf.intaa )
elif model_class in get_values(lowercase ):
A__ = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa )
A__ = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa )
elif model_class in get_values(lowercase ):
A__ = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa )
elif model_class in get_values(lowercase ):
A__ = tf.zeros(
(self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa )
return inputs_dict
def UpperCamelCase ( self ) -> Tuple:
'''simple docstring'''
A__ = TFLayoutLMvaModelTester(self )
A__ = ConfigTester(self , config_class=lowercase , hidden_size=37 )
def UpperCamelCase ( self ) -> List[str]:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCamelCase ( self ) -> List[str]:
'''simple docstring'''
A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
A__ = model_class(lowercase )
if getattr(lowercase , "hf_compute_loss" , lowercase ):
# The number of elements in the loss should be the same as the number of elements in the label
A__ = self._prepare_for_class(inputs_dict.copy() , lowercase , return_labels=lowercase )
A__ = prepared_for_class[
sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=lowercase )[0]
]
A__ = added_label.shape.as_list()[:1]
# Test that model correctly compute the loss with kwargs
A__ = self._prepare_for_class(inputs_dict.copy() , lowercase , return_labels=lowercase )
A__ = prepared_for_class.pop("input_ids" )
A__ = model(lowercase , **lowercase )[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] )
# Test that model correctly compute the loss when we mask some positions
A__ = self._prepare_for_class(inputs_dict.copy() , lowercase , return_labels=lowercase )
A__ = prepared_for_class.pop("input_ids" )
if "labels" in prepared_for_class:
A__ = prepared_for_class["labels"].numpy()
if len(labels.shape ) > 1 and labels.shape[1] != 1:
A__ = -100
A__ = tf.convert_to_tensor(lowercase )
A__ = model(lowercase , **lowercase )[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] )
self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) )
# Test that model correctly compute the loss with a dict
A__ = self._prepare_for_class(inputs_dict.copy() , lowercase , return_labels=lowercase )
A__ = model(lowercase )[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] )
# Test that model correctly compute the loss with a tuple
A__ = self._prepare_for_class(inputs_dict.copy() , lowercase , return_labels=lowercase )
# Get keys that were added with the _prepare_for_class function
A__ = prepared_for_class.keys() - inputs_dict.keys()
A__ = inspect.signature(model.call ).parameters
A__ = list(signature.keys() )
# Create a dictionary holding the location of the tensors in the tuple
A__ = {0: "input_ids"}
for label_key in label_keys:
A__ = signature_names.index(lowercase )
A__ = label_key
A__ = sorted(tuple_index_mapping.items() )
# Initialize a list with their default values, update the values and convert to a tuple
A__ = []
for name in signature_names:
if name != "kwargs":
list_input.append(signature[name].default )
for index, value in sorted_tuple_index_mapping:
A__ = prepared_for_class[value]
A__ = tuple(lowercase )
# Send to model
A__ = model(tuple_input[:-1] )[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] )
def UpperCamelCase ( self ) -> List[str]:
'''simple docstring'''
(
(
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) ,
) = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase )
def UpperCamelCase ( self ) -> int:
'''simple docstring'''
(
(
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) ,
) = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
A__ = type
self.model_tester.create_and_check_model(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase )
def UpperCamelCase ( self ) -> int:
'''simple docstring'''
(
(
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) ,
) = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(
lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase )
def UpperCamelCase ( self ) -> Optional[Any]:
'''simple docstring'''
(
(
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) ,
) = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(
lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase )
def UpperCamelCase ( self ) -> Optional[int]:
'''simple docstring'''
(
(
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) , (
A__
) ,
) = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(
lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase )
@slow
def UpperCamelCase ( self ) -> str:
'''simple docstring'''
for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
A__ = TFLayoutLMvaModel.from_pretrained(lowercase )
self.assertIsNotNone(lowercase )
def lowerCAmelCase__ ( ) -> Tuple:
'''simple docstring'''
A__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_tf
class a__ ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def UpperCamelCase ( self ) -> Optional[Any]:
'''simple docstring'''
return LayoutLMvaImageProcessor(apply_ocr=lowercase ) if is_vision_available() else None
@slow
def UpperCamelCase ( self ) -> Tuple:
'''simple docstring'''
A__ = TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" )
A__ = self.default_image_processor
A__ = prepare_img()
A__ = image_processor(images=lowercase , return_tensors="tf" ).pixel_values
A__ = tf.constant([[1, 2]] )
A__ = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 )
# forward pass
A__ = model(input_ids=lowercase , bbox=lowercase , pixel_values=lowercase , training=lowercase )
# verify the logits
A__ = (1, 199, 768)
self.assertEqual(outputs.last_hidden_state.shape , lowercase )
A__ = tf.constant(
[[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] )
self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , lowercase , atol=1e-4 ) )
| 514 | 1 |
"""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 snake_case__ ( __lowercase ):
def __lowerCAmelCase ( self : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase : Tuple = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(lowercase , "hidden_sizes" ) )
self.parent.assertTrue(hasattr(lowercase , "neck_hidden_sizes" ) )
self.parent.assertTrue(hasattr(lowercase , "num_attention_heads" ) )
class snake_case__ :
def __init__( self : List[Any] , lowercase : Optional[int] , lowercase : Tuple=13 , lowercase : Union[str, Any]=32 , lowercase : int=2 , lowercase : Tuple=3 , lowercase : Optional[Any]=6_40 , lowercase : Dict=4 , lowercase : Optional[int]="silu" , lowercase : Dict=3 , lowercase : List[str]=32 , lowercase : Union[str, Any]=0.1 , lowercase : List[str]=0.1 , lowercase : List[str]=0.1 , lowercase : Any=0.0_2 , lowercase : Union[str, Any]=True , lowercase : Dict=True , lowercase : Any=10 , lowercase : List[str]=None , ):
'''simple docstring'''
UpperCAmelCase : int = parent
UpperCAmelCase : int = batch_size
UpperCAmelCase : Any = image_size
UpperCAmelCase : Optional[int] = patch_size
UpperCAmelCase : List[Any] = num_channels
UpperCAmelCase : Optional[Any] = last_hidden_size
UpperCAmelCase : Optional[int] = num_attention_heads
UpperCAmelCase : Any = hidden_act
UpperCAmelCase : Any = conv_kernel_size
UpperCAmelCase : str = output_stride
UpperCAmelCase : Dict = hidden_dropout_prob
UpperCAmelCase : Union[str, Any] = attention_probs_dropout_prob
UpperCAmelCase : List[str] = classifier_dropout_prob
UpperCAmelCase : str = use_labels
UpperCAmelCase : Any = is_training
UpperCAmelCase : Dict = num_labels
UpperCAmelCase : Union[str, Any] = initializer_range
UpperCAmelCase : Dict = scope
def __lowerCAmelCase ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCAmelCase : Optional[int] = None
UpperCAmelCase : Union[str, Any] = None
if self.use_labels:
UpperCAmelCase : int = ids_tensor([self.batch_size] , self.num_labels )
UpperCAmelCase : List[str] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
UpperCAmelCase : List[str] = self.get_config()
return config, pixel_values, labels, pixel_labels
def __lowerCAmelCase ( self : List[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 __lowerCAmelCase ( self : Optional[int] , lowercase : Tuple , lowercase : List[str] , lowercase : Optional[int] , lowercase : List[str] ):
'''simple docstring'''
UpperCAmelCase : List[Any] = MobileViTModel(config=lowercase )
model.to(lowercase )
model.eval()
UpperCAmelCase : List[Any] = model(lowercase )
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 __lowerCAmelCase ( self : Union[str, Any] , lowercase : Tuple , lowercase : Any , lowercase : int , lowercase : Any ):
'''simple docstring'''
UpperCAmelCase : int = self.num_labels
UpperCAmelCase : int = MobileViTForImageClassification(lowercase )
model.to(lowercase )
model.eval()
UpperCAmelCase : Union[str, Any] = model(lowercase , labels=lowercase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __lowerCAmelCase ( self : List[str] , lowercase : Optional[int] , lowercase : Optional[int] , lowercase : int , lowercase : List[str] ):
'''simple docstring'''
UpperCAmelCase : Union[str, Any] = self.num_labels
UpperCAmelCase : Any = MobileViTForSemanticSegmentation(lowercase )
model.to(lowercase )
model.eval()
UpperCAmelCase : str = model(lowercase )
self.parent.assertEqual(
result.logits.shape , (
self.batch_size,
self.num_labels,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
UpperCAmelCase : Tuple = model(lowercase , labels=lowercase )
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 __lowerCAmelCase ( self : str ):
'''simple docstring'''
UpperCAmelCase : List[Any] = self.prepare_config_and_inputs()
UpperCAmelCase : Tuple = config_and_inputs
UpperCAmelCase : Tuple = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class snake_case__ ( __lowercase , __lowercase , unittest.TestCase ):
SCREAMING_SNAKE_CASE__ = (
(MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
if is_torch_available()
else ()
)
SCREAMING_SNAKE_CASE__ = (
{
'''feature-extraction''': MobileViTModel,
'''image-classification''': MobileViTForImageClassification,
'''image-segmentation''': MobileViTForSemanticSegmentation,
}
if is_torch_available()
else {}
)
SCREAMING_SNAKE_CASE__ = False
SCREAMING_SNAKE_CASE__ = False
SCREAMING_SNAKE_CASE__ = False
SCREAMING_SNAKE_CASE__ = False
def __lowerCAmelCase ( self : int ):
'''simple docstring'''
UpperCAmelCase : str = MobileViTModelTester(self )
UpperCAmelCase : int = MobileViTConfigTester(self , config_class=lowercase , has_text_modality=lowercase )
def __lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason="MobileViT does not use inputs_embeds" )
def __lowerCAmelCase ( self : List[str] ):
'''simple docstring'''
pass
@unittest.skip(reason="MobileViT does not support input and output embeddings" )
def __lowerCAmelCase ( self : List[str] ):
'''simple docstring'''
pass
@unittest.skip(reason="MobileViT does not output attentions" )
def __lowerCAmelCase ( self : List[str] ):
'''simple docstring'''
pass
def __lowerCAmelCase ( self : Any ):
'''simple docstring'''
UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase : str = model_class(lowercase )
UpperCAmelCase : Dict = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCAmelCase : Dict = [*signature.parameters.keys()]
UpperCAmelCase : Dict = ["pixel_values"]
self.assertListEqual(arg_names[:1] , lowercase )
@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
def __lowerCAmelCase ( self : Union[str, Any] ):
'''simple docstring'''
pass
def __lowerCAmelCase ( self : int ):
'''simple docstring'''
UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowercase )
def __lowerCAmelCase ( self : int ):
'''simple docstring'''
def check_hidden_states_output(lowercase : List[Any] , lowercase : Optional[Any] , lowercase : Any ):
UpperCAmelCase : str = model_class(lowercase )
model.to(lowercase )
model.eval()
with torch.no_grad():
UpperCAmelCase : Any = model(**self._prepare_for_class(lowercase , lowercase ) )
UpperCAmelCase : Tuple = outputs.hidden_states
UpperCAmelCase : Tuple = 5
self.assertEqual(len(lowercase ) , lowercase )
# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
# with the width and height being successively divided by 2.
UpperCAmelCase : Any = 2
for i in range(len(lowercase ) ):
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 )
UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase : str = True
check_hidden_states_output(lowercase , lowercase , lowercase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
UpperCAmelCase : Any = True
check_hidden_states_output(lowercase , lowercase , lowercase )
def __lowerCAmelCase ( self : Any ):
'''simple docstring'''
UpperCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*lowercase )
def __lowerCAmelCase ( self : Dict ):
'''simple docstring'''
UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*lowercase )
@slow
def __lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCAmelCase : List[str] = MobileViTModel.from_pretrained(lowercase )
self.assertIsNotNone(lowercase )
def lowercase_ ( ):
'''simple docstring'''
UpperCAmelCase : List[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
@require_vision
class snake_case__ ( unittest.TestCase ):
@cached_property
def __lowerCAmelCase ( self : Tuple ):
'''simple docstring'''
return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small" ) if is_vision_available() else None
@slow
def __lowerCAmelCase ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase : List[Any] = MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small" ).to(lowercase )
UpperCAmelCase : Dict = self.default_image_processor
UpperCAmelCase : Optional[Any] = prepare_img()
UpperCAmelCase : Union[str, Any] = image_processor(images=lowercase , return_tensors="pt" ).to(lowercase )
# forward pass
with torch.no_grad():
UpperCAmelCase : str = model(**lowercase )
# verify the logits
UpperCAmelCase : Optional[int] = torch.Size((1, 10_00) )
self.assertEqual(outputs.logits.shape , lowercase )
UpperCAmelCase : List[str] = torch.tensor([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3] ).to(lowercase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase , atol=1E-4 ) )
@slow
def __lowerCAmelCase ( self : str ):
'''simple docstring'''
UpperCAmelCase : Optional[Any] = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
UpperCAmelCase : Optional[int] = model.to(lowercase )
UpperCAmelCase : str = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
UpperCAmelCase : List[Any] = prepare_img()
UpperCAmelCase : Tuple = image_processor(images=lowercase , return_tensors="pt" ).to(lowercase )
# forward pass
with torch.no_grad():
UpperCAmelCase : int = model(**lowercase )
UpperCAmelCase : Any = outputs.logits
# verify the logits
UpperCAmelCase : List[Any] = torch.Size((1, 21, 32, 32) )
self.assertEqual(logits.shape , lowercase )
UpperCAmelCase : Optional[Any] = 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=lowercase , )
self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , lowercase , atol=1E-4 ) )
@slow
def __lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
UpperCAmelCase : int = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
UpperCAmelCase : str = model.to(lowercase )
UpperCAmelCase : str = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
UpperCAmelCase : List[str] = prepare_img()
UpperCAmelCase : List[Any] = image_processor(images=lowercase , return_tensors="pt" ).to(lowercase )
# forward pass
with torch.no_grad():
UpperCAmelCase : List[Any] = model(**lowercase )
UpperCAmelCase : List[str] = outputs.logits.detach().cpu()
UpperCAmelCase : Any = image_processor.post_process_semantic_segmentation(outputs=lowercase , target_sizes=[(50, 60)] )
UpperCAmelCase : Optional[Any] = torch.Size((50, 60) )
self.assertEqual(segmentation[0].shape , lowercase )
UpperCAmelCase : Optional[Any] = image_processor.post_process_semantic_segmentation(outputs=lowercase )
UpperCAmelCase : Union[str, Any] = torch.Size((32, 32) )
self.assertEqual(segmentation[0].shape , lowercase )
| 706 |
"""simple docstring"""
from typing import Any
class snake_case__ :
def __init__( self : Union[str, Any] , lowercase : Any ):
'''simple docstring'''
UpperCAmelCase : Dict = data
UpperCAmelCase : Optional[Any] = None
def __repr__( self : str ):
'''simple docstring'''
return f"""Node({self.data})"""
class snake_case__ :
def __init__( self : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase : Optional[Any] = None
def __iter__( self : Dict ):
'''simple docstring'''
UpperCAmelCase : str = self.head
while node:
yield node.data
UpperCAmelCase : Tuple = node.next
def __len__( self : Tuple ):
'''simple docstring'''
return sum(1 for _ in self )
def __repr__( self : Any ):
'''simple docstring'''
return "->".join([str(lowercase ) for item in self] )
def __getitem__( self : List[str] , lowercase : int ):
'''simple docstring'''
if not 0 <= index < len(self ):
raise ValueError("list index out of range." )
for i, node in enumerate(self ):
if i == index:
return node
return None
def __setitem__( self : str , lowercase : int , lowercase : Any ):
'''simple docstring'''
if not 0 <= index < len(self ):
raise ValueError("list index out of range." )
UpperCAmelCase : List[str] = self.head
for _ in range(lowercase ):
UpperCAmelCase : List[Any] = current.next
UpperCAmelCase : List[str] = data
def __lowerCAmelCase ( self : Optional[Any] , lowercase : Any ):
'''simple docstring'''
self.insert_nth(len(self ) , lowercase )
def __lowerCAmelCase ( self : List[str] , lowercase : Any ):
'''simple docstring'''
self.insert_nth(0 , lowercase )
def __lowerCAmelCase ( self : List[str] , lowercase : int , lowercase : Any ):
'''simple docstring'''
if not 0 <= index <= len(self ):
raise IndexError("list index out of range" )
UpperCAmelCase : List[Any] = Node(lowercase )
if self.head is None:
UpperCAmelCase : Optional[Any] = new_node
elif index == 0:
UpperCAmelCase : Optional[int] = self.head # link new_node to head
UpperCAmelCase : Optional[Any] = new_node
else:
UpperCAmelCase : Optional[int] = self.head
for _ in range(index - 1 ):
UpperCAmelCase : Union[str, Any] = temp.next
UpperCAmelCase : Dict = temp.next
UpperCAmelCase : Any = new_node
def __lowerCAmelCase ( self : Dict ): # print every node data
'''simple docstring'''
print(self )
def __lowerCAmelCase ( self : Optional[Any] ):
'''simple docstring'''
return self.delete_nth(0 )
def __lowerCAmelCase ( self : str ): # delete from tail
'''simple docstring'''
return self.delete_nth(len(self ) - 1 )
def __lowerCAmelCase ( self : Optional[Any] , lowercase : int = 0 ):
'''simple docstring'''
if not 0 <= index <= len(self ) - 1: # test if index is valid
raise IndexError("List index out of range." )
UpperCAmelCase : List[str] = self.head # default first node
if index == 0:
UpperCAmelCase : Tuple = self.head.next
else:
UpperCAmelCase : Union[str, Any] = self.head
for _ in range(index - 1 ):
UpperCAmelCase : Dict = temp.next
UpperCAmelCase : Optional[Any] = temp.next
UpperCAmelCase : int = temp.next.next
return delete_node.data
def __lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
return self.head is None
def __lowerCAmelCase ( self : int ):
'''simple docstring'''
UpperCAmelCase : List[Any] = None
UpperCAmelCase : str = self.head
while current:
# Store the current node's next node.
UpperCAmelCase : List[Any] = current.next
# Make the current node's next point backwards
UpperCAmelCase : List[str] = prev
# Make the previous node be the current node
UpperCAmelCase : Optional[Any] = current
# Make the current node the next node (to progress iteration)
UpperCAmelCase : Any = next_node
# Return prev in order to put the head at the end
UpperCAmelCase : List[str] = prev
def lowercase_ ( ):
'''simple docstring'''
UpperCAmelCase : Optional[int] = LinkedList()
assert linked_list.is_empty() is True
assert str(_lowercase ) == ""
try:
linked_list.delete_head()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
try:
linked_list.delete_tail()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
for i in range(10 ):
assert len(_lowercase ) == i
linked_list.insert_nth(_lowercase , i + 1 )
assert str(_lowercase ) == "->".join(str(_lowercase ) for i in range(1 , 11 ) )
linked_list.insert_head(0 )
linked_list.insert_tail(11 )
assert str(_lowercase ) == "->".join(str(_lowercase ) for i in range(0 , 12 ) )
assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9 ) == 10
assert linked_list.delete_tail() == 11
assert len(_lowercase ) == 9
assert str(_lowercase ) == "->".join(str(_lowercase ) for i in range(1 , 10 ) )
assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True
for i in range(0 , 9 ):
UpperCAmelCase : Union[str, Any] = -i
assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True
linked_list.reverse()
assert str(_lowercase ) == "->".join(str(_lowercase ) for i in range(-8 , 1 ) )
def lowercase_ ( ):
'''simple docstring'''
UpperCAmelCase : Optional[Any] = [
-9,
1_00,
Node(77_34_51_12 ),
"dlrow olleH",
7,
55_55,
0,
-1_9_2.5_5_5_5_5,
"Hello, world!",
7_7.9,
Node(10 ),
None,
None,
1_2.2_0,
]
UpperCAmelCase : Optional[Any] = LinkedList()
for i in test_input:
linked_list.insert_tail(_lowercase )
# Check if it's empty or not
assert linked_list.is_empty() is False
assert (
str(_lowercase ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->"
"-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the head
UpperCAmelCase : Tuple = linked_list.delete_head()
assert result == -9
assert (
str(_lowercase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the tail
UpperCAmelCase : Any = linked_list.delete_tail()
assert result == 1_2.2
assert (
str(_lowercase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None"
)
# Delete a node in specific location in linked list
UpperCAmelCase : Union[str, Any] = linked_list.delete_nth(10 )
assert result is None
assert (
str(_lowercase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None"
)
# Add a Node instance to its head
linked_list.insert_head(Node("Hello again, world!" ) )
assert (
str(_lowercase )
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None"
)
# Add None to its tail
linked_list.insert_tail(_lowercase )
assert (
str(_lowercase )
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None"
)
# Reverse the linked list
linked_list.reverse()
assert (
str(_lowercase )
== "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->"
"7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)"
)
def lowercase_ ( ):
'''simple docstring'''
from doctest import testmod
testmod()
UpperCAmelCase : Any = LinkedList()
linked_list.insert_head(input("Inserting 1st at head " ).strip() )
linked_list.insert_head(input("Inserting 2nd at head " ).strip() )
print("\nPrint list:" )
linked_list.print_list()
linked_list.insert_tail(input("\nInserting 1st at tail " ).strip() )
linked_list.insert_tail(input("Inserting 2nd at tail " ).strip() )
print("\nPrint list:" )
linked_list.print_list()
print("\nDelete head" )
linked_list.delete_head()
print("Delete tail" )
linked_list.delete_tail()
print("\nPrint list:" )
linked_list.print_list()
print("\nReverse linked list" )
linked_list.reverse()
print("\nPrint list:" )
linked_list.print_list()
print("\nString representation of linked list:" )
print(_lowercase )
print("\nReading/changing Node data using indexing:" )
print(F"""Element at Position 1: {linked_list[1]}""" )
UpperCAmelCase : int = input("Enter New Value: " ).strip()
print("New list:" )
print(_lowercase )
print(F"""length of linked_list is : {len(_lowercase )}""" )
if __name__ == "__main__":
main()
| 292 | 0 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
SCREAMING_SNAKE_CASE : Dict = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE : Optional[int] = {
'''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 __lowerCamelCase ( __lowercase ):
__UpperCamelCase = 'visual_bert'
def __init__(self , lowerCamelCase=30_522 , lowerCamelCase=768 , lowerCamelCase=512 , lowerCamelCase=12 , lowerCamelCase=12 , lowerCamelCase=3_072 , lowerCamelCase="gelu" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=512 , lowerCamelCase=2 , lowerCamelCase=0.02 , lowerCamelCase=1e-12 , lowerCamelCase=False , lowerCamelCase=True , lowerCamelCase=1 , lowerCamelCase=0 , lowerCamelCase=2 , **lowerCamelCase , ):
'''simple docstring'''
super().__init__(pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , **lowerCamelCase )
_lowerCAmelCase = vocab_size
_lowerCAmelCase = max_position_embeddings
_lowerCAmelCase = hidden_size
_lowerCAmelCase = visual_embedding_dim
_lowerCAmelCase = num_hidden_layers
_lowerCAmelCase = num_attention_heads
_lowerCAmelCase = intermediate_size
_lowerCAmelCase = hidden_act
_lowerCAmelCase = hidden_dropout_prob
_lowerCAmelCase = attention_probs_dropout_prob
_lowerCAmelCase = initializer_range
_lowerCAmelCase = type_vocab_size
_lowerCAmelCase = layer_norm_eps
_lowerCAmelCase = bypass_transformer
_lowerCAmelCase = special_visual_initialize
| 156 |
"""simple docstring"""
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import flax
import jax
import jax.numpy as jnp
from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils_flax import (
CommonSchedulerState,
FlaxKarrasDiffusionSchedulers,
FlaxSchedulerMixin,
FlaxSchedulerOutput,
add_noise_common,
get_velocity_common,
)
@flax.struct.dataclass
class __lowerCamelCase :
__UpperCamelCase = 42
# setable values
__UpperCamelCase = 42
__UpperCamelCase = 42
__UpperCamelCase = None
@classmethod
def A__ (cls , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
return cls(common=lowerCamelCase , init_noise_sigma=lowerCamelCase , timesteps=lowerCamelCase )
@dataclass
class __lowerCamelCase ( __lowercase ):
__UpperCamelCase = 42
class __lowerCamelCase ( __lowercase , __lowercase ):
__UpperCamelCase = [e.name for e in FlaxKarrasDiffusionSchedulers]
__UpperCamelCase = 42
@property
def A__ (self ):
'''simple docstring'''
return True
@register_to_config
def __init__(self , lowerCamelCase = 1_000 , lowerCamelCase = 0.0001 , lowerCamelCase = 0.02 , lowerCamelCase = "linear" , lowerCamelCase = None , lowerCamelCase = "fixed_small" , lowerCamelCase = True , lowerCamelCase = "epsilon" , lowerCamelCase = jnp.floataa , ):
'''simple docstring'''
_lowerCAmelCase = dtype
def A__ (self , lowerCamelCase = None ):
'''simple docstring'''
if common is None:
_lowerCAmelCase = CommonSchedulerState.create(self )
# standard deviation of the initial noise distribution
_lowerCAmelCase = jnp.array(1.0 , dtype=self.dtype )
_lowerCAmelCase = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1]
return DDPMSchedulerState.create(
common=lowerCamelCase , init_noise_sigma=lowerCamelCase , timesteps=lowerCamelCase , )
def A__ (self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None ):
'''simple docstring'''
return sample
def A__ (self , lowerCamelCase , lowerCamelCase , lowerCamelCase = () ):
'''simple docstring'''
_lowerCAmelCase = self.config.num_train_timesteps // num_inference_steps
# creates integer timesteps by multiplying by ratio
# rounding to avoid issues when num_inference_step is power of 3
_lowerCAmelCase = (jnp.arange(0 , lowerCamelCase ) * step_ratio).round()[::-1]
return state.replace(
num_inference_steps=lowerCamelCase , timesteps=lowerCamelCase , )
def A__ (self , lowerCamelCase , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None ):
'''simple docstring'''
_lowerCAmelCase = state.common.alphas_cumprod[t]
_lowerCAmelCase = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) )
# For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf)
# and sample from it to get previous sample
# x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample
_lowerCAmelCase = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t]
if variance_type is None:
_lowerCAmelCase = self.config.variance_type
# hacks - were probably added for training stability
if variance_type == "fixed_small":
_lowerCAmelCase = jnp.clip(lowerCamelCase , a_min=1e-20 )
# for rl-diffuser https://arxiv.org/abs/2205.09991
elif variance_type == "fixed_small_log":
_lowerCAmelCase = jnp.log(jnp.clip(lowerCamelCase , a_min=1e-20 ) )
elif variance_type == "fixed_large":
_lowerCAmelCase = state.common.betas[t]
elif variance_type == "fixed_large_log":
# Glide max_log
_lowerCAmelCase = jnp.log(state.common.betas[t] )
elif variance_type == "learned":
return predicted_variance
elif variance_type == "learned_range":
_lowerCAmelCase = variance
_lowerCAmelCase = state.common.betas[t]
_lowerCAmelCase = (predicted_variance + 1) / 2
_lowerCAmelCase = frac * max_log + (1 - frac) * min_log
return variance
def A__ (self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = True , ):
'''simple docstring'''
_lowerCAmelCase = timestep
if key is None:
_lowerCAmelCase = jax.random.PRNGKey(0 )
if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]:
_lowerCAmelCase , _lowerCAmelCase = jnp.split(lowerCamelCase , sample.shape[1] , axis=1 )
else:
_lowerCAmelCase = None
# 1. compute alphas, betas
_lowerCAmelCase = state.common.alphas_cumprod[t]
_lowerCAmelCase = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) )
_lowerCAmelCase = 1 - alpha_prod_t
_lowerCAmelCase = 1 - alpha_prod_t_prev
# 2. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
if self.config.prediction_type == "epsilon":
_lowerCAmelCase = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
elif self.config.prediction_type == "sample":
_lowerCAmelCase = model_output
elif self.config.prediction_type == "v_prediction":
_lowerCAmelCase = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
else:
raise ValueError(
f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` """
""" for the FlaxDDPMScheduler.""" )
# 3. Clip "predicted x_0"
if self.config.clip_sample:
_lowerCAmelCase = jnp.clip(lowerCamelCase , -1 , 1 )
# 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
# See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
_lowerCAmelCase = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t
_lowerCAmelCase = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t
# 5. Compute predicted previous sample µ_t
# See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
_lowerCAmelCase = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
# 6. Add noise
def random_variance():
_lowerCAmelCase = jax.random.split(lowerCamelCase , num=1 )
_lowerCAmelCase = jax.random.normal(lowerCamelCase , shape=model_output.shape , dtype=self.dtype )
return (self._get_variance(lowerCamelCase , lowerCamelCase , predicted_variance=lowerCamelCase ) ** 0.5) * noise
_lowerCAmelCase = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) )
_lowerCAmelCase = pred_prev_sample + variance
if not return_dict:
return (pred_prev_sample, state)
return FlaxDDPMSchedulerOutput(prev_sample=lowerCamelCase , state=lowerCamelCase )
def A__ (self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ):
'''simple docstring'''
return add_noise_common(state.common , lowerCamelCase , lowerCamelCase , lowerCamelCase )
def A__ (self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ):
'''simple docstring'''
return get_velocity_common(state.common , lowerCamelCase , lowerCamelCase , lowerCamelCase )
def __len__(self ):
'''simple docstring'''
return self.config.num_train_timesteps
| 156 | 1 |
"""simple docstring"""
from math import factorial
def lowercase ( UpperCamelCase : List[Any] = 20 ):
"""simple docstring"""
A__ : List[str] =2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1,
# 2, 3,...
A__ : List[str] =n // 2
return int(factorial(UpperCamelCase ) / (factorial(UpperCamelCase ) * factorial(n - k )) )
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
print(solution(20))
else:
try:
__A : List[str] = int(sys.argv[1])
print(solution(n))
except ValueError:
print("Invalid entry - please enter a number.")
| 703 |
"""simple docstring"""
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
__A : Optional[int] = logging.get_logger(__name__)
__A : Any = {"vocab_file": "sentencepiece.bpe.model"}
__A : List[Any] = {
"vocab_file": {
"camembert-base": "https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model",
}
}
__A : List[Any] = {
"camembert-base": 512,
}
__A : Optional[int] = "▁"
class __lowerCAmelCase ( _UpperCamelCase):
'''simple docstring'''
__magic_name__ : Tuple = VOCAB_FILES_NAMES
__magic_name__ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP
__magic_name__ : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__magic_name__ : Dict = ["""input_ids""", """attention_mask"""]
def __init__( self : str , UpperCamelCase__ : List[Any] , UpperCamelCase__ : int="<s>" , UpperCamelCase__ : Dict="</s>" , UpperCamelCase__ : str="</s>" , UpperCamelCase__ : str="<s>" , UpperCamelCase__ : str="<unk>" , UpperCamelCase__ : List[str]="<pad>" , UpperCamelCase__ : Union[str, Any]="<mask>" , UpperCamelCase__ : Optional[int]=["<s>NOTUSED", "</s>NOTUSED"] , UpperCamelCase__ : Optional[Dict[str, Any]] = None , **UpperCamelCase__ : Dict , ):
# Mask token behave like a normal word, i.e. include the space before it
A__ : str =AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else mask_token
A__ : List[Any] ={} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , cls_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , mask_token=UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase__ , )
A__ : Union[str, Any] =spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(UpperCamelCase__ ) )
A__ : Any =vocab_file
# HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual
# sentencepiece vocabulary (this is the case for <s> and </s>
A__ : Optional[Any] ={"<s>NOTUSED": 0, "<pad>": 1, "</s>NOTUSED": 2, "<unk>": 3}
A__ : str =len(self.fairseq_tokens_to_ids )
A__ : Union[str, Any] =len(self.sp_model ) + len(self.fairseq_tokens_to_ids )
A__ : Optional[int] ={v: k for k, v in self.fairseq_tokens_to_ids.items()}
def _UpperCAmelCase ( self : Any , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ):
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
A__ : Optional[int] =[self.cls_token_id]
A__ : Union[str, Any] =[self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def _UpperCAmelCase ( self : int , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None , UpperCamelCase__ : bool = False ):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=UpperCamelCase__ , token_ids_a=UpperCamelCase__ , already_has_special_tokens=UpperCamelCase__ )
if token_ids_a is None:
return [1] + ([0] * len(UpperCamelCase__ )) + [1]
return [1] + ([0] * len(UpperCamelCase__ )) + [1, 1] + ([0] * len(UpperCamelCase__ )) + [1]
def _UpperCAmelCase ( self : str , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ):
A__ : Optional[int] =[self.sep_token_id]
A__ : Dict =[self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
@property
def _UpperCAmelCase ( self : Any ):
return len(self.fairseq_tokens_to_ids ) + len(self.sp_model )
def _UpperCAmelCase ( self : Union[str, Any] ):
A__ : List[Any] ={self.convert_ids_to_tokens(UpperCamelCase__ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def _UpperCAmelCase ( self : str , UpperCamelCase__ : str ):
return self.sp_model.encode(UpperCamelCase__ , out_type=UpperCamelCase__ )
def _UpperCAmelCase ( self : List[str] , UpperCamelCase__ : List[str] ):
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
elif self.sp_model.PieceToId(UpperCamelCase__ ) == 0:
# Convert sentence piece unk token to fairseq unk token index
return self.unk_token_id
return self.fairseq_offset + self.sp_model.PieceToId(UpperCamelCase__ )
def _UpperCAmelCase ( self : List[str] , UpperCamelCase__ : Optional[Any] ):
if index in self.fairseq_ids_to_tokens:
return self.fairseq_ids_to_tokens[index]
return self.sp_model.IdToPiece(index - self.fairseq_offset )
def _UpperCAmelCase ( self : Optional[int] , UpperCamelCase__ : Union[str, Any] ):
A__ : Dict =[]
A__ : Tuple =""
A__ : int =False
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
if not prev_is_special:
out_string += " "
out_string += self.sp_model.decode(UpperCamelCase__ ) + token
A__ : List[Any] =True
A__ : Optional[int] =[]
else:
current_sub_tokens.append(UpperCamelCase__ )
A__ : Dict =False
out_string += self.sp_model.decode(UpperCamelCase__ )
return out_string.strip()
def __getstate__( self : Dict ):
A__ : Dict =self.__dict__.copy()
A__ : List[Any] =None
return state
def __setstate__( self : Any , UpperCamelCase__ : int ):
A__ : Union[str, Any] =d
# for backward compatibility
if not hasattr(self , "sp_model_kwargs" ):
A__ : List[str] ={}
A__ : int =spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def _UpperCAmelCase ( self : str , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ):
if not os.path.isdir(UpperCamelCase__ ):
logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' )
return
A__ : int =os.path.join(
UpperCamelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , UpperCamelCase__ )
elif not os.path.isfile(self.vocab_file ):
with open(UpperCamelCase__ , "wb" ) as fi:
A__ : Union[str, Any] =self.sp_model.serialized_model_proto()
fi.write(UpperCamelCase__ )
return (out_vocab_file,)
| 595 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCAmelCase : Any = {
'''configuration_git''': ['''GIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GitConfig''', '''GitVisionConfig'''],
'''processing_git''': ['''GitProcessor'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase : List[str] = [
'''GIT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''GitForCausalLM''',
'''GitModel''',
'''GitPreTrainedModel''',
'''GitVisionModel''',
]
if TYPE_CHECKING:
from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig
from .processing_git import GitProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_git import (
GIT_PRETRAINED_MODEL_ARCHIVE_LIST,
GitForCausalLM,
GitModel,
GitPreTrainedModel,
GitVisionModel,
)
else:
import sys
UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 239 |
import numpy as np
def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Optional[Any]:
__A : List[Any] = int(np.ceil((x_end - xa) / h ) )
__A : Tuple = np.zeros((n + 1,) )
__A : Tuple = ya
__A : Optional[Any] = xa
for k in range(a ):
__A : List[Any] = f(a , y[k] )
__A : int = f(x + 0.5 * h , y[k] + 0.5 * h * ka )
__A : Optional[int] = f(x + 0.5 * h , y[k] + 0.5 * h * ka )
__A : Dict = f(x + h , y[k] + h * ka )
__A : Union[str, Any] = y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka)
x += h
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| 239 | 1 |
from __future__ import annotations
import unittest
from transformers import DebertaVaConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFDebertaVaForMaskedLM,
TFDebertaVaForQuestionAnswering,
TFDebertaVaForSequenceClassification,
TFDebertaVaForTokenClassification,
TFDebertaVaModel,
)
class lowerCAmelCase_ :
'''simple docstring'''
def __init__( self , lowerCamelCase , lowerCamelCase=13 , lowerCamelCase=7 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=99 , lowerCamelCase=32 , lowerCamelCase=2 , lowerCamelCase=4 , lowerCamelCase=37 , lowerCamelCase="gelu" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=512 , lowerCamelCase=16 , lowerCamelCase=2 , lowerCamelCase=0.0_2 , lowerCamelCase=False , lowerCamelCase=True , lowerCamelCase="None" , lowerCamelCase=3 , lowerCamelCase=4 , lowerCamelCase=None , ):
'''simple docstring'''
a__ = parent
a__ = batch_size
a__ = seq_length
a__ = is_training
a__ = use_input_mask
a__ = use_token_type_ids
a__ = use_labels
a__ = vocab_size
a__ = hidden_size
a__ = num_hidden_layers
a__ = num_attention_heads
a__ = intermediate_size
a__ = hidden_act
a__ = hidden_dropout_prob
a__ = attention_probs_dropout_prob
a__ = max_position_embeddings
a__ = type_vocab_size
a__ = type_sequence_label_size
a__ = initializer_range
a__ = num_labels
a__ = num_choices
a__ = relative_attention
a__ = position_biased_input
a__ = pos_att_type
a__ = scope
def _A ( self ):
'''simple docstring'''
a__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
a__ = None
if self.use_input_mask:
a__ = random_attention_mask([self.batch_size, self.seq_length] )
a__ = None
if self.use_token_type_ids:
a__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
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__ = DebertaVaConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=lowerCamelCase , )
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def _A ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
a__ = TFDebertaVaModel(config=lowerCamelCase )
a__ = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
a__ = [input_ids, input_mask]
a__ = model(lowerCamelCase )
a__ = model(lowerCamelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _A ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
a__ = TFDebertaVaForMaskedLM(config=lowerCamelCase )
a__ = {
"""input_ids""": input_ids,
"""attention_mask""": input_mask,
"""token_type_ids""": token_type_ids,
}
a__ = model(lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def _A ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
a__ = self.num_labels
a__ = TFDebertaVaForSequenceClassification(config=lowerCamelCase )
a__ = {
"""input_ids""": input_ids,
"""attention_mask""": input_mask,
"""token_type_ids""": token_type_ids,
}
a__ = model(lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _A ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
a__ = self.num_labels
a__ = TFDebertaVaForTokenClassification(config=lowerCamelCase )
a__ = {
"""input_ids""": input_ids,
"""attention_mask""": input_mask,
"""token_type_ids""": token_type_ids,
}
a__ = model(lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def _A ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
a__ = TFDebertaVaForQuestionAnswering(config=lowerCamelCase )
a__ = {
"""input_ids""": input_ids,
"""attention_mask""": input_mask,
"""token_type_ids""": token_type_ids,
}
a__ = model(lowerCamelCase )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def _A ( self ):
'''simple docstring'''
a__ = self.prepare_config_and_inputs()
(
(
a__
) , (
a__
) , (
a__
) , (
a__
) , (
a__
) , (
a__
) , (
a__
) ,
) = config_and_inputs
a__ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
return config, inputs_dict
@require_tf
class lowerCAmelCase_ ( A_ ,A_ ,unittest.TestCase ):
'''simple docstring'''
A_ : str = (
(
TFDebertaVaModel,
TFDebertaVaForMaskedLM,
TFDebertaVaForQuestionAnswering,
TFDebertaVaForSequenceClassification,
TFDebertaVaForTokenClassification,
)
if is_tf_available()
else ()
)
A_ : int = (
{
'feature-extraction': TFDebertaVaModel,
'fill-mask': TFDebertaVaForMaskedLM,
'question-answering': TFDebertaVaForQuestionAnswering,
'text-classification': TFDebertaVaForSequenceClassification,
'token-classification': TFDebertaVaForTokenClassification,
'zero-shot': TFDebertaVaForSequenceClassification,
}
if is_tf_available()
else {}
)
A_ : int = False
A_ : Optional[Any] = False
def _A ( self ):
'''simple docstring'''
a__ = TFDebertaVaModelTester(self )
a__ = ConfigTester(self , config_class=lowerCamelCase , hidden_size=37 )
def _A ( self ):
'''simple docstring'''
self.config_tester.run_common_tests()
def _A ( self ):
'''simple docstring'''
a__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase )
def _A ( self ):
'''simple docstring'''
a__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase )
def _A ( self ):
'''simple docstring'''
a__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*lowerCamelCase )
def _A ( self ):
'''simple docstring'''
a__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase )
def _A ( self ):
'''simple docstring'''
a__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*lowerCamelCase )
@slow
def _A ( self ):
'''simple docstring'''
a__ = TFDebertaVaModel.from_pretrained("""kamalkraj/deberta-v2-xlarge""" )
self.assertIsNotNone(lowerCamelCase )
@require_tf
class lowerCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
@unittest.skip(reason="""Model not available yet""" )
def _A ( self ):
'''simple docstring'''
pass
@slow
def _A ( self ):
'''simple docstring'''
a__ = TFDebertaVaModel.from_pretrained("""kamalkraj/deberta-v2-xlarge""" )
a__ = tf.constant([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] )
a__ = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
a__ = model(lowerCamelCase , attention_mask=lowerCamelCase )[0]
a__ = tf.constant(
[[[0.2_3_5_6, 0.1_9_4_8, 0.0_3_6_9], [-0.1_0_6_3, 0.3_5_8_6, -0.5_1_5_2], [-0.6_3_9_9, -0.0_2_5_9, -0.2_5_2_5]]] )
tf.debugging.assert_near(output[:, 1:4, 1:4] , lowerCamelCase , atol=1e-4 )
| 412 |
import gc
import unittest
import torch
from parameterized import parameterized
from diffusers import AutoencoderKL
from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism
from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class lowerCAmelCase_ ( A_ ,A_ ,unittest.TestCase ):
'''simple docstring'''
A_ : Any = AutoencoderKL
A_ : List[Any] = 'sample'
A_ : Optional[Any] = 1e-2
@property
def _A ( self ):
'''simple docstring'''
a__ = 4
a__ = 3
a__ = (32, 32)
a__ = floats_tensor((batch_size, num_channels) + sizes ).to(lowerCamelCase )
return {"sample": image}
@property
def _A ( self ):
'''simple docstring'''
return (3, 32, 32)
@property
def _A ( self ):
'''simple docstring'''
return (3, 32, 32)
def _A ( self ):
'''simple docstring'''
a__ = {
"""block_out_channels""": [32, 64],
"""in_channels""": 3,
"""out_channels""": 3,
"""down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""],
"""up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""],
"""latent_channels""": 4,
}
a__ = self.dummy_input
return init_dict, inputs_dict
def _A ( self ):
'''simple docstring'''
pass
def _A ( self ):
'''simple docstring'''
pass
@unittest.skipIf(torch_device == """mps""" , """Gradient checkpointing skipped on MPS""" )
def _A ( self ):
'''simple docstring'''
a__ , a__ = self.prepare_init_args_and_inputs_for_common()
a__ = self.model_class(**lowerCamelCase )
model.to(lowerCamelCase )
assert not model.is_gradient_checkpointing and model.training
a__ = model(**lowerCamelCase ).sample
# run the backwards pass on the model. For backwards pass, for simplicity purpose,
# we won't calculate the loss and rather backprop on out.sum()
model.zero_grad()
a__ = torch.randn_like(lowerCamelCase )
a__ = (out - labels).mean()
loss.backward()
# re-instantiate the model now enabling gradient checkpointing
a__ = self.model_class(**lowerCamelCase )
# clone model
model_a.load_state_dict(model.state_dict() )
model_a.to(lowerCamelCase )
model_a.enable_gradient_checkpointing()
assert model_a.is_gradient_checkpointing and model_a.training
a__ = model_a(**lowerCamelCase ).sample
# run the backwards pass on the model. For backwards pass, for simplicity purpose,
# we won't calculate the loss and rather backprop on out.sum()
model_a.zero_grad()
a__ = (out_a - labels).mean()
loss_a.backward()
# compare the output and parameters gradients
self.assertTrue((loss - loss_a).abs() < 1e-5 )
a__ = dict(model.named_parameters() )
a__ = dict(model_a.named_parameters() )
for name, param in named_params.items():
self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5e-5 ) )
def _A ( self ):
'''simple docstring'''
a__ , a__ = AutoencoderKL.from_pretrained("""fusing/autoencoder-kl-dummy""" , output_loading_info=lowerCamelCase )
self.assertIsNotNone(lowerCamelCase )
self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 )
model.to(lowerCamelCase )
a__ = model(**self.dummy_input )
assert image is not None, "Make sure output is not None"
def _A ( self ):
'''simple docstring'''
a__ = AutoencoderKL.from_pretrained("""fusing/autoencoder-kl-dummy""" )
a__ = model.to(lowerCamelCase )
model.eval()
if torch_device == "mps":
a__ = torch.manual_seed(0 )
else:
a__ = torch.Generator(device=lowerCamelCase ).manual_seed(0 )
a__ = torch.randn(
1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , )
a__ = image.to(lowerCamelCase )
with torch.no_grad():
a__ = model(lowerCamelCase , sample_posterior=lowerCamelCase , generator=lowerCamelCase ).sample
a__ = output[0, -1, -3:, -3:].flatten().cpu()
# Since the VAE Gaussian prior's generator is seeded on the appropriate device,
# the expected output slices are not the same for CPU and GPU.
if torch_device == "mps":
a__ = torch.tensor(
[
-4.00_78e-01,
-3.83_23e-04,
-1.26_81e-01,
-1.14_62e-01,
2.00_95e-01,
1.08_93e-01,
-8.82_47e-02,
-3.03_61e-01,
-9.86_44e-03,
] )
elif torch_device == "cpu":
a__ = torch.tensor(
[-0.1_3_5_2, 0.0_8_7_8, 0.0_4_1_9, -0.0_8_1_8, -0.1_0_6_9, 0.0_6_8_8, -0.1_4_5_8, -0.4_4_4_6, -0.0_0_2_6] )
else:
a__ = torch.tensor(
[-0.2_4_2_1, 0.4_6_4_2, 0.2_5_0_7, -0.0_4_3_8, 0.0_6_8_2, 0.3_1_6_0, -0.2_0_1_8, -0.0_7_2_7, 0.2_4_8_5] )
self.assertTrue(torch_all_close(lowerCamelCase , lowerCamelCase , rtol=1e-2 ) )
@slow
class lowerCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
def _A ( self , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
return f'gaussian_noise_s={seed}_shape={"_".join([str(lowerCamelCase ) for s in shape] )}.npy'
def _A ( self ):
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _A ( self , lowerCamelCase=0 , lowerCamelCase=(4, 3, 512, 512) , lowerCamelCase=False ):
'''simple docstring'''
a__ = torch.floataa if fpaa else torch.floataa
a__ = torch.from_numpy(load_hf_numpy(self.get_file_format(lowerCamelCase , lowerCamelCase ) ) ).to(lowerCamelCase ).to(lowerCamelCase )
return image
def _A ( self , lowerCamelCase="CompVis/stable-diffusion-v1-4" , lowerCamelCase=False ):
'''simple docstring'''
a__ = """fp16""" if fpaa else None
a__ = torch.floataa if fpaa else torch.floataa
a__ = AutoencoderKL.from_pretrained(
lowerCamelCase , subfolder="""vae""" , torch_dtype=lowerCamelCase , revision=lowerCamelCase , )
model.to(lowerCamelCase ).eval()
return model
def _A ( self , lowerCamelCase=0 ):
'''simple docstring'''
if torch_device == "mps":
return torch.manual_seed(lowerCamelCase )
return torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase )
@parameterized.expand(
[
# fmt: off
[33, [-0.1_6_0_3, 0.9_8_7_8, -0.0_4_9_5, -0.0_7_9_0, -0.2_7_0_9, 0.8_3_7_5, -0.2_0_6_0, -0.0_8_2_4], [-0.2_3_9_5, 0.0_0_9_8, 0.0_1_0_2, -0.0_7_0_9, -0.2_8_4_0, -0.0_2_7_4, -0.0_7_1_8, -0.1_8_2_4]],
[47, [-0.2_3_7_6, 0.1_1_6_8, 0.1_3_3_2, -0.4_8_4_0, -0.2_5_0_8, -0.0_7_9_1, -0.0_4_9_3, -0.4_0_8_9], [0.0_3_5_0, 0.0_8_4_7, 0.0_4_6_7, 0.0_3_4_4, -0.0_8_4_2, -0.0_5_4_7, -0.0_6_3_3, -0.1_1_3_1]],
# fmt: on
] )
def _A ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
a__ = self.get_sd_vae_model()
a__ = self.get_sd_image(lowerCamelCase )
a__ = self.get_generator(lowerCamelCase )
with torch.no_grad():
a__ = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample
assert sample.shape == image.shape
a__ = sample[-1, -2:, -2:, :2].flatten().float().cpu()
a__ = torch.tensor(expected_slice_mps if torch_device == """mps""" else expected_slice )
assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3e-3 )
@parameterized.expand(
[
# fmt: off
[33, [-0.0_5_1_3, 0.0_2_8_9, 1.3_7_9_9, 0.2_1_6_6, -0.2_5_7_3, -0.0_8_7_1, 0.5_1_0_3, -0.0_9_9_9]],
[47, [-0.4_1_2_8, -0.1_3_2_0, -0.3_7_0_4, 0.1_9_6_5, -0.4_1_1_6, -0.2_3_3_2, -0.3_3_4_0, 0.2_2_4_7]],
# fmt: on
] )
@require_torch_gpu
def _A ( self , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
a__ = self.get_sd_vae_model(fpaa=lowerCamelCase )
a__ = self.get_sd_image(lowerCamelCase , fpaa=lowerCamelCase )
a__ = self.get_generator(lowerCamelCase )
with torch.no_grad():
a__ = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample
assert sample.shape == image.shape
a__ = sample[-1, -2:, :2, -2:].flatten().float().cpu()
a__ = torch.tensor(lowerCamelCase )
assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1e-2 )
@parameterized.expand(
[
# fmt: off
[33, [-0.1_6_0_9, 0.9_8_6_6, -0.0_4_8_7, -0.0_7_7_7, -0.2_7_1_6, 0.8_3_6_8, -0.2_0_5_5, -0.0_8_1_4], [-0.2_3_9_5, 0.0_0_9_8, 0.0_1_0_2, -0.0_7_0_9, -0.2_8_4_0, -0.0_2_7_4, -0.0_7_1_8, -0.1_8_2_4]],
[47, [-0.2_3_7_7, 0.1_1_4_7, 0.1_3_3_3, -0.4_8_4_1, -0.2_5_0_6, -0.0_8_0_5, -0.0_4_9_1, -0.4_0_8_5], [0.0_3_5_0, 0.0_8_4_7, 0.0_4_6_7, 0.0_3_4_4, -0.0_8_4_2, -0.0_5_4_7, -0.0_6_3_3, -0.1_1_3_1]],
# fmt: on
] )
def _A ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
a__ = self.get_sd_vae_model()
a__ = self.get_sd_image(lowerCamelCase )
with torch.no_grad():
a__ = model(lowerCamelCase ).sample
assert sample.shape == image.shape
a__ = sample[-1, -2:, -2:, :2].flatten().float().cpu()
a__ = torch.tensor(expected_slice_mps if torch_device == """mps""" else expected_slice )
assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3e-3 )
@parameterized.expand(
[
# fmt: off
[13, [-0.2_0_5_1, -0.1_8_0_3, -0.2_3_1_1, -0.2_1_1_4, -0.3_2_9_2, -0.3_5_7_4, -0.2_9_5_3, -0.3_3_2_3]],
[37, [-0.2_6_3_2, -0.2_6_2_5, -0.2_1_9_9, -0.2_7_4_1, -0.4_5_3_9, -0.4_9_9_0, -0.3_7_2_0, -0.4_9_2_5]],
# fmt: on
] )
@require_torch_gpu
def _A ( self , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
a__ = self.get_sd_vae_model()
a__ = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) )
with torch.no_grad():
a__ = model.decode(lowerCamelCase ).sample
assert list(sample.shape ) == [3, 3, 512, 512]
a__ = sample[-1, -2:, :2, -2:].flatten().cpu()
a__ = torch.tensor(lowerCamelCase )
assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1e-3 )
@parameterized.expand(
[
# fmt: off
[27, [-0.0_3_6_9, 0.0_2_0_7, -0.0_7_7_6, -0.0_6_8_2, -0.1_7_4_7, -0.1_9_3_0, -0.1_4_6_5, -0.2_0_3_9]],
[16, [-0.1_6_2_8, -0.2_1_3_4, -0.2_7_4_7, -0.2_6_4_2, -0.3_7_7_4, -0.4_4_0_4, -0.3_6_8_7, -0.4_2_7_7]],
# fmt: on
] )
@require_torch_gpu
def _A ( self , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
a__ = self.get_sd_vae_model(fpaa=lowerCamelCase )
a__ = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase )
with torch.no_grad():
a__ = model.decode(lowerCamelCase ).sample
assert list(sample.shape ) == [3, 3, 512, 512]
a__ = sample[-1, -2:, :2, -2:].flatten().float().cpu()
a__ = torch.tensor(lowerCamelCase )
assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=5e-3 )
@parameterized.expand([(13,), (16,), (27,)] )
@require_torch_gpu
@unittest.skipIf(not is_xformers_available() , reason="""xformers is not required when using PyTorch 2.0.""" )
def _A ( self , lowerCamelCase ):
'''simple docstring'''
a__ = self.get_sd_vae_model(fpaa=lowerCamelCase )
a__ = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase )
with torch.no_grad():
a__ = model.decode(lowerCamelCase ).sample
model.enable_xformers_memory_efficient_attention()
with torch.no_grad():
a__ = model.decode(lowerCamelCase ).sample
assert list(sample.shape ) == [3, 3, 512, 512]
assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1e-1 )
@parameterized.expand([(13,), (16,), (37,)] )
@require_torch_gpu
@unittest.skipIf(not is_xformers_available() , reason="""xformers is not required when using PyTorch 2.0.""" )
def _A ( self , lowerCamelCase ):
'''simple docstring'''
a__ = self.get_sd_vae_model()
a__ = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) )
with torch.no_grad():
a__ = model.decode(lowerCamelCase ).sample
model.enable_xformers_memory_efficient_attention()
with torch.no_grad():
a__ = model.decode(lowerCamelCase ).sample
assert list(sample.shape ) == [3, 3, 512, 512]
assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1e-2 )
@parameterized.expand(
[
# fmt: off
[33, [-0.3_0_0_1, 0.0_9_1_8, -2.6_9_8_4, -3.9_7_2_0, -3.2_0_9_9, -5.0_3_5_3, 1.7_3_3_8, -0.2_0_6_5, 3.4_2_6_7]],
[47, [-1.5_0_3_0, -4.3_8_7_1, -6.0_3_5_5, -9.1_1_5_7, -1.6_6_6_1, -2.7_8_5_3, 2.1_6_0_7, -5.0_8_2_3, 2.5_6_3_3]],
# fmt: on
] )
def _A ( self , lowerCamelCase , lowerCamelCase ):
'''simple docstring'''
a__ = self.get_sd_vae_model()
a__ = self.get_sd_image(lowerCamelCase )
a__ = self.get_generator(lowerCamelCase )
with torch.no_grad():
a__ = model.encode(lowerCamelCase ).latent_dist
a__ = dist.sample(generator=lowerCamelCase )
assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]
a__ = sample[0, -1, -3:, -3:].flatten().cpu()
a__ = torch.tensor(lowerCamelCase )
a__ = 3e-3 if torch_device != """mps""" else 1e-2
assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=lowerCamelCase )
| 412 | 1 |
'''simple docstring'''
def A__ ( __lowerCAmelCase : int ):
if number < 0:
raise ValueError("""number must not be negative""" )
return number & (number - 1) == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| 50 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_torch_available,
)
_lowercase = {'''configuration_vit_mae''': ['''VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ViTMAEConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''ViTMAEForPreTraining''',
'''ViTMAELayer''',
'''ViTMAEModel''',
'''ViTMAEPreTrainedModel''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''TFViTMAEForPreTraining''',
'''TFViTMAEModel''',
'''TFViTMAEPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_vit_mae import (
VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST,
ViTMAEForPreTraining,
ViTMAELayer,
ViTMAEModel,
ViTMAEPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel
else:
import sys
_lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 118 | 0 |
'''simple docstring'''
def snake_case_ ( SCREAMING_SNAKE_CASE__ = 10**12 ):
'''simple docstring'''
_snake_case = 1
_snake_case = 0
_snake_case = 1
_snake_case = 1
while numerator <= 2 * min_total - 1:
prev_numerator += 2 * numerator
numerator += 2 * prev_numerator
prev_denominator += 2 * denominator
denominator += 2 * prev_denominator
return (denominator + 1) // 2
if __name__ == "__main__":
print(F'{solution() = }')
| 368 |
'''simple docstring'''
import itertools
import json
import os
import unittest
from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast
from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class __SCREAMING_SNAKE_CASE ( __UpperCamelCase , unittest.TestCase ):
'''simple docstring'''
UpperCAmelCase__ : List[Any] = LongformerTokenizer
UpperCAmelCase__ : Dict = True
UpperCAmelCase__ : Union[str, Any] = LongformerTokenizerFast
UpperCAmelCase__ : List[str] = True
def UpperCamelCase( self ):
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
_snake_case = [
"l",
"o",
"w",
"e",
"r",
"s",
"t",
"i",
"d",
"n",
"\u0120",
"\u0120l",
"\u0120n",
"\u0120lo",
"\u0120low",
"er",
"\u0120lowest",
"\u0120newer",
"\u0120wider",
"<unk>",
]
_snake_case = dict(zip(lowerCamelCase , range(len(lowerCamelCase ) ) ) )
_snake_case = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
_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:
fp.write(json.dumps(lowerCamelCase ) + "\n" )
with open(self.merges_file , "w" , encoding="utf-8" ) as fp:
fp.write("\n".join(lowerCamelCase ) )
def UpperCamelCase( self , **lowerCamelCase ):
kwargs.update(self.special_tokens_map )
return self.tokenizer_class.from_pretrained(self.tmpdirname , **lowerCamelCase )
def UpperCamelCase( self , **lowerCamelCase ):
kwargs.update(self.special_tokens_map )
return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **lowerCamelCase )
def UpperCamelCase( self , lowerCamelCase ):
_snake_case = "lower newer"
_snake_case = "lower newer"
return input_text, output_text
def UpperCamelCase( self ):
_snake_case = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map )
_snake_case = "lower newer"
_snake_case = ["l", "o", "w", "er", "\u0120", "n", "e", "w", "er"]
_snake_case = tokenizer.tokenize(lowerCamelCase ) # , add_prefix_space=True)
self.assertListEqual(lowerCamelCase , lowerCamelCase )
_snake_case = tokens + [tokenizer.unk_token]
_snake_case = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase ) , lowerCamelCase )
def UpperCamelCase( self ):
_snake_case = self.get_tokenizer()
self.assertListEqual(tokenizer.encode("Hello world!" , add_special_tokens=lowerCamelCase ) , [0, 31_414, 232, 328, 2] )
self.assertListEqual(
tokenizer.encode("Hello world! cécé herlolip 418" , add_special_tokens=lowerCamelCase ) , [0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2] , )
@slow
def UpperCamelCase( self ):
_snake_case = self.tokenizer_class.from_pretrained("allenai/longformer-base-4096" )
_snake_case = tokenizer.encode("sequence builders" , add_special_tokens=lowerCamelCase )
_snake_case = tokenizer.encode("multi-sequence build" , add_special_tokens=lowerCamelCase )
_snake_case = tokenizer.encode(
"sequence builders" , add_special_tokens=lowerCamelCase , add_prefix_space=lowerCamelCase )
_snake_case = tokenizer.encode(
"sequence builders" , "multi-sequence build" , add_special_tokens=lowerCamelCase , add_prefix_space=lowerCamelCase )
_snake_case = tokenizer.build_inputs_with_special_tokens(lowerCamelCase )
_snake_case = tokenizer.build_inputs_with_special_tokens(lowerCamelCase , lowerCamelCase )
assert encoded_sentence == encoded_text_from_decode
assert encoded_pair == encoded_pair_from_decode
def UpperCamelCase( self ):
_snake_case = self.get_tokenizer()
_snake_case = "Encode this sequence."
_snake_case = tokenizer.byte_encoder[" ".encode("utf-8" )[0]]
# Testing encoder arguments
_snake_case = tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase , add_prefix_space=lowerCamelCase )
_snake_case = tokenizer.convert_ids_to_tokens(encoded[0] )[0]
self.assertNotEqual(lowerCamelCase , lowerCamelCase )
_snake_case = tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase , add_prefix_space=lowerCamelCase )
_snake_case = tokenizer.convert_ids_to_tokens(encoded[0] )[0]
self.assertEqual(lowerCamelCase , lowerCamelCase )
tokenizer.add_special_tokens({"bos_token": "<s>"} )
_snake_case = tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase )
_snake_case = tokenizer.convert_ids_to_tokens(encoded[1] )[0]
self.assertNotEqual(lowerCamelCase , lowerCamelCase )
# Testing spaces after special tokens
_snake_case = "<mask>"
tokenizer.add_special_tokens(
{"mask_token": AddedToken(lowerCamelCase , lstrip=lowerCamelCase , rstrip=lowerCamelCase )} ) # mask token has a left space
_snake_case = tokenizer.convert_tokens_to_ids(lowerCamelCase )
_snake_case = "Encode <mask> sequence"
_snake_case = "Encode <mask>sequence"
_snake_case = tokenizer.encode(lowerCamelCase )
_snake_case = encoded.index(lowerCamelCase )
_snake_case = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0]
self.assertEqual(lowerCamelCase , lowerCamelCase )
_snake_case = tokenizer.encode(lowerCamelCase )
_snake_case = encoded.index(lowerCamelCase )
_snake_case = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0]
self.assertNotEqual(lowerCamelCase , lowerCamelCase )
def UpperCamelCase( self ):
pass
def UpperCamelCase( self ):
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
_snake_case = self.rust_tokenizer_class.from_pretrained(lowerCamelCase , **lowerCamelCase )
_snake_case = self.tokenizer_class.from_pretrained(lowerCamelCase , **lowerCamelCase )
_snake_case = "A, <mask> AllenNLP sentence."
_snake_case = tokenizer_r.encode_plus(lowerCamelCase , add_special_tokens=lowerCamelCase , return_token_type_ids=lowerCamelCase )
_snake_case = tokenizer_p.encode_plus(lowerCamelCase , add_special_tokens=lowerCamelCase , return_token_type_ids=lowerCamelCase )
# token_type_ids should put 0 everywhere
self.assertEqual(sum(tokens_r["token_type_ids"] ) , sum(tokens_p["token_type_ids"] ) )
# attention_mask should put 1 everywhere, so sum over length should be 1
self.assertEqual(
sum(tokens_r["attention_mask"] ) / len(tokens_r["attention_mask"] ) , sum(tokens_p["attention_mask"] ) / len(tokens_p["attention_mask"] ) , )
_snake_case = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"] )
_snake_case = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"] )
# Rust correctly handles the space before the mask while python doesnt
self.assertSequenceEqual(tokens_p["input_ids"] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] )
self.assertSequenceEqual(tokens_r["input_ids"] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] )
self.assertSequenceEqual(
lowerCamelCase , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
self.assertSequenceEqual(
lowerCamelCase , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
def UpperCamelCase( self ):
for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ):
_snake_case = self.rust_tokenizer_class.from_pretrained(
self.tmpdirname , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase )
_snake_case = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() )
_snake_case = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() )
self.assertEqual(pre_tokenizer_state["add_prefix_space"] , lowerCamelCase )
self.assertEqual(post_processor_state["add_prefix_space"] , lowerCamelCase )
self.assertEqual(post_processor_state["trim_offsets"] , lowerCamelCase )
def UpperCamelCase( self ):
# Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and
# `trim_offsets`
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
_snake_case = "hello" # `hello` is a token in the vocabulary of `pretrained_name`
_snake_case = F'''{text_of_1_token} {text_of_1_token}'''
_snake_case = self.rust_tokenizer_class.from_pretrained(
lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase )
_snake_case = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase )
self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCamelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(lowerCamelCase ) + 1, len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , )
_snake_case = self.rust_tokenizer_class.from_pretrained(
lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase )
_snake_case = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase )
self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCamelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(lowerCamelCase ) + 1, len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , )
_snake_case = self.rust_tokenizer_class.from_pretrained(
lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase )
_snake_case = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase )
self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCamelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(lowerCamelCase ), len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , )
_snake_case = self.rust_tokenizer_class.from_pretrained(
lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase )
_snake_case = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase )
self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCamelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(lowerCamelCase ), len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , )
_snake_case = F''' {text}'''
# tokenizer_r = self.rust_tokenizer_class.from_pretrained(
# pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True
# )
# encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
# self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token)))
# self.assertEqual(
# encoding.offset_mapping[1],
# (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)),
# )
_snake_case = self.rust_tokenizer_class.from_pretrained(
lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase )
_snake_case = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase )
self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(lowerCamelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(lowerCamelCase ) + 1, 1 + len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , )
_snake_case = self.rust_tokenizer_class.from_pretrained(
lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase )
_snake_case = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase )
self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(lowerCamelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(lowerCamelCase ), 1 + len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , )
_snake_case = self.rust_tokenizer_class.from_pretrained(
lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase )
_snake_case = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase )
self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(lowerCamelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(lowerCamelCase ), 1 + len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , )
| 368 | 1 |
'''simple docstring'''
from math import factorial
def _UpperCamelCase ( UpperCamelCase__ = 1_0_0 ):
return sum(map(__a , str(factorial(__a ) ) ) )
if __name__ == "__main__":
print(solution(int(input('Enter the Number: ').strip())))
| 407 |
from string import ascii_uppercase
lowerCamelCase__ = {char: i for i, char in enumerate(ascii_uppercase)}
lowerCamelCase__ = dict(enumerate(ascii_uppercase))
def A(__a: str , __a: str ):
lowerCAmelCase_ = len(__a )
lowerCAmelCase_ = 0
while True:
if x == i:
lowerCAmelCase_ = 0
if len(__a ) == len(__a ):
break
key += key[i]
i += 1
return key
def A(__a: str , __a: str ):
lowerCAmelCase_ = ""
lowerCAmelCase_ = 0
for letter in message:
if letter == " ":
cipher_text += " "
else:
lowerCAmelCase_ = (dicta[letter] - dicta[key_new[i]]) % 26
i += 1
cipher_text += dicta[x]
return cipher_text
def A(__a: str , __a: str ):
lowerCAmelCase_ = ""
lowerCAmelCase_ = 0
for letter in cipher_text:
if letter == " ":
or_txt += " "
else:
lowerCAmelCase_ = (dicta[letter] + dicta[key_new[i]] + 26) % 26
i += 1
or_txt += dicta[x]
return or_txt
def A():
lowerCAmelCase_ = "THE GERMAN ATTACK"
lowerCAmelCase_ = "SECRET"
lowerCAmelCase_ = generate_key(__a , __a )
lowerCAmelCase_ = cipher_text(__a , __a )
print(F"Encrypted Text = {s}" )
print(F"Original Text = {original_text(__a , __a )}" )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 122 | 0 |
def __lowerCAmelCase ( _UpperCamelCase , _UpperCamelCase = False ) -> bool:
'''simple docstring'''
if n == 2:
return True
if not n % 2 or n < 2:
return False
if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit
return False
if n > 3317044064679887385961981 and not allow_probable:
raise ValueError(
"""Warning: upper bound of deterministic test is exceeded. """
"""Pass allow_probable=True to allow probabilistic test. """
"""A return value of True indicates a probable prime.""" )
# array bounds provided by analysis
lowerCamelCase__: Any = [
2047,
1373653,
25326001,
3215031751,
2152302898747,
3474749660383,
341550071728321,
1,
3825123056546413051,
1,
1,
318665857834031151167461,
3317044064679887385961981,
]
lowerCamelCase__: List[str] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
for idx, _p in enumerate(_UpperCamelCase , 1 ):
if n < _p:
# then we have our last prime to check
lowerCamelCase__: List[Any] = primes[:idx]
break
lowerCamelCase__: Optional[Any] = n - 1, 0
# break up n -1 into a power of 2 (s) and
# remaining odd component
# essentially, solve for d * 2 ** s == n - 1
while d % 2 == 0:
d //= 2
s += 1
for prime in plist:
lowerCamelCase__: Union[str, Any] = False
for r in range(_UpperCamelCase ):
lowerCamelCase__: Optional[Any] = pow(_UpperCamelCase , d * 2**r , _UpperCamelCase )
# see article for analysis explanation for m
if (r == 0 and m == 1) or ((m + 1) % n == 0):
lowerCamelCase__: Dict = True
# this loop will not determine compositeness
break
if pr:
continue
# if pr is False, then the above loop never evaluated to true,
# and the n MUST be composite
return False
return True
def __lowerCAmelCase ( ) -> None:
'''simple docstring'''
assert not miller_rabin(561 )
assert miller_rabin(563 )
# 2047
assert not miller_rabin(838201 )
assert miller_rabin(838207 )
# 1_373_653
assert not miller_rabin(17316001 )
assert miller_rabin(17316017 )
# 25_326_001
assert not miller_rabin(3078386641 )
assert miller_rabin(3078386653 )
# 3_215_031_751
assert not miller_rabin(1713045574801 )
assert miller_rabin(1713045574819 )
# 2_152_302_898_747
assert not miller_rabin(2779799728307 )
assert miller_rabin(2779799728327 )
# 3_474_749_660_383
assert not miller_rabin(113850023909441 )
assert miller_rabin(113850023909527 )
# 341_550_071_728_321
assert not miller_rabin(1275041018848804351 )
assert miller_rabin(1275041018848804391 )
# 3_825_123_056_546_413_051
assert not miller_rabin(79666464458507787791867 )
assert miller_rabin(79666464458507787791951 )
# 318_665_857_834_031_151_167_461
assert not miller_rabin(552840677446647897660333 )
assert miller_rabin(552840677446647897660359 )
# 3_317_044_064_679_887_385_961_981
# upper limit for probabilistic test
if __name__ == "__main__":
test_miller_rabin()
| 702 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
_lowercase = {
'configuration_mask2former': [
'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
'Mask2FormerConfig',
],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = ['Mask2FormerImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'Mask2FormerForUniversalSegmentation',
'Mask2FormerModel',
'Mask2FormerPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_maskaformer import MaskaFormerImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_maskaformer import (
MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
MaskaFormerForUniversalSegmentation,
MaskaFormerModel,
MaskaFormerPreTrainedModel,
)
else:
import sys
_lowercase = _LazyModule(__name__, globals()['__file__'], _import_structure)
| 242 | 0 |
"""simple docstring"""
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING
__lowerCamelCase = logging.get_logger(__name__)
__lowerCamelCase = {
'salesforce/blip2-opt-2.7b': 'https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json',
}
class __A ( SCREAMING_SNAKE_CASE_ ):
UpperCAmelCase__ = "blip_2_vision_model"
def __init__( self : Dict , __snake_case : Any=1_4_0_8 , __snake_case : Union[str, Any]=6_1_4_4 , __snake_case : List[str]=3_9 , __snake_case : int=1_6 , __snake_case : Tuple=2_2_4 , __snake_case : Any=1_4 , __snake_case : List[Any]="gelu" , __snake_case : Optional[Any]=0.00001 , __snake_case : Union[str, Any]=0.0 , __snake_case : Dict=1E-10 , __snake_case : List[str]=True , **__snake_case : Optional[int] , ) -> Tuple:
super().__init__(**__snake_case )
__magic_name__: Any = hidden_size
__magic_name__: Any = intermediate_size
__magic_name__: Union[str, Any] = num_hidden_layers
__magic_name__: List[Any] = num_attention_heads
__magic_name__: Any = patch_size
__magic_name__: int = image_size
__magic_name__: Tuple = initializer_range
__magic_name__: List[Any] = attention_dropout
__magic_name__: Union[str, Any] = layer_norm_eps
__magic_name__: Dict = hidden_act
__magic_name__: str = qkv_bias
@classmethod
def lowerCamelCase__ ( cls : List[str] , __snake_case : Union[str, os.PathLike] , **__snake_case : Optional[Any] ) -> "PretrainedConfig":
cls._set_token_in_kwargs(__snake_case )
__magic_name__, __magic_name__: Union[str, Any] = cls.get_config_dict(__snake_case , **__snake_case )
# get the vision config dict if we are loading from Blip2Config
if config_dict.get("""model_type""" ) == "blip-2":
__magic_name__: int = config_dict["""vision_config"""]
if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' )
return cls.from_dict(__snake_case , **__snake_case )
class __A ( SCREAMING_SNAKE_CASE_ ):
UpperCAmelCase__ = "blip_2_qformer"
def __init__( self : Optional[Any] , __snake_case : Optional[Any]=3_0_5_2_2 , __snake_case : List[Any]=7_6_8 , __snake_case : int=1_2 , __snake_case : str=1_2 , __snake_case : Union[str, Any]=3_0_7_2 , __snake_case : Union[str, Any]="gelu" , __snake_case : Any=0.1 , __snake_case : Optional[Any]=0.1 , __snake_case : List[Any]=5_1_2 , __snake_case : str=0.02 , __snake_case : Any=1E-12 , __snake_case : Tuple=0 , __snake_case : Tuple="absolute" , __snake_case : Dict=2 , __snake_case : List[Any]=1_4_0_8 , **__snake_case : Tuple , ) -> Dict:
super().__init__(pad_token_id=__snake_case , **__snake_case )
__magic_name__: Optional[Any] = vocab_size
__magic_name__: Optional[int] = hidden_size
__magic_name__: Dict = num_hidden_layers
__magic_name__: str = num_attention_heads
__magic_name__: List[str] = hidden_act
__magic_name__: Any = intermediate_size
__magic_name__: int = hidden_dropout_prob
__magic_name__: str = attention_probs_dropout_prob
__magic_name__: int = max_position_embeddings
__magic_name__: List[str] = initializer_range
__magic_name__: Optional[int] = layer_norm_eps
__magic_name__: Dict = position_embedding_type
__magic_name__: List[Any] = cross_attention_frequency
__magic_name__: Tuple = encoder_hidden_size
@classmethod
def lowerCamelCase__ ( cls : Tuple , __snake_case : Union[str, os.PathLike] , **__snake_case : Optional[int] ) -> "PretrainedConfig":
cls._set_token_in_kwargs(__snake_case )
__magic_name__, __magic_name__: Optional[Any] = cls.get_config_dict(__snake_case , **__snake_case )
# get the qformer config dict if we are loading from Blip2Config
if config_dict.get("""model_type""" ) == "blip-2":
__magic_name__: List[str] = config_dict["""qformer_config"""]
if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' )
return cls.from_dict(__snake_case , **__snake_case )
class __A ( SCREAMING_SNAKE_CASE_ ):
UpperCAmelCase__ = "blip-2"
UpperCAmelCase__ = True
def __init__( self : str , __snake_case : Dict=None , __snake_case : int=None , __snake_case : Tuple=None , __snake_case : int=3_2 , **__snake_case : Tuple ) -> List[Any]:
super().__init__(**__snake_case )
if vision_config is None:
__magic_name__: int = {}
logger.info("""vision_config is None. initializing the Blip2VisionConfig with default values.""" )
if qformer_config is None:
__magic_name__: str = {}
logger.info("""qformer_config is None. Initializing the Blip2QFormerConfig with default values.""" )
if text_config is None:
__magic_name__: Optional[Any] = {}
logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""" )
__magic_name__: Dict = BlipaVisionConfig(**__snake_case )
__magic_name__: Optional[int] = BlipaQFormerConfig(**__snake_case )
__magic_name__: str = text_config["""model_type"""] if """model_type""" in text_config else """opt"""
__magic_name__: Union[str, Any] = CONFIG_MAPPING[text_model_type](**__snake_case )
__magic_name__: Tuple = self.text_config.tie_word_embeddings
__magic_name__: Optional[int] = self.text_config.is_encoder_decoder
__magic_name__: Optional[Any] = num_query_tokens
__magic_name__: int = self.vision_config.hidden_size
__magic_name__: List[Any] = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
__magic_name__: Tuple = 1.0
__magic_name__: Any = 0.02
@classmethod
def lowerCamelCase__ ( cls : List[str] , __snake_case : BlipaVisionConfig , __snake_case : BlipaQFormerConfig , __snake_case : PretrainedConfig , **__snake_case : Optional[int] , ) -> str:
return cls(
vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **__snake_case , )
def lowerCamelCase__ ( self : Optional[Any] ) -> Optional[int]:
__magic_name__: Optional[int] = copy.deepcopy(self.__dict__ )
__magic_name__: List[Any] = self.vision_config.to_dict()
__magic_name__: int = self.qformer_config.to_dict()
__magic_name__: Dict = self.text_config.to_dict()
__magic_name__: Optional[int] = self.__class__.model_type
return output
| 96 |
"""simple docstring"""
def a ( __UpperCAmelCase : int = 1_0_0 ) -> int:
__magic_name__: str = 0
__magic_name__: Any = 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() = }''')
| 96 | 1 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import importlib.metadata
import json
import os
from dataclasses import dataclass
from typing import Any, Dict, Union
from packaging import version
from ..utils import is_torch_available, logging
if is_torch_available():
import torch
__lowerCamelCase = logging.get_logger(__name__)
@dataclass
class a__ :
def __init__( self : Tuple , lowerCamelCase_ : List[Any]=False , lowerCamelCase_ : List[Any]=False , lowerCamelCase_ : Union[str, Any]=6.0 , lowerCamelCase_ : Dict=None , lowerCamelCase_ : int=False , lowerCamelCase_ : Tuple=False , lowerCamelCase_ : Tuple=None , lowerCamelCase_ : int="fp4" , lowerCamelCase_ : str=False , **lowerCamelCase_ : int , ):
a_ : int = load_in_abit
a_ : List[str] = load_in_abit
a_ : Union[str, Any] = llm_inta_threshold
a_ : Optional[int] = llm_inta_skip_modules
a_ : List[str] = llm_inta_enable_fpaa_cpu_offload
a_ : List[Any] = llm_inta_has_fpaa_weight
a_ : str = bnb_abit_quant_type
a_ : int = bnb_abit_use_double_quant
if bnb_abit_compute_dtype is None:
a_ : List[Any] = torch.floataa
elif isinstance(lowerCamelCase_ , lowerCamelCase_ ):
a_ : str = getattr(lowerCamelCase_ , lowerCamelCase_ )
elif isinstance(lowerCamelCase_ , torch.dtype ):
a_ : str = bnb_abit_compute_dtype
else:
raise ValueError("""bnb_4bit_compute_dtype must be a string or a torch.dtype""" )
self.post_init()
def UpperCAmelCase( self : str ):
if not isinstance(self.llm_inta_threshold , lowerCamelCase_ ):
raise ValueError("""llm_int8_threshold must be a float""" )
if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules , lowerCamelCase_ ):
raise ValueError("""llm_int8_skip_modules must be a list of strings""" )
if not isinstance(self.llm_inta_enable_fpaa_cpu_offload , lowerCamelCase_ ):
raise ValueError("""llm_int8_enable_fp32_cpu_offload must be a boolean""" )
if not isinstance(self.llm_inta_has_fpaa_weight , lowerCamelCase_ ):
raise ValueError("""llm_int8_has_fp16_weight must be a boolean""" )
if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype , torch.dtype ):
raise ValueError("""bnb_4bit_compute_dtype must be torch.dtype""" )
if not isinstance(self.bnb_abit_quant_type , lowerCamelCase_ ):
raise ValueError("""bnb_4bit_quant_type must be a string""" )
if not isinstance(self.bnb_abit_use_double_quant , lowerCamelCase_ ):
raise ValueError("""bnb_4bit_use_double_quant must be a boolean""" )
if self.load_in_abit and not version.parse(importlib.metadata.version("""bitsandbytes""" ) ) >= version.parse(
"""0.39.0""" ):
raise ValueError(
"""4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version""" )
def UpperCAmelCase( self : List[Any] ):
return self.load_in_abit or self.load_in_abit
def UpperCAmelCase( self : Optional[int] ):
if self.load_in_abit:
return "llm_int8"
elif self.load_in_abit and self.bnb_abit_quant_type == "fp4":
return "fp4"
elif self.load_in_abit and self.bnb_abit_quant_type == "nf4":
return "nf4"
else:
return None
@classmethod
def UpperCAmelCase( cls : Dict , lowerCamelCase_ : List[str] , lowerCamelCase_ : str , **lowerCamelCase_ : int ):
a_ : Optional[Any] = cls(**lowerCamelCase_ )
a_ : Dict = []
for key, value in kwargs.items():
if hasattr(lowerCamelCase_ , lowerCamelCase_ ):
setattr(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
to_remove.append(lowerCamelCase_ )
for key in to_remove:
kwargs.pop(lowerCamelCase_ , lowerCamelCase_ )
if return_unused_kwargs:
return config, kwargs
else:
return config
def UpperCAmelCase( self : List[Any] , lowerCamelCase_ : Union[str, os.PathLike] ):
with open(lowerCamelCase_ , """w""" , encoding="""utf-8""" ) as writer:
a_ : List[Any] = self.to_dict()
a_ : Tuple = json.dumps(lowerCamelCase_ , indent=2 , sort_keys=lowerCamelCase_ ) + """\n"""
writer.write(lowerCamelCase_ )
def UpperCAmelCase( self : int ):
a_ : Any = copy.deepcopy(self.__dict__ )
a_ : Dict = str(output["""bnb_4bit_compute_dtype"""] ).split(""".""" )[1]
return output
def __repr__( self : Tuple ):
return F'''{self.__class__.__name__} {self.to_json_string()}'''
def UpperCAmelCase( self : Optional[int] , lowerCamelCase_ : bool = True ):
if use_diff is True:
a_ : Any = self.to_diff_dict()
else:
a_ : Tuple = self.to_dict()
return json.dumps(lowerCamelCase_ , indent=2 , sort_keys=lowerCamelCase_ ) + "\n"
def UpperCAmelCase( self : List[Any] ):
a_ : Optional[int] = self.to_dict()
# get the default config dict
a_ : Tuple = BitsAndBytesConfig().to_dict()
a_ : int = {}
# only serialize values that differ from the default config
for key, value in config_dict.items():
if value != default_config_dict[key]:
a_ : List[Any] = value
return serializable_config_dict
| 478 |
import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List
from ..utils import logging
__lowerCamelCase = logging.get_logger(__name__)
def _a ( __UpperCamelCase=None , __UpperCamelCase=None ):
return field(default_factory=lambda: default , metadata=__UpperCamelCase )
@dataclass
class a__ :
lowerCamelCase__: List[str] = list_field(
default=[] , metadata={
"""help""": (
"""Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version"""
""" of all available models"""
)
} , )
lowerCamelCase__: List[int] = list_field(
default=[8] , metadata={"""help""": """List of batch sizes for which memory and time performance will be evaluated"""} )
lowerCamelCase__: List[int] = list_field(
default=[8, 32, 128, 512] , metadata={"""help""": """List of sequence lengths for which memory and time performance will be evaluated"""} , )
lowerCamelCase__: bool = field(
default=lowerCAmelCase_ , metadata={"""help""": """Whether to benchmark inference of model. Inference can be disabled via --no-inference."""} , )
lowerCamelCase__: bool = field(
default=lowerCAmelCase_ , metadata={"""help""": """Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."""} , )
lowerCamelCase__: bool = field(
default=lowerCAmelCase_ , metadata={"""help""": """Whether to run on available tpu devices. TPU can be disabled via --no-tpu."""} )
lowerCamelCase__: bool = field(default=lowerCAmelCase_ , metadata={"""help""": """Use FP16 to accelerate inference."""} )
lowerCamelCase__: bool = field(default=lowerCAmelCase_ , metadata={"""help""": """Benchmark training of model"""} )
lowerCamelCase__: bool = field(default=lowerCAmelCase_ , metadata={"""help""": """Verbose memory tracing"""} )
lowerCamelCase__: bool = field(
default=lowerCAmelCase_ , metadata={"""help""": """Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."""} , )
lowerCamelCase__: bool = field(
default=lowerCAmelCase_ , metadata={
"""help""": """Whether to perform memory measurements. Memory measurements can be disabled via --no-memory"""
} , )
lowerCamelCase__: bool = field(default=lowerCAmelCase_ , metadata={"""help""": """Trace memory line by line"""} )
lowerCamelCase__: bool = field(default=lowerCAmelCase_ , metadata={"""help""": """Save result to a CSV file"""} )
lowerCamelCase__: bool = field(default=lowerCAmelCase_ , metadata={"""help""": """Save all print statements in a log file"""} )
lowerCamelCase__: bool = field(default=lowerCAmelCase_ , metadata={"""help""": """Whether to print environment information"""} )
lowerCamelCase__: bool = field(
default=lowerCAmelCase_ , metadata={
"""help""": (
"""Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use"""
""" multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled"""
""" for debugging / testing and on TPU."""
)
} , )
lowerCamelCase__: str = field(
default=F"""inference_time_{round(time() )}.csv""" , metadata={"""help""": """CSV filename used if saving time results to csv."""} , )
lowerCamelCase__: str = field(
default=F"""inference_memory_{round(time() )}.csv""" , metadata={"""help""": """CSV filename used if saving memory results to csv."""} , )
lowerCamelCase__: str = field(
default=F"""train_time_{round(time() )}.csv""" , metadata={"""help""": """CSV filename used if saving time results to csv for training."""} , )
lowerCamelCase__: str = field(
default=F"""train_memory_{round(time() )}.csv""" , metadata={"""help""": """CSV filename used if saving memory results to csv for training."""} , )
lowerCamelCase__: str = field(
default=F"""env_info_{round(time() )}.csv""" , metadata={"""help""": """CSV filename used if saving environment information."""} , )
lowerCamelCase__: str = field(
default=F"""log_{round(time() )}.csv""" , metadata={"""help""": """Log filename used if print statements are saved in log."""} , )
lowerCamelCase__: int = field(default=3 , metadata={"""help""": """Times an experiment will be run."""} )
lowerCamelCase__: bool = field(
default=lowerCAmelCase_ , metadata={
"""help""": (
"""Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain"""
""" model weights."""
)
} , )
def UpperCAmelCase( self : Any ):
warnings.warn(
F'''The class {self.__class__} is deprecated. Hugging Face Benchmarking utils'''
""" are deprecated in general and it is advised to use external Benchmarking libraries """
""" to benchmark Transformer models.""" , lowerCamelCase_ , )
def UpperCAmelCase( self : Union[str, Any] ):
return json.dumps(dataclasses.asdict(self ) , indent=2 )
@property
def UpperCAmelCase( self : List[str] ):
if len(self.models ) <= 0:
raise ValueError(
"""Please make sure you provide at least one model name / model identifier, *e.g.* `--models"""
""" bert-base-cased` or `args.models = ['bert-base-cased'].""" )
return self.models
@property
def UpperCAmelCase( self : Union[str, Any] ):
if not self.multi_process:
return False
elif self.is_tpu:
logger.info("""Multiprocessing is currently not possible on TPU.""" )
return False
else:
return True
| 478 | 1 |
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ ( __A : str ) -> str:
return " ".join(input_str.split()[::-1] )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 418 |
'''simple docstring'''
import platform
from argparse import ArgumentParser
import huggingface_hub
from .. import __version__ as version
from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
from . import BaseDiffusersCLICommand
def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> Optional[Any]:
return EnvironmentCommand()
class lowercase_ ( A ):
"""simple docstring"""
@staticmethod
def lowerCAmelCase_ ( __lowerCamelCase : ArgumentParser ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE = parser.add_parser("env" )
download_parser.set_defaults(func=__lowerCamelCase )
def lowerCAmelCase_ ( self : Union[str, Any] ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE = huggingface_hub.__version__
_SCREAMING_SNAKE_CASE = "not installed"
_SCREAMING_SNAKE_CASE = "NA"
if is_torch_available():
import torch
_SCREAMING_SNAKE_CASE = torch.__version__
_SCREAMING_SNAKE_CASE = torch.cuda.is_available()
_SCREAMING_SNAKE_CASE = "not installed"
if is_transformers_available():
import transformers
_SCREAMING_SNAKE_CASE = transformers.__version__
_SCREAMING_SNAKE_CASE = "not installed"
if is_accelerate_available():
import accelerate
_SCREAMING_SNAKE_CASE = accelerate.__version__
_SCREAMING_SNAKE_CASE = "not installed"
if is_xformers_available():
import xformers
_SCREAMING_SNAKE_CASE = xformers.__version__
_SCREAMING_SNAKE_CASE = {
"`diffusers` version": version,
"Platform": platform.platform(),
"Python version": platform.python_version(),
"PyTorch version (GPU?)": F"""{pt_version} ({pt_cuda_available})""",
"Huggingface_hub version": hub_version,
"Transformers version": transformers_version,
"Accelerate version": accelerate_version,
"xFormers version": xformers_version,
"Using GPU in script?": "<fill in>",
"Using distributed or parallel set-up in script?": "<fill in>",
}
print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n" )
print(self.format_dict(__lowerCamelCase ) )
return info
@staticmethod
def lowerCAmelCase_ ( __lowerCamelCase : List[Any] ):
"""simple docstring"""
return "\n".join([F"""- {prop}: {val}""" for prop, val in d.items()] ) + "\n"
| 418 | 1 |
'''simple docstring'''
import pytest
import datasets
# Import fixture modules as plugins
__lowerCamelCase : Tuple = ["tests.fixtures.files", "tests.fixtures.hub", "tests.fixtures.fsspec"]
def UpperCAmelCase_ ( lowerCAmelCase_ , lowerCAmelCase_ ):
"""simple docstring"""
for item in items:
if any(marker in item.keywords for marker in ["integration", "unit"] ):
continue
item.add_marker(pytest.mark.unit )
def UpperCAmelCase_ ( lowerCAmelCase_ ):
"""simple docstring"""
config.addinivalue_line("markers" , "torchaudio_latest: mark test to run with torchaudio>=0.12" )
@pytest.fixture(autouse=lowerCAmelCase_ )
def UpperCAmelCase_ ( lowerCAmelCase_ , lowerCAmelCase_ ):
"""simple docstring"""
lowercase = tmp_path_factory.getbasetemp() / "cache"
lowercase = test_hf_cache_home / "datasets"
lowercase = test_hf_cache_home / "metrics"
lowercase = test_hf_cache_home / "modules"
monkeypatch.setattr("datasets.config.HF_DATASETS_CACHE" , str(lowerCAmelCase_ ) )
monkeypatch.setattr("datasets.config.HF_METRICS_CACHE" , str(lowerCAmelCase_ ) )
monkeypatch.setattr("datasets.config.HF_MODULES_CACHE" , str(lowerCAmelCase_ ) )
lowercase = test_hf_datasets_cache / "downloads"
monkeypatch.setattr("datasets.config.DOWNLOADED_DATASETS_PATH" , str(lowerCAmelCase_ ) )
lowercase = test_hf_datasets_cache / "downloads" / "extracted"
monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(lowerCAmelCase_ ) )
@pytest.fixture(autouse=lowerCAmelCase_ , scope="session" )
def UpperCAmelCase_ ( ):
"""simple docstring"""
datasets.disable_progress_bar()
@pytest.fixture(autouse=lowerCAmelCase_ )
def UpperCAmelCase_ ( lowerCAmelCase_ ):
"""simple docstring"""
monkeypatch.setattr("datasets.config.HF_UPDATE_DOWNLOAD_COUNTS" , lowerCAmelCase_ )
@pytest.fixture
def UpperCAmelCase_ ( lowerCAmelCase_ ):
"""simple docstring"""
monkeypatch.setattr("sqlalchemy.util.deprecations.SILENCE_UBER_WARNING" , lowerCAmelCase_ )
| 459 |
'''simple docstring'''
import sacrebleu as scb
from packaging import version
from sacrebleu import CHRF
import datasets
__lowerCamelCase : Any = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n"
__lowerCamelCase : Dict = "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n"
__lowerCamelCase : List[Any] = "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n"
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class UpperCAmelCase ( datasets.Metric ):
def UpperCAmelCase__ (self : List[str] ) -> Union[str, Any]:
if version.parse(scb.__version__ ) < version.parse("1.4.12" ):
raise ImportWarning(
"To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"
"You can install it with `pip install \"sacrebleu>=1.4.12\"`." )
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , homepage="https://github.com/mjpost/sacreBLEU#chrf--chrf" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"predictions": datasets.Value("string" , id="sequence" ),
"references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ),
} ) , codebase_urls=["https://github.com/mjpost/sacreBLEU#chrf--chrf"] , reference_urls=[
"https://github.com/m-popovic/chrF",
] , )
def UpperCAmelCase__ (self : Tuple , A__ : Dict , A__ : Tuple , A__ : int = CHRF.CHAR_ORDER , A__ : int = CHRF.WORD_ORDER , A__ : int = CHRF.BETA , A__ : bool = False , A__ : bool = False , A__ : bool = False , ) -> List[str]:
lowercase = len(references[0] )
if any(len(A__ ) != references_per_prediction for refs in references ):
raise ValueError("Sacrebleu requires the same number of references for each prediction" )
lowercase = [[refs[i] for refs in references] for i in range(A__ )]
lowercase = CHRF(A__ , A__ , A__ , A__ , A__ , A__ )
lowercase = sb_chrf.corpus_score(A__ , A__ )
return {
"score": output.score,
"char_order": output.char_order,
"word_order": output.word_order,
"beta": output.beta,
}
| 459 | 1 |
import json
import os
import unittest
from typing import Tuple
from transformers import WavaVecaPhonemeCTCTokenizer
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.models.wavaveca_phoneme.tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizerOutput
from transformers.testing_utils import require_phonemizer
from ...test_tokenization_common import TokenizerTesterMixin
@require_phonemizer
class _a ( UpperCAmelCase__ , unittest.TestCase ):
"""simple docstring"""
A_ = WavaVecaPhonemeCTCTokenizer
A_ = False
def _UpperCAmelCase ( self ) -> Optional[int]:
super().setUp()
UpperCamelCase_ = (
'<s> <pad> </s> <unk> n s t ə l a i k d m ɛ ɾ e ɪ p o ɐ z ð f j v b ɹ ʁ ʊ iː r w ʌ u ɡ æ aɪ ʃ h ɔ ɑː '
'ŋ ɚ eɪ β uː y ɑ̃ oʊ ᵻ eː θ aʊ ts oː ɔ̃ ɣ ɜ ɑ dʒ əl x ɜː ç ʒ tʃ ɔː ɑːɹ ɛ̃ ʎ ɔːɹ ʋ aː ɕ œ ø oːɹ ɲ yː '
'ʔ iə i5 s. tɕ ?? nʲ ɛː œ̃ ɭ ɔø ʑ tʲ ɨ ɛɹ ts. rʲ ɪɹ ɭʲ i.5 ɔɪ q sʲ u5 ʊɹ iɜ a5 iɛ5 øː ʕ ja əɜ th ɑ5 '
'oɪ dʲ ə5 tɕh ts.h mʲ ɯ dʑ vʲ e̞ tʃʲ ei5 o5 onɡ5 ɑu5 iɑ5 ai5 aɪɚ kh ə1 ʐ i2 ʉ ħ t[ aɪə ʲ ju ə2 u2 oɜ '
'pː iɛɜ ou5 y5 uɜ tː uo5 d[ uoɜ tsh ɑɜ ɵ i̪5 uei5 ɟ aɜ ɑɨ i.ɜ eʊ o2 ɐ̃ ä pʲ kʲ n̩ ɒ ph ɑu2 uɨ əɪ ɫ ɬ '
'yɜ bʲ ɑ2 s̪ aiɜ χ ɐ̃ʊ̃ 1 ə4 yæɜ a2 ɨː t̪ iouɜ ũ onɡɜ aɨ iɛ2 ɔɨ ɑuɜ o̞ ei2 iou2 c kː y2 ɖ oe dˤ yɛɜ '
'əʊ S ɡʲ onɡ2 u" eiɜ ʈ ɯᵝ iou5 dZ r̝̊ i.2 tS s^ ʝ yə5 iɑɜ uə5 pf ɨu iɑ2 ou2 ər2 fʲ ai2 r̝ uəɜ ɳ əɨ '
'ua5 uɪ ɽ bː yu5 uo2 yɛ5 l̩ ɻ ərɜ ʂ i̪2 ouɜ uaɜ a. a.ː yæ5 dː r̩ ee ɪu ər5 i̪ ɜ æi u: i.ː t^ o1 ɪ^ '
'ai ueiɜ æː ɛɪ eə i. ɴ ie ua2 ɑ1 o4 tʃː o: ɑ: u1 N i̪1 au yæ2 u. qː yəɜ y: kʰ tʃʰ iʊ sx õ uo tʰ '
'uai5 bʰ u.ː uə2 ʊə d^ s̪ː yiɜ dʰ r. oe: i1 ɟː yu2 nʲʲ i̪4 uei2 tsʲ ɸ ĩ ɑ4 t̪ː eɑ u4 e: tsː ʈʰ ɡʰ '
'ɯɯ dʒʲ ʂʲ X ɵː uaiɜ tɕʲ ã t^ː ẽː yɛ2 cː i.1 ɛʊ dˤdˤ dʒː i4 ɡː yi ɕʲ ɟʰ pʰ dʑʲ yuɜ ua1 ua4 æiː ɐɐ '
'ui iou1 ʊː a1 iou4 cʰ iɛ1 yə2 ɖʰ ẽ ʒʲ ää ər4 iːː ɪː iɑ1 ər1 œː øi ɪuː cʰcʰ əː1 iː1 ũ kʰː o̞o̞ xʲ '
'ou1 iɛ4 e̞e̞ y1 dzː dʲʲ dʰː ɯᵝɯᵝ lː uo1 i.4 i: yɛ5ʲ a4'
).split(' ' )
UpperCamelCase_ = dict(zip(_UpperCAmelCase , range(len(_UpperCAmelCase ) ) ) )
UpperCamelCase_ = {'pad_token': '<pad>', 'unk_token': '<unk>', 'bos_token': '<s>', 'eos_token': '</s>'}
UpperCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] )
with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp:
fp.write(json.dumps(_UpperCAmelCase ) + '\n' )
def _UpperCAmelCase ( self , _UpperCAmelCase , _UpperCAmelCase=False , _UpperCAmelCase=20 , _UpperCAmelCase=5 ) -> Tuple[str, list]:
UpperCamelCase_ = [(i, tokenizer.decode([i] , clean_up_tokenization_spaces=_UpperCAmelCase )) for i in range(len(_UpperCAmelCase ) )]
UpperCamelCase_ = list(filter(lambda _UpperCAmelCase : [t[0]] == tokenizer.encode(t[1] , do_phonemize=_UpperCAmelCase ) , _UpperCAmelCase ) )
if max_length is not None and len(_UpperCAmelCase ) > max_length:
UpperCamelCase_ = toks[:max_length]
if min_length is not None and len(_UpperCAmelCase ) < min_length and len(_UpperCAmelCase ) > 0:
while len(_UpperCAmelCase ) < min_length:
UpperCamelCase_ = toks + toks
# toks_str = [t[1] for t in toks]
UpperCamelCase_ = [t[0] for t in toks]
# Ensure consistency
UpperCamelCase_ = tokenizer.decode(_UpperCAmelCase , clean_up_tokenization_spaces=_UpperCAmelCase )
if " " not in output_txt and len(_UpperCAmelCase ) > 1:
UpperCamelCase_ = (
tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=_UpperCAmelCase )
+ ' '
+ tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=_UpperCAmelCase )
)
if with_prefix_space:
UpperCamelCase_ = ' ' + output_txt
UpperCamelCase_ = tokenizer.encode(_UpperCAmelCase , add_special_tokens=_UpperCAmelCase )
return output_txt, output_ids
def _UpperCAmelCase ( self , **_UpperCAmelCase ) -> Optional[int]:
kwargs.update(self.special_tokens_map )
return WavaVecaPhonemeCTCTokenizer.from_pretrained(self.tmpdirname , **_UpperCAmelCase )
def _UpperCAmelCase ( self ) -> Dict:
UpperCamelCase_ = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' )
# check adding a single token
tokenizer.add_tokens('xxx' )
UpperCamelCase_ = tokenizer('m xxx ɪ' , do_phonemize=_UpperCAmelCase ).input_ids
self.assertEqual(_UpperCAmelCase , [13, 392, 17] ) # xxx should be last token
tokenizer.add_tokens(['aaa', 'bbb', 'ccc'] )
UpperCamelCase_ = tokenizer('m aaa ɪ ccc' , do_phonemize=_UpperCAmelCase ).input_ids
self.assertEqual(_UpperCAmelCase , [13, 393, 17, 395] ) # aaa and ccc should be after xxx and 2 after aaa
UpperCamelCase_ = tokenizer('maɪ c' , do_phonemize=_UpperCAmelCase ).input_ids
self.assertEqual(_UpperCAmelCase , [3, 200] ) # mai should be <unk> (=3)
def _UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase_ = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' )
UpperCamelCase_ = 'Hello how are you'
UpperCamelCase_ = tokenizer.phonemize(_UpperCAmelCase , phonemizer_lang='en-us' )
self.assertEqual(_UpperCAmelCase , 'h ə l oʊ h aʊ ɑːɹ j uː' )
def _UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase_ = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' )
UpperCamelCase_ = 'Hello how are you'
UpperCamelCase_ = tokenizer.phonemize(_UpperCAmelCase , phonemizer_lang='en-us' )
self.assertEqual(tokenizer(_UpperCAmelCase ).input_ids , tokenizer(_UpperCAmelCase , do_phonemize=_UpperCAmelCase ).input_ids )
def _UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase_ = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' )
UpperCamelCase_ = 'Hello how are you'
UpperCamelCase_ = tokenizer.phonemize(_UpperCAmelCase , phonemizer_lang='en-us' )
UpperCamelCase_ = tokenizer.decode(tokenizer(_UpperCAmelCase ).input_ids )
self.assertEqual(_UpperCAmelCase , _UpperCAmelCase )
def _UpperCAmelCase ( self ) -> str:
UpperCamelCase_ = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' )
UpperCamelCase_ = [
[11, 5, 15, tokenizer.pad_token_id, 15, 8, 98],
[24, 22, 5, 24, 22, 5, 77],
]
UpperCamelCase_ = tokenizer.decode(sample_ids[0] )
UpperCamelCase_ = tokenizer.batch_decode(_UpperCAmelCase )
self.assertEqual(_UpperCAmelCase , batch_tokens[0] )
self.assertEqual(_UpperCAmelCase , ['k s ɾ ɾ l ɭʲ', 'j ð s j ð s oːɹ'] )
def _UpperCAmelCase ( self ) -> int:
UpperCamelCase_ = self.tokenizer_class.from_pretrained(
'facebook/wav2vec2-lv-60-espeak-cv-ft' , word_delimiter_token='|' )
tokenizer.add_tokens('|' )
UpperCamelCase_ = 'Hello how are you'
UpperCamelCase_ = tokenizer.phonemize(_UpperCAmelCase , phonemizer_lang='en-us' )
self.assertEqual(_UpperCAmelCase , 'h ə l oʊ | h aʊ | ɑːɹ | j uː |' )
def _UpperCAmelCase ( self ) -> Any:
UpperCamelCase_ = self.tokenizer_class.from_pretrained(
'facebook/wav2vec2-lv-60-espeak-cv-ft' , word_delimiter_token='|' )
tokenizer.add_tokens('|' )
UpperCamelCase_ = 'Hello how are you'
UpperCamelCase_ = tokenizer.phonemize(_UpperCAmelCase , phonemizer_lang='en-us' )
self.assertEqual(tokenizer(_UpperCAmelCase ).input_ids , tokenizer(_UpperCAmelCase , do_phonemize=_UpperCAmelCase ).input_ids )
def _UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase_ = self.tokenizer_class.from_pretrained(
'facebook/wav2vec2-lv-60-espeak-cv-ft' , word_delimiter_token='|' )
tokenizer.add_tokens('|' )
# fmt: off
UpperCamelCase_ = [
[11, 5, 15, tokenizer.pad_token_id, tokenizer.word_delimiter_token_id, 15, 8, tokenizer.word_delimiter_token_id, 98],
[tokenizer.word_delimiter_token_id, 24, 22, tokenizer.word_delimiter_token_id, 5, 24, 22, 5, 77],
]
# fmt: on
# decode with word_del_token filter
UpperCamelCase_ = tokenizer.decode(sample_ids[0] )
UpperCamelCase_ = tokenizer.batch_decode(_UpperCAmelCase )
self.assertEqual(_UpperCAmelCase , batch_tokens[0] )
self.assertEqual(_UpperCAmelCase , ['k s ɾ ɾ l ɭʲ', 'j ð s j ð s oːɹ'] )
# decode with no word_del_token filter
UpperCamelCase_ = tokenizer.decode(sample_ids[0] , filter_word_delimiter_token=_UpperCAmelCase )
UpperCamelCase_ = tokenizer.batch_decode(_UpperCAmelCase , filter_word_delimiter_token=_UpperCAmelCase )
self.assertEqual(_UpperCAmelCase , batch_tokens[0] )
self.assertEqual(_UpperCAmelCase , ['k s ɾ | ɾ l | ɭʲ', '| j ð | s j ð s oːɹ'] )
def _UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase_ = self.tokenizer_class.from_pretrained(
'facebook/wav2vec2-lv-60-espeak-cv-ft' , word_delimiter_token='|' )
tokenizer.add_tokens('|' )
UpperCamelCase_ = 'Hello how are you'
UpperCamelCase_ = tokenizer.phonemize(_UpperCAmelCase , phonemizer_lang='en-us' )
UpperCamelCase_ = tokenizer.decode(tokenizer(_UpperCAmelCase ).input_ids , filter_word_delimiter_token=_UpperCAmelCase )
self.assertEqual(_UpperCAmelCase , _UpperCAmelCase )
def _UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase_ = self.tokenizer_class.from_pretrained(
'facebook/wav2vec2-lv-60-espeak-cv-ft' , word_delimiter_token='|' )
tokenizer.add_tokens('|' )
UpperCamelCase_ = 'Hello how are you'
UpperCamelCase_ = tokenizer.phonemize(_UpperCAmelCase , phonemizer_lang='en-us' )
UpperCamelCase_ = tokenizer.decode(tokenizer(_UpperCAmelCase ).input_ids , filter_word_delimiter_token=_UpperCAmelCase )
self.assertEqual(' '.join([p.strip() for p in phonemes.split(' |' )] ).strip() , _UpperCAmelCase )
def _UpperCAmelCase ( self ) -> Any:
UpperCamelCase_ = self.tokenizer_class.from_pretrained(
'facebook/wav2vec2-lv-60-espeak-cv-ft' , word_delimiter_token=_UpperCAmelCase )
UpperCamelCase_ = 'Hello how are you'
UpperCamelCase_ = tokenizer(_UpperCAmelCase , phonemizer_lang='en-us' ).input_ids
UpperCamelCase_ = tokenizer(_UpperCAmelCase , phonemizer_lang='fr-fr' ).input_ids
self.assertNotEqual(_UpperCAmelCase , _UpperCAmelCase )
UpperCamelCase_ = tokenizer.decode(_UpperCAmelCase )
UpperCamelCase_ = tokenizer.decode(_UpperCAmelCase )
self.assertEqual(_UpperCAmelCase , 'h ə l oʊ h aʊ ɑːɹ j uː' )
self.assertEqual(_UpperCAmelCase , 'ɛ l o h aʊ a ʁ j u' )
def _UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase_ = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' )
UpperCamelCase_ = 'Hello how Are you'
UpperCamelCase_ = 'hello how are you'
UpperCamelCase_ = tokenizer(_UpperCAmelCase ).input_ids
UpperCamelCase_ = tokenizer(_UpperCAmelCase ).input_ids
self.assertEqual(_UpperCAmelCase , _UpperCAmelCase )
def _UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase_ = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' )
tokenizer.add_tokens(['!', '?'] )
tokenizer.add_special_tokens({'cls_token': '$$$'} )
# fmt: off
UpperCamelCase_ = [
[11, 5, 15, tokenizer.pad_token_id, 15, 8, 98, 392, 392, 393, 392, 392, 393, 394, 394],
[24, 22, 5, 24, 22, 5, 77, tokenizer.pad_token_id, 394, 394],
]
# fmt: on
UpperCamelCase_ = tokenizer.batch_decode(_UpperCAmelCase )
self.assertEqual(_UpperCAmelCase , ['k s ɾ ɾ l ɭʲ!?!? $$$', 'j ð s j ð s oːɹ $$$'] )
@staticmethod
def _UpperCAmelCase ( _UpperCAmelCase , _UpperCAmelCase ) -> Union[str, Any]:
UpperCamelCase_ = [d[key] for d in offsets]
return retrieved_list
def _UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase_ = self.get_tokenizer(word_delimiter_token='|' )
tokenizer.add_tokens('|' )
# fmt: off
# ksssɾɾ|ɾɾ<pad>ɾɾ|<pad>ɾlll|ɭʲ -> k s ɾ ɾ | ɾ l | ɭʲ"
UpperCamelCase_ = [11, 5, 5, 5, 15, 15, tokenizer.pad_token_id, 15, 15, tokenizer.word_delimiter_token_id, tokenizer.pad_token_id, 15, 8, 8, 8, tokenizer.word_delimiter_token_id, 98]
# fmt: on
UpperCamelCase_ = tokenizer.decode(_UpperCAmelCase , output_char_offsets=_UpperCAmelCase , filter_word_delimiter_token=_UpperCAmelCase )
# check Wav2Vec2CTCTokenizerOutput keys for char
self.assertEqual(len(outputs.keys() ) , 2 )
self.assertTrue('text' in outputs )
self.assertTrue('char_offsets' in outputs )
self.assertTrue(isinstance(_UpperCAmelCase , _UpperCAmelCase ) )
# check that order of chars is correct and identical for both outputs
self.assertEqual(' '.join(self.get_from_offsets(outputs['char_offsets'] , 'char' ) ) , outputs.text )
self.assertListEqual(
self.get_from_offsets(outputs['char_offsets'] , 'char' ) , ['k', 's', 'ɾ', 'ɾ', '|', 'ɾ', 'l', '|', 'ɭʲ'] )
# check that offsets are actually correct for char
# 0-1 is 11, 1-4 is 5, 4-6 is first 15, 6-7 is <pad> (thus not shown), 7-9 is second 15, 9-10 is word_delimiter_token,
# 10-11 is <pad> (thus not shown), 11-12 is third 15, 12-15 is 8, 15-16 is word_delimiter_token, 16-17 is 98
self.assertListEqual(
self.get_from_offsets(outputs['char_offsets'] , 'start_offset' ) , [0, 1, 4, 7, 9, 11, 12, 15, 16] )
self.assertListEqual(
self.get_from_offsets(outputs['char_offsets'] , 'end_offset' ) , [1, 4, 6, 9, 10, 12, 15, 16, 17] )
def _UpperCAmelCase ( self ) -> List[str]:
UpperCamelCase_ = self.get_tokenizer(word_delimiter_token='|' )
def check_list_tuples_equal(_UpperCAmelCase , _UpperCAmelCase ):
self.assertTrue(isinstance(_UpperCAmelCase , _UpperCAmelCase ) )
self.assertTrue(isinstance(outputs_list[0] , _UpperCAmelCase ) )
# transform list to ModelOutput
UpperCamelCase_ = WavaVecaPhonemeCTCTokenizerOutput(
{k: [d[k] for d in outputs_list] for k in outputs_list[0]} )
self.assertListEqual(outputs_batch['text'] , outputs_batch_a['text'] )
def recursive_check(_UpperCAmelCase , _UpperCAmelCase ):
if isinstance(_UpperCAmelCase , _UpperCAmelCase ):
[recursive_check(_UpperCAmelCase , _UpperCAmelCase ) for la, la in zip(_UpperCAmelCase , _UpperCAmelCase )]
self.assertEqual(_UpperCAmelCase , _UpperCAmelCase )
if "char_offsets" in outputs_batch:
recursive_check(outputs_batch['char_offsets'] , outputs_batch_a['char_offsets'] )
# fmt: off
UpperCamelCase_ = [
[11, 5, 15, tokenizer.pad_token_id, 15, 4, 8, 98, 32, 32, 32, 32, 4, 33, tokenizer.word_delimiter_token_id, 32, 32, 33, 34, 34],
[24, 22, 5, tokenizer.word_delimiter_token_id, tokenizer.word_delimiter_token_id, 24, 22, 22, 22, 4, 5, 77, tokenizer.pad_token_id, 22, 22, 4, 34, 34, 34, 34],
]
# fmt: on
# We assume that `decode` works as expected. All we will check now is
# the output type is correct and the output is identical to `decode`
# char
UpperCamelCase_ = tokenizer.batch_decode(_UpperCAmelCase , output_char_offsets=_UpperCAmelCase )
UpperCamelCase_ = [tokenizer.decode(_UpperCAmelCase , output_char_offsets=_UpperCAmelCase ) for ids in sample_ids]
check_list_tuples_equal(_UpperCAmelCase , _UpperCAmelCase )
@unittest.skip('Wav2Vec2PhonemeTokenizer always lower cases letters to correctly map to phonemes' )
def _UpperCAmelCase ( self ) -> List[Any]:
pass
@unittest.skip('Wav2Vec2PhonemeTokenizer always puts spaces between phonemes' )
def _UpperCAmelCase ( self ) -> List[str]:
pass
@unittest.skip('encodes to text to ids, but decodes ids to phonemes -> not possible to have internal consistency' )
def _UpperCAmelCase ( self ) -> List[Any]:
pass
@unittest.skip('Wav2Vec2PhonemeModel has no max model length => no testing' )
def _UpperCAmelCase ( self ) -> List[Any]:
pass
def _UpperCAmelCase ( self ) -> str:
UpperCamelCase_ = self.get_tokenizers(do_lower_case=_UpperCAmelCase )
for tokenizer in tokenizers:
with self.subTest(f"""{tokenizer.__class__.__name__}""" ):
UpperCamelCase_ = tokenizer.vocab_size
UpperCamelCase_ = len(_UpperCAmelCase )
self.assertNotEqual(_UpperCAmelCase , 0 )
# We usually have added tokens from the start in tests because our vocab fixtures are
# smaller than the original vocabs - let's not assert this
# self.assertEqual(vocab_size, all_size)
UpperCamelCase_ = ['aaaaa bbbbbb', 'cccccccccdddddddd']
UpperCamelCase_ = tokenizer.add_tokens(_UpperCAmelCase )
UpperCamelCase_ = tokenizer.vocab_size
UpperCamelCase_ = len(_UpperCAmelCase )
self.assertNotEqual(_UpperCAmelCase , 0 )
self.assertEqual(_UpperCAmelCase , _UpperCAmelCase )
self.assertEqual(_UpperCAmelCase , len(_UpperCAmelCase ) )
self.assertEqual(_UpperCAmelCase , all_size + len(_UpperCAmelCase ) )
UpperCamelCase_ = tokenizer.encode('aaaaa bbbbbb low cccccccccdddddddd l' , add_special_tokens=_UpperCAmelCase )
self.assertGreaterEqual(len(_UpperCAmelCase ) , 4 )
self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 )
self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 )
UpperCamelCase_ = {'eos_token': '>>>>|||<||<<|<<', 'pad_token': '<<<<<|||>|>>>>|>'}
UpperCamelCase_ = tokenizer.add_special_tokens(_UpperCAmelCase )
UpperCamelCase_ = tokenizer.vocab_size
UpperCamelCase_ = len(_UpperCAmelCase )
self.assertNotEqual(_UpperCAmelCase , 0 )
self.assertEqual(_UpperCAmelCase , _UpperCAmelCase )
self.assertEqual(_UpperCAmelCase , len(_UpperCAmelCase ) )
self.assertEqual(_UpperCAmelCase , all_size_a + len(_UpperCAmelCase ) )
UpperCamelCase_ = tokenizer.encode(
'>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l' , add_special_tokens=_UpperCAmelCase )
self.assertGreaterEqual(len(_UpperCAmelCase ) , 6 )
self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 )
self.assertGreater(tokens[0] , tokens[1] )
self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 )
self.assertGreater(tokens[-3] , tokens[-4] )
self.assertEqual(tokens[0] , tokenizer.eos_token_id )
self.assertEqual(tokens[-3] , tokenizer.pad_token_id )
@unittest.skip('The tokenizer shouldn\'t be used to encode input IDs (except for labels), only to decode.' )
def _UpperCAmelCase ( self ) -> List[Any]:
pass
@unittest.skip('The tokenizer shouldn\'t be used to encode input IDs (except for labels), only to decode.' )
def _UpperCAmelCase ( self ) -> List[Any]:
pass
def _UpperCAmelCase ( self ) -> Optional[int]:
# The default common tokenizer tests assumes that the output of `convert_tokens_to_string` is a string which
# is not the case for Wav2Vec2PhonemeCTCTokenizer.
UpperCamelCase_ = self.get_tokenizers(fast=_UpperCAmelCase , do_lower_case=_UpperCAmelCase )
for tokenizer in tokenizers:
with self.subTest(f"""{tokenizer.__class__.__name__}""" ):
UpperCamelCase_ = ['ð', 'ɪ', 's', 'ɪ', 'z', 'ɐ', 't', 'ɛ', 'k', 's', 't']
UpperCamelCase_ = tokenizer.convert_tokens_to_string(_UpperCAmelCase )
self.assertIsInstance(output['text'] , _UpperCAmelCase )
| 23 |
"""simple docstring"""
import copy
from typing import Any, Dict, List, Optional, Union
import numpy as np
import torch
from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging
A = logging.get_logger(__name__)
class a__ ( __magic_name__ ):
lowercase_ = ["input_features", "is_longer"]
def __init__( self : List[str] , UpperCamelCase_ : Dict=64 , UpperCamelCase_ : Tuple=48000 , UpperCamelCase_ : List[Any]=480 , UpperCamelCase_ : List[str]=10 , UpperCamelCase_ : str=1024 , UpperCamelCase_ : List[str]=0.0 , UpperCamelCase_ : Optional[int]=False , UpperCamelCase_ : float = 0 , UpperCamelCase_ : float = 14000 , UpperCamelCase_ : int = None , UpperCamelCase_ : str = "fusion" , UpperCamelCase_ : str = "repeatpad" , **UpperCamelCase_ : Optional[Any] , ):
"""simple docstring"""
super().__init__(
feature_size=UpperCamelCase_ , sampling_rate=UpperCamelCase_ , padding_value=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , **UpperCamelCase_ , )
__UpperCAmelCase : Union[str, Any] = top_db
__UpperCAmelCase : Optional[Any] = truncation
__UpperCAmelCase : str = padding
__UpperCAmelCase : int = fft_window_size
__UpperCAmelCase : str = (fft_window_size >> 1) + 1
__UpperCAmelCase : List[Any] = hop_length
__UpperCAmelCase : Optional[Any] = max_length_s
__UpperCAmelCase : Tuple = max_length_s * sampling_rate
__UpperCAmelCase : str = sampling_rate
__UpperCAmelCase : int = frequency_min
__UpperCAmelCase : Optional[Any] = frequency_max
__UpperCAmelCase : Any = mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase_ , min_frequency=UpperCamelCase_ , max_frequency=UpperCamelCase_ , sampling_rate=UpperCamelCase_ , norm=UpperCamelCase_ , mel_scale="htk" , )
__UpperCAmelCase : Any = mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCamelCase_ , min_frequency=UpperCamelCase_ , max_frequency=UpperCamelCase_ , sampling_rate=UpperCamelCase_ , norm="slaney" , mel_scale="slaney" , )
def a_ ( self : Dict):
"""simple docstring"""
__UpperCAmelCase : Dict = copy.deepcopy(self.__dict__)
__UpperCAmelCase : str = self.__class__.__name__
if "mel_filters" in output:
del output["mel_filters"]
if "mel_filters_slaney" in output:
del output["mel_filters_slaney"]
return output
def a_ ( self : int , UpperCamelCase_ : np.array , UpperCamelCase_ : Optional[np.array] = None):
"""simple docstring"""
__UpperCAmelCase : List[Any] = spectrogram(
UpperCamelCase_ , window_function(self.fft_window_size , "hann") , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=UpperCamelCase_ , log_mel="dB" , )
return log_mel_spectrogram.T
def a_ ( self : List[Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : int):
"""simple docstring"""
__UpperCAmelCase : Optional[Any] = np.array_split(list(range(0 , total_frames - chunk_frames + 1)) , 3)
if len(ranges[1]) == 0:
# if the audio is too short, we just use the first chunk
__UpperCAmelCase : str = [0]
if len(ranges[2]) == 0:
# if the audio is too short, we just use the first chunk
__UpperCAmelCase : Dict = [0]
# randomly choose index for each part
__UpperCAmelCase : Dict = np.random.choice(ranges[0])
__UpperCAmelCase : List[str] = np.random.choice(ranges[1])
__UpperCAmelCase : List[Any] = np.random.choice(ranges[2])
__UpperCAmelCase : List[Any] = mel[idx_front : idx_front + chunk_frames, :]
__UpperCAmelCase : List[str] = mel[idx_middle : idx_middle + chunk_frames, :]
__UpperCAmelCase : List[str] = mel[idx_back : idx_back + chunk_frames, :]
__UpperCAmelCase : Tuple = torch.tensor(mel[None, None, :])
__UpperCAmelCase : Union[str, Any] = torch.nn.functional.interpolate(
UpperCamelCase_ , size=[chunk_frames, 64] , mode="bilinear" , align_corners=UpperCamelCase_)
__UpperCAmelCase : Union[str, Any] = mel_shrink[0][0].numpy()
__UpperCAmelCase : Optional[int] = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0)
return mel_fusion
def a_ ( self : Optional[Any] , UpperCamelCase_ : np.array , UpperCamelCase_ : Any , UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
if waveform.shape[0] > max_length:
if truncation == "rand_trunc":
__UpperCAmelCase : List[str] = True
# random crop to max_length (for compatibility) -> this should be handled by self.pad
__UpperCAmelCase : List[Any] = len(UpperCamelCase_) - max_length
__UpperCAmelCase : int = np.random.randint(0 , overflow + 1)
__UpperCAmelCase : Union[str, Any] = waveform[idx : idx + max_length]
__UpperCAmelCase : Union[str, Any] = self._np_extract_fbank_features(UpperCamelCase_ , self.mel_filters_slaney)[None, :]
elif truncation == "fusion":
__UpperCAmelCase : Any = self._np_extract_fbank_features(UpperCamelCase_ , self.mel_filters)
__UpperCAmelCase : Dict = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed
__UpperCAmelCase : Tuple = mel.shape[0]
if chunk_frames == total_frames:
# there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
# In this case, we just use the whole audio.
__UpperCAmelCase : List[str] = np.stack([mel, mel, mel, mel] , axis=0)
__UpperCAmelCase : Any = False
else:
__UpperCAmelCase : List[str] = self._random_mel_fusion(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_)
__UpperCAmelCase : Union[str, Any] = True
else:
raise NotImplementedError(F"data_truncating {truncation} not implemented")
else:
__UpperCAmelCase : Optional[Any] = False
# only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
if waveform.shape[0] < max_length:
if padding == "repeat":
__UpperCAmelCase : Tuple = int(max_length / len(UpperCamelCase_))
__UpperCAmelCase : List[str] = np.stack(np.tile(UpperCamelCase_ , n_repeat + 1))[:max_length]
if padding == "repeatpad":
__UpperCAmelCase : Union[str, Any] = int(max_length / len(UpperCamelCase_))
__UpperCAmelCase : Optional[Any] = np.stack(np.tile(UpperCamelCase_ , UpperCamelCase_))
__UpperCAmelCase : int = np.pad(UpperCamelCase_ , (0, max_length - waveform.shape[0]) , mode="constant" , constant_values=0)
if truncation == "fusion":
__UpperCAmelCase : Any = self._np_extract_fbank_features(UpperCamelCase_ , self.mel_filters)
__UpperCAmelCase : List[Any] = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0)
else:
__UpperCAmelCase : Optional[int] = self._np_extract_fbank_features(UpperCamelCase_ , self.mel_filters_slaney)[None, :]
return input_mel, longer
def __call__( self : Dict , UpperCamelCase_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCamelCase_ : str = None , UpperCamelCase_ : Optional[str] = None , UpperCamelCase_ : Optional[int] = None , UpperCamelCase_ : Optional[int] = None , UpperCamelCase_ : Optional[Union[str, TensorType]] = None , **UpperCamelCase_ : Any , ):
"""simple docstring"""
__UpperCAmelCase : int = truncation if truncation is not None else self.truncation
__UpperCAmelCase : Optional[Any] = padding if padding else self.padding
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
F"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"
F" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"
F" was sampled with {self.sampling_rate} and not {sampling_rate}.")
else:
logger.warning(
"It is strongly recommended to pass the `sampling_rate` argument to this function. "
"Failing to do so can result in silent errors that might be hard to debug.")
__UpperCAmelCase : List[str] = isinstance(UpperCamelCase_ , np.ndarray) and len(raw_speech.shape) > 1
if is_batched_numpy and len(raw_speech.shape) > 2:
raise ValueError(F"Only mono-channel audio is supported for input to {self}")
__UpperCAmelCase : str = is_batched_numpy or (
isinstance(UpperCamelCase_ , (list, tuple)) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list)))
)
if is_batched:
__UpperCAmelCase : Dict = [np.asarray(UpperCamelCase_ , dtype=np.floataa) for speech in raw_speech]
elif not is_batched and not isinstance(UpperCamelCase_ , np.ndarray):
__UpperCAmelCase : Tuple = np.asarray(UpperCamelCase_ , dtype=np.floataa)
elif isinstance(UpperCamelCase_ , np.ndarray) and raw_speech.dtype is np.dtype(np.floataa):
__UpperCAmelCase : Optional[int] = raw_speech.astype(np.floataa)
# always return batch
if not is_batched:
__UpperCAmelCase : int = [np.asarray(UpperCamelCase_)]
# convert to mel spectrogram, truncate and pad if needed.
__UpperCAmelCase : Optional[int] = [
self._get_input_mel(UpperCamelCase_ , max_length if max_length else self.nb_max_samples , UpperCamelCase_ , UpperCamelCase_)
for waveform in raw_speech
]
__UpperCAmelCase : Tuple = []
__UpperCAmelCase : List[Any] = []
for mel, longer in padded_inputs:
input_mel.append(UpperCamelCase_)
is_longer.append(UpperCamelCase_)
if truncation == "fusion" and sum(UpperCamelCase_) == 0:
# if no audio is longer than 10s, then randomly select one audio to be longer
__UpperCAmelCase : Any = np.random.randint(0 , len(UpperCamelCase_))
__UpperCAmelCase : Optional[int] = True
if isinstance(input_mel[0] , UpperCamelCase_):
__UpperCAmelCase : Tuple = [np.asarray(UpperCamelCase_ , dtype=np.floataa) for feature in input_mel]
# is_longer is a list of bool
__UpperCAmelCase : List[str] = [[longer] for longer in is_longer]
__UpperCAmelCase : Optional[int] = {"input_features": input_mel, "is_longer": is_longer}
__UpperCAmelCase : Optional[int] = BatchFeature(UpperCamelCase_)
if return_tensors is not None:
__UpperCAmelCase : Any = input_features.convert_to_tensors(UpperCamelCase_)
return input_features
| 77 | 0 |
'''simple docstring'''
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
UpperCAmelCase_ : List[str] = True
except ImportError:
UpperCAmelCase_ : int = False
try:
from torch.hub import _get_torch_home
UpperCAmelCase_ : Optional[int] = _get_torch_home()
except ImportError:
UpperCAmelCase_ : str = os.path.expanduser(
os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch'))
)
UpperCAmelCase_ : int = os.path.join(torch_cache_home, 'transformers')
UpperCAmelCase_ : List[Any] = 'https://cdn.huggingface.co'
UpperCAmelCase_ : str = 'https://s3.amazonaws.com/models.huggingface.co/bert'
UpperCAmelCase_ : Optional[int] = '/'.join(str(Path(__file__).resolve()).split('/')[:-1])
UpperCAmelCase_ : Optional[int] = os.path.join(PATH, 'config.yaml')
UpperCAmelCase_ : Optional[Any] = os.path.join(PATH, 'attributes.txt')
UpperCAmelCase_ : int = os.path.join(PATH, 'objects.txt')
UpperCAmelCase_ : List[Any] = os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path)
UpperCAmelCase_ : Optional[Any] = os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE)
UpperCAmelCase_ : str = os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE)
UpperCAmelCase_ : Tuple = 'pytorch_model.bin'
UpperCAmelCase_ : int = 'config.yaml'
def _lowercase ( UpperCamelCase__ : Any=OBJECTS, UpperCamelCase__ : Tuple=ATTRIBUTES ):
__A : List[Any] = []
with open(UpperCamelCase__ ) as f:
for object in f.readlines():
vg_classes.append(object.split(',' )[0].lower().strip() )
__A : Union[str, Any] = []
with open(UpperCamelCase__ ) as f:
for object in f.readlines():
vg_attrs.append(object.split(',' )[0].lower().strip() )
return vg_classes, vg_attrs
def _lowercase ( UpperCamelCase__ : List[Any] ):
__A : Optional[int] = OrderedDict()
with open(UpperCamelCase__, 'rb' ) as f:
__A : Optional[int] = pkl.load(UpperCamelCase__ )['model']
for k in copy.deepcopy(list(ckp.keys() ) ):
__A : Optional[Any] = ckp.pop(UpperCamelCase__ )
if isinstance(UpperCamelCase__, np.ndarray ):
__A : List[str] = torch.tensor(UpperCamelCase__ )
else:
assert isinstance(UpperCamelCase__, torch.tensor ), type(UpperCamelCase__ )
__A : Tuple = v
return r
class _lowerCamelCase :
'''simple docstring'''
__lowercase : List[str] = {}
def __init__( self , __lowercase , __lowercase = "root" , __lowercase=0 ):
"""simple docstring"""
__A : Dict = name
__A : List[str] = level
__A : Any = {}
for k, v in dictionary.items():
if v is None:
raise ValueError()
__A : int = copy.deepcopy(__lowercase )
__A : List[Any] = copy.deepcopy(__lowercase )
if isinstance(__lowercase , __lowercase ):
__A : int = Config(__lowercase , name=__lowercase , level=level + 1 )
__A : str = v
setattr(self , __lowercase , __lowercase )
__A : List[str] = d
def __repr__( self ):
"""simple docstring"""
return str(list((self._pointer.keys()) ) )
def __setattr__( self , __lowercase , __lowercase ):
"""simple docstring"""
__A : int = val
__A : Dict = val
__A : str = key.split('.' )
__A : Optional[Any] = len(__lowercase ) - 1
__A : Any = 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:
__A : Optional[int] = val
else:
__A : str = pointer[l]
def snake_case__ ( self ):
"""simple docstring"""
return self._pointer
def snake_case__ ( self , __lowercase , __lowercase ):
"""simple docstring"""
with open(F"""{file_name}""" , 'w' ) as stream:
dump(__lowercase , __lowercase )
def snake_case__ ( self , __lowercase , __lowercase ):
"""simple docstring"""
with open(F"""{file_name}""" , 'w' ) as stream:
json.dump(__lowercase , __lowercase )
@staticmethod
def snake_case__ ( __lowercase ):
"""simple docstring"""
with open(__lowercase ) as stream:
__A : Any = load(__lowercase , Loader=__lowercase )
return data
def __str__( self ):
"""simple docstring"""
__A : int = ' '
if self._name != "root":
__A : Optional[Any] = F"""{t * (self._level-1)}{self._name}:\n"""
else:
__A : Optional[Any] = ''
__A : Optional[Any] = 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"""
__A : Optional[int] = level
return r[:-1]
@classmethod
def snake_case__ ( cls , __lowercase , **__lowercase ):
"""simple docstring"""
__A ,__A : str = cls.get_config_dict(__lowercase , **__lowercase )
return cls(__lowercase )
@classmethod
def snake_case__ ( cls , __lowercase , **__lowercase ):
"""simple docstring"""
__A : Union[str, Any] = kwargs.pop('cache_dir' , __lowercase )
__A : Tuple = kwargs.pop('force_download' , __lowercase )
__A : Optional[int] = kwargs.pop('resume_download' , __lowercase )
__A : Tuple = kwargs.pop('proxies' , __lowercase )
__A : int = kwargs.pop('local_files_only' , __lowercase )
if os.path.isdir(__lowercase ):
__A : Any = os.path.join(__lowercase , __lowercase )
elif os.path.isfile(__lowercase ) or is_remote_url(__lowercase ):
__A : Tuple = pretrained_model_name_or_path
else:
__A : Optional[int] = hf_bucket_url(__lowercase , filename=__lowercase , use_cdn=__lowercase )
try:
# Load from URL or cache if already cached
__A : List[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
__A : List[str] = Config.load_yaml(__lowercase )
except EnvironmentError:
__A : Dict = '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 _lowercase ( UpperCamelCase__ : Any ):
__A : Any = torch.load('dump.pt', map_location=in_tensor.device )
__A : Optional[Any] = in_tensor.numpy()
__A : Union[str, Any] = out_tensor.numpy()[0]
print(na.shape, na[0, 0, :5] )
print(na.shape, na[0, 0, :5] )
assert np.allclose(UpperCamelCase__, UpperCamelCase__, rtol=0.01, atol=0.1 ), (
f"""{sum([1 for x in np.isclose(UpperCamelCase__, UpperCamelCase__, 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 _lowercase ( UpperCamelCase__ : List[str] ):
__A : Any = urlparse(UpperCamelCase__ )
return parsed.scheme in ("http", "https")
def _lowercase ( UpperCamelCase__ : str, UpperCamelCase__ : str, UpperCamelCase__ : Tuple=True ):
__A : Any = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
__A : List[str] = '/' not in model_id
if legacy_format:
return f"""{endpoint}/{model_id}-{filename}"""
else:
return f"""{endpoint}/{model_id}/{filename}"""
def _lowercase ( UpperCamelCase__ : Any, UpperCamelCase__ : Optional[Any], UpperCamelCase__ : List[Any]=None, UpperCamelCase__ : List[str]=0, UpperCamelCase__ : Tuple=None, ):
__A : Any = 'python/{}'.format(sys.version.split()[0] )
if _torch_available:
ua += "; torch/{}".format(torch.__version__ )
if isinstance(UpperCamelCase__, UpperCamelCase__ ):
ua += "; " + "; ".join('{}/{}'.format(UpperCamelCase__, UpperCamelCase__ ) for k, v in user_agent.items() )
elif isinstance(UpperCamelCase__, UpperCamelCase__ ):
ua += "; " + user_agent
__A : Dict = {'user-agent': ua}
if resume_size > 0:
__A : str = 'bytes=%d-' % (resume_size,)
__A : List[Any] = requests.get(UpperCamelCase__, stream=UpperCamelCase__, proxies=UpperCamelCase__, headers=UpperCamelCase__ )
if response.status_code == 416: # Range not satisfiable
return
__A : Any = response.headers.get('Content-Length' )
__A : List[Any] = resume_size + int(UpperCamelCase__ ) if content_length is not None else None
__A : str = tqdm(
unit='B', unit_scale=UpperCamelCase__, total=UpperCamelCase__, initial=UpperCamelCase__, desc='Downloading', )
for chunk in response.iter_content(chunk_size=1024 ):
if chunk: # filter out keep-alive new chunks
progress.update(len(UpperCamelCase__ ) )
temp_file.write(UpperCamelCase__ )
progress.close()
def _lowercase ( UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Optional[Any]=None, UpperCamelCase__ : List[Any]=False, UpperCamelCase__ : List[str]=None, UpperCamelCase__ : Optional[int]=10, UpperCamelCase__ : Dict=False, UpperCamelCase__ : List[str]=None, UpperCamelCase__ : Optional[Any]=False, ):
if cache_dir is None:
__A : List[str] = TRANSFORMERS_CACHE
if isinstance(UpperCamelCase__, UpperCamelCase__ ):
__A : List[Any] = str(UpperCamelCase__ )
os.makedirs(UpperCamelCase__, exist_ok=UpperCamelCase__ )
__A : str = None
if not local_files_only:
try:
__A : int = requests.head(UpperCamelCase__, allow_redirects=UpperCamelCase__, proxies=UpperCamelCase__, timeout=UpperCamelCase__ )
if response.status_code == 200:
__A : Tuple = response.headers.get('ETag' )
except (EnvironmentError, requests.exceptions.Timeout):
# etag is already None
pass
__A : int = url_to_filename(UpperCamelCase__, UpperCamelCase__ )
# get cache path to put the file
__A : List[Any] = os.path.join(UpperCamelCase__, UpperCamelCase__ )
# 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(UpperCamelCase__ ):
return cache_path
else:
__A : str = [
file
for file in fnmatch.filter(os.listdir(UpperCamelCase__ ), filename + '.*' )
if not file.endswith('.json' ) and not file.endswith('.lock' )
]
if len(UpperCamelCase__ ) > 0:
return os.path.join(UpperCamelCase__, 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(UpperCamelCase__ ) and not force_download:
return cache_path
# Prevent parallel downloads of the same file with a lock.
__A : List[str] = cache_path + '.lock'
with FileLock(UpperCamelCase__ ):
# If the download just completed while the lock was activated.
if os.path.exists(UpperCamelCase__ ) and not force_download:
# Even if returning early like here, the lock will be released.
return cache_path
if resume_download:
__A : Optional[int] = cache_path + '.incomplete'
@contextmanager
def _resumable_file_manager():
with open(UpperCamelCase__, 'a+b' ) as f:
yield f
__A : List[str] = _resumable_file_manager
if os.path.exists(UpperCamelCase__ ):
__A : int = os.stat(UpperCamelCase__ ).st_size
else:
__A : Union[str, Any] = 0
else:
__A : Dict = partial(tempfile.NamedTemporaryFile, dir=UpperCamelCase__, delete=UpperCamelCase__ )
__A : Dict = 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', UpperCamelCase__, temp_file.name, )
http_get(
UpperCamelCase__, UpperCamelCase__, proxies=UpperCamelCase__, resume_size=UpperCamelCase__, user_agent=UpperCamelCase__, )
os.replace(temp_file.name, UpperCamelCase__ )
__A : str = {'url': url, 'etag': etag}
__A : Dict = cache_path + '.json'
with open(UpperCamelCase__, 'w' ) as meta_file:
json.dump(UpperCamelCase__, UpperCamelCase__ )
return cache_path
def _lowercase ( UpperCamelCase__ : List[str], UpperCamelCase__ : Dict=None ):
__A : Tuple = url.encode('utf-8' )
__A : int = shaaaa(UpperCamelCase__ )
__A : Tuple = url_hash.hexdigest()
if etag:
__A : Tuple = etag.encode('utf-8' )
__A : Optional[Any] = shaaaa(UpperCamelCase__ )
filename += "." + etag_hash.hexdigest()
if url.endswith('.h5' ):
filename += ".h5"
return filename
def _lowercase ( UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Union[str, Any]=None, UpperCamelCase__ : str=False, UpperCamelCase__ : Any=None, UpperCamelCase__ : Tuple=False, UpperCamelCase__ : Dict=None, UpperCamelCase__ : Union[str, Any]=False, UpperCamelCase__ : Union[str, Any]=False, UpperCamelCase__ : Optional[Any]=False, ):
if cache_dir is None:
__A : int = TRANSFORMERS_CACHE
if isinstance(UpperCamelCase__, UpperCamelCase__ ):
__A : Union[str, Any] = str(UpperCamelCase__ )
if isinstance(UpperCamelCase__, UpperCamelCase__ ):
__A : List[str] = str(UpperCamelCase__ )
if is_remote_url(UpperCamelCase__ ):
# URL, so get it from the cache (downloading if necessary)
__A : Tuple = get_from_cache(
UpperCamelCase__, cache_dir=UpperCamelCase__, force_download=UpperCamelCase__, proxies=UpperCamelCase__, resume_download=UpperCamelCase__, user_agent=UpperCamelCase__, local_files_only=UpperCamelCase__, )
elif os.path.exists(UpperCamelCase__ ):
# File, and it exists.
__A : Optional[Any] = url_or_filename
elif urlparse(UpperCamelCase__ ).scheme == "":
# File, but it doesn't exist.
raise EnvironmentError('file {} not found'.format(UpperCamelCase__ ) )
else:
# Something unknown
raise ValueError('unable to parse {} as a URL or as a local path'.format(UpperCamelCase__ ) )
if extract_compressed_file:
if not is_zipfile(UpperCamelCase__ ) and not tarfile.is_tarfile(UpperCamelCase__ ):
return output_path
# Path where we extract compressed archives
# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
__A ,__A : List[str] = os.path.split(UpperCamelCase__ )
__A : Optional[Any] = output_file.replace('.', '-' ) + '-extracted'
__A : str = os.path.join(UpperCamelCase__, UpperCamelCase__ )
if os.path.isdir(UpperCamelCase__ ) and os.listdir(UpperCamelCase__ ) and not force_extract:
return output_path_extracted
# Prevent parallel extractions
__A : Any = output_path + '.lock'
with FileLock(UpperCamelCase__ ):
shutil.rmtree(UpperCamelCase__, ignore_errors=UpperCamelCase__ )
os.makedirs(UpperCamelCase__ )
if is_zipfile(UpperCamelCase__ ):
with ZipFile(UpperCamelCase__, 'r' ) as zip_file:
zip_file.extractall(UpperCamelCase__ )
zip_file.close()
elif tarfile.is_tarfile(UpperCamelCase__ ):
__A : Optional[int] = tarfile.open(UpperCamelCase__ )
tar_file.extractall(UpperCamelCase__ )
tar_file.close()
else:
raise EnvironmentError('Archive format of {} could not be identified'.format(UpperCamelCase__ ) )
return output_path_extracted
return output_path
def _lowercase ( UpperCamelCase__ : int, UpperCamelCase__ : str="," ):
assert isinstance(UpperCamelCase__, UpperCamelCase__ )
if os.path.isfile(UpperCamelCase__ ):
with open(UpperCamelCase__ ) as f:
__A : Any = eval(f.read() )
else:
__A : Optional[int] = requests.get(UpperCamelCase__ )
try:
__A : int = requests.json()
except Exception:
__A : Dict = req.content.decode()
assert data is not None, "could not connect"
try:
__A : Dict = eval(UpperCamelCase__ )
except Exception:
__A : Any = data.split('\n' )
req.close()
return data
def _lowercase ( UpperCamelCase__ : Optional[Any] ):
__A : Dict = requests.get(UpperCamelCase__ )
__A : Optional[int] = np.array(Image.open(BytesIO(response.content ) ) )
return img
def _lowercase ( UpperCamelCase__ : Union[str, Any] ):
__A : Optional[Any] = url.split('/' )[-1]
if fn not in os.listdir(os.getcwd() ):
wget.download(UpperCamelCase__ )
with open(UpperCamelCase__, 'rb' ) as stream:
__A : Union[str, Any] = pkl.load(UpperCamelCase__ )
__A : Union[str, Any] = weights.pop('model' )
__A : Optional[Any] = {}
for k, v in model.items():
__A : int = torch.from_numpy(UpperCamelCase__ )
if "running_var" in k:
__A : List[str] = torch.tensor([0] )
__A : Optional[Any] = k.replace('running_var', 'num_batches_tracked' )
__A : Dict = zero
return new
def _lowercase ( ):
print(f"""{os.path.abspath(os.path.join(UpperCamelCase__, os.pardir ) )}/demo.ipynb""" )
def _lowercase ( UpperCamelCase__ : Tuple, UpperCamelCase__ : Union[str, Any]="RGB" ):
assert isinstance(UpperCamelCase__, UpperCamelCase__ )
if os.path.isfile(UpperCamelCase__ ):
__A : Any = cva.imread(UpperCamelCase__ )
else:
__A : Any = get_image_from_url(UpperCamelCase__ )
assert img is not None, f"""could not connect to: {im}"""
__A : int = cva.cvtColor(UpperCamelCase__, cva.COLOR_BGR2RGB )
if input_format == "RGB":
__A : Any = img[:, :, ::-1]
return img
def _lowercase ( UpperCamelCase__ : Tuple, UpperCamelCase__ : Any=1 ):
return (images[i : i + batch] for i in range(0, len(UpperCamelCase__ ), UpperCamelCase__ ))
| 540 |
'''simple docstring'''
from __future__ import annotations
class _lowerCamelCase :
'''simple docstring'''
def __init__( self , __lowercase ):
"""simple docstring"""
__A : Dict = order
# a_{0} ... a_{k}
__A : str = [1.0] + [0.0] * order
# b_{0} ... b_{k}
__A : Any = [1.0] + [0.0] * order
# x[n-1] ... x[n-k]
__A : Optional[int] = [0.0] * self.order
# y[n-1] ... y[n-k]
__A : Dict = [0.0] * self.order
def snake_case__ ( self , __lowercase , __lowercase ):
"""simple docstring"""
if len(__lowercase ) < self.order:
__A : List[Any] = [1.0, *a_coeffs]
if len(__lowercase ) != self.order + 1:
__A : Tuple = (
F"""Expected a_coeffs to have {self.order + 1} elements """
F"""for {self.order}-order filter, got {len(__lowercase )}"""
)
raise ValueError(__lowercase )
if len(__lowercase ) != self.order + 1:
__A : List[Any] = (
F"""Expected b_coeffs to have {self.order + 1} elements """
F"""for {self.order}-order filter, got {len(__lowercase )}"""
)
raise ValueError(__lowercase )
__A : Optional[int] = a_coeffs
__A : Optional[int] = b_coeffs
def snake_case__ ( self , __lowercase ):
"""simple docstring"""
__A : Union[str, Any] = 0.0
# Start at index 1 and do index 0 at the end.
for i in range(1 , self.order + 1 ):
result += (
self.b_coeffs[i] * self.input_history[i - 1]
- self.a_coeffs[i] * self.output_history[i - 1]
)
__A : Optional[int] = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0]
__A : List[str] = self.input_history[:-1]
__A : Optional[int] = self.output_history[:-1]
__A : Optional[int] = sample
__A : Dict = result
return result
| 540 | 1 |
'''simple docstring'''
import math
def snake_case_ (UpperCamelCase : int ):
'''simple docstring'''
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(math.sqrt(UpperCamelCase ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def snake_case_ (UpperCamelCase : int = 1_0001 ):
'''simple docstring'''
try:
_a = int(UpperCamelCase )
except (TypeError, ValueError):
raise TypeError('''Parameter nth must be int or castable to int.''' ) from None
if nth <= 0:
raise ValueError('''Parameter nth must be greater than or equal to one.''' )
_a = []
_a = 2
while len(UpperCamelCase ) < nth:
if is_prime(UpperCamelCase ):
primes.append(UpperCamelCase )
num += 1
else:
num += 1
return primes[len(UpperCamelCase ) - 1]
if __name__ == "__main__":
print(F'''{solution() = }''')
| 22 |
'''simple docstring'''
import json
import os
import tempfile
import unittest
import numpy as np
from datasets import load_dataset
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import ImageGPTImageProcessor
class A ( unittest.TestCase ):
def __init__( self : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : List[str]=7 , lowerCAmelCase_ : Dict=3 , lowerCAmelCase_ : List[Any]=18 , lowerCAmelCase_ : Any=30 , lowerCAmelCase_ : Optional[int]=4_00 , lowerCAmelCase_ : Union[str, Any]=True , lowerCAmelCase_ : List[str]=None , lowerCAmelCase_ : List[str]=True , ) -> Optional[Any]:
"""simple docstring"""
_a = size if size is not None else {'''height''': 18, '''width''': 18}
_a = parent
_a = batch_size
_a = num_channels
_a = image_size
_a = min_resolution
_a = max_resolution
_a = do_resize
_a = size
_a = do_normalize
def __lowerCAmelCase ( self : Dict ) -> int:
"""simple docstring"""
return {
# here we create 2 clusters for the sake of simplicity
"clusters": np.asarray(
[
[0.8_8_6_6_4_4_3_6_3_4_0_3_3_2_0_3, 0.6_6_1_8_8_2_9_3_6_9_5_4_4_9_8_3, 0.3_8_9_1_7_4_6_4_0_1_7_8_6_8_0_4],
[-0.6_0_4_2_5_5_9_1_4_6_8_8_1_1_0_4, -0.0_2_2_9_5_0_0_8_8_6_0_5_2_8_4_6_9, 0.5_4_2_3_7_9_7_3_6_9_0_0_3_2_9_6],
] ),
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
}
@require_torch
@require_vision
class A ( _a ,unittest.TestCase ):
lowercase_ = ImageGPTImageProcessor if is_vision_available() else None
def __lowerCAmelCase ( self : List[Any] ) -> str:
"""simple docstring"""
_a = ImageGPTImageProcessingTester(self )
@property
def __lowerCAmelCase ( self : Tuple ) -> int:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def __lowerCAmelCase ( self : List[str] ) -> Dict:
"""simple docstring"""
_a = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(lowerCAmelCase_ , '''clusters''' ) )
self.assertTrue(hasattr(lowerCAmelCase_ , '''do_resize''' ) )
self.assertTrue(hasattr(lowerCAmelCase_ , '''size''' ) )
self.assertTrue(hasattr(lowerCAmelCase_ , '''do_normalize''' ) )
def __lowerCAmelCase ( self : List[Any] ) -> List[str]:
"""simple docstring"""
_a = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} )
_a = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} )
def __lowerCAmelCase ( self : str ) -> str:
"""simple docstring"""
_a = self.image_processing_class(**self.image_processor_dict )
_a = json.loads(image_processor.to_json_string() )
for key, value in self.image_processor_dict.items():
if key == "clusters":
self.assertTrue(np.array_equal(lowerCAmelCase_ , obj[key] ) )
else:
self.assertEqual(obj[key] , lowerCAmelCase_ )
def __lowerCAmelCase ( self : List[str] ) -> int:
"""simple docstring"""
_a = self.image_processing_class(**self.image_processor_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
_a = os.path.join(lowerCAmelCase_ , '''image_processor.json''' )
image_processor_first.to_json_file(lowerCAmelCase_ )
_a = self.image_processing_class.from_json_file(lowerCAmelCase_ ).to_dict()
_a = image_processor_first.to_dict()
for key, value in image_processor_first.items():
if key == "clusters":
self.assertTrue(np.array_equal(lowerCAmelCase_ , image_processor_second[key] ) )
else:
self.assertEqual(image_processor_first[key] , lowerCAmelCase_ )
def __lowerCAmelCase ( self : Any ) -> List[Any]:
"""simple docstring"""
_a = self.image_processing_class(**self.image_processor_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
image_processor_first.save_pretrained(lowerCAmelCase_ )
_a = self.image_processing_class.from_pretrained(lowerCAmelCase_ ).to_dict()
_a = image_processor_first.to_dict()
for key, value in image_processor_first.items():
if key == "clusters":
self.assertTrue(np.array_equal(lowerCAmelCase_ , image_processor_second[key] ) )
else:
self.assertEqual(image_processor_first[key] , lowerCAmelCase_ )
@unittest.skip('''ImageGPT requires clusters at initialization''' )
def __lowerCAmelCase ( self : List[Any] ) -> Union[str, Any]:
"""simple docstring"""
pass
def snake_case_ ():
'''simple docstring'''
_a = load_dataset('''hf-internal-testing/fixtures_image_utils''' , split='''test''' )
_a = Image.open(dataset[4]['''file'''] )
_a = Image.open(dataset[5]['''file'''] )
_a = [imagea, imagea]
return images
@require_vision
@require_torch
class A ( unittest.TestCase ):
@slow
def __lowerCAmelCase ( self : List[str] ) -> int:
"""simple docstring"""
_a = ImageGPTImageProcessor.from_pretrained('''openai/imagegpt-small''' )
_a = prepare_images()
# test non-batched
_a = image_processing(images[0] , return_tensors='''pt''' )
self.assertIsInstance(encoding.input_ids , torch.LongTensor )
self.assertEqual(encoding.input_ids.shape , (1, 10_24) )
_a = [3_06, 1_91, 1_91]
self.assertEqual(encoding.input_ids[0, :3].tolist() , lowerCAmelCase_ )
# test batched
_a = image_processing(lowerCAmelCase_ , return_tensors='''pt''' )
self.assertIsInstance(encoding.input_ids , torch.LongTensor )
self.assertEqual(encoding.input_ids.shape , (2, 10_24) )
_a = [3_03, 13, 13]
self.assertEqual(encoding.input_ids[1, -3:].tolist() , lowerCAmelCase_ )
| 22 | 1 |
'''simple docstring'''
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.testing_utils import require_tensorflow_text, require_tf, slow
if is_tf_available():
import tensorflow as tf
if is_tensorflow_text_available():
from transformers.models.bert import TFBertTokenizer
lowercase__ = ['''bert-base-uncased''', '''bert-base-cased''']
lowercase__ = '''hf-internal-testing/tiny-bert-tf-only'''
if is_tf_available():
class UpperCAmelCase_ ( tf.keras.Model ):
"""simple docstring"""
def __init__( self , UpperCAmelCase_ ):
super().__init__()
snake_case_ = tokenizer
snake_case_ = AutoConfig.from_pretrained(UpperCAmelCase_ )
snake_case_ = TFAutoModel.from_config(UpperCAmelCase_ )
def _lowercase ( self , UpperCAmelCase_ ):
snake_case_ = self.tokenizer(UpperCAmelCase_ )
snake_case_ = self.bert(**UpperCAmelCase_ )
return out["pooler_output"]
@require_tf
@require_tensorflow_text
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
def _lowercase ( self ):
super().setUp()
snake_case_ = [
BertTokenizer.from_pretrained(UpperCAmelCase_ ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2)
] # repeat for when fast_bert_tokenizer=false
snake_case_ = [TFBertTokenizer.from_pretrained(UpperCAmelCase_ ) for checkpoint in TOKENIZER_CHECKPOINTS] + [
TFBertTokenizer.from_pretrained(UpperCAmelCase_ , use_fast_bert_tokenizer=UpperCAmelCase_ )
for checkpoint in TOKENIZER_CHECKPOINTS
]
assert len(self.tokenizers ) == len(self.tf_tokenizers )
snake_case_ = [
"This is a straightforward English test sentence.",
"This one has some weird characters\rto\nsee\r\nif those\u00E9break things.",
"Now we're going to add some Chinese: 一 二 三 一二三",
"And some much more rare Chinese: 齉 堃 齉堃",
"Je vais aussi écrire en français pour tester les accents",
"Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ",
]
snake_case_ = list(zip(self.test_sentences , self.test_sentences[::-1] ) )
def _lowercase ( self ):
for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ):
for test_inputs in (self.test_sentences, self.paired_sentences):
snake_case_ = tokenizer(UpperCAmelCase_ , return_tensors="tf" , padding="longest" )
snake_case_ = tf_tokenizer(UpperCAmelCase_ )
for key in python_outputs.keys():
self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) )
self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) )
@slow
def _lowercase ( self ):
for tf_tokenizer in self.tf_tokenizers:
snake_case_ = tf_tokenizer(self.paired_sentences )
snake_case_ = tf_tokenizer(
text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , )
for key in merged_outputs.keys():
self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) )
@slow
def _lowercase ( self ):
for tf_tokenizer in self.tf_tokenizers:
snake_case_ = tf.function(UpperCAmelCase_ )
for test_inputs in (self.test_sentences, self.paired_sentences):
snake_case_ = tf.constant(UpperCAmelCase_ )
snake_case_ = compiled_tokenizer(UpperCAmelCase_ )
snake_case_ = tf_tokenizer(UpperCAmelCase_ )
for key in eager_outputs.keys():
self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) )
@slow
def _lowercase ( self ):
for tf_tokenizer in self.tf_tokenizers:
snake_case_ = ModelToSave(tokenizer=UpperCAmelCase_ )
snake_case_ = tf.convert_to_tensor(self.test_sentences )
snake_case_ = model(UpperCAmelCase_ ) # Build model with some sample inputs
with TemporaryDirectory() as tempdir:
snake_case_ = Path(UpperCAmelCase_ ) / "saved.model"
model.save(UpperCAmelCase_ )
snake_case_ = tf.keras.models.load_model(UpperCAmelCase_ )
snake_case_ = loaded_model(UpperCAmelCase_ )
# We may see small differences because the loaded model is compiled, so we need an epsilon for the test
self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1e-5 )
| 420 |
'''simple docstring'''
import json
import os
import re
import unicodedata
from json.encoder import INFINITY
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import regex
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging
from ...utils.generic import _is_jax, _is_numpy
lowercase__ = logging.get_logger(__name__)
lowercase__ = {
'''artists_file''': '''artists.json''',
'''lyrics_file''': '''lyrics.json''',
'''genres_file''': '''genres.json''',
}
lowercase__ = {
'''artists_file''': {
'''jukebox''': '''https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json''',
},
'''genres_file''': {
'''jukebox''': '''https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json''',
},
'''lyrics_file''': {
'''jukebox''': '''https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json''',
},
}
lowercase__ = {
'''jukebox''': 5_12,
}
class UpperCAmelCase_ ( SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
snake_case = VOCAB_FILES_NAMES
snake_case = PRETRAINED_VOCAB_FILES_MAP
snake_case = PRETRAINED_LYRIC_TOKENS_SIZES
snake_case = ["""input_ids""", """attention_mask"""]
def __init__( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_=["v3", "v2", "v2"] , UpperCAmelCase_=5_12 , UpperCAmelCase_=5 , UpperCAmelCase_="<|endoftext|>" , **UpperCAmelCase_ , ):
snake_case_ = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else unk_token
super().__init__(
unk_token=UpperCAmelCase_ , n_genres=UpperCAmelCase_ , version=UpperCAmelCase_ , max_n_lyric_tokens=UpperCAmelCase_ , **UpperCAmelCase_ , )
snake_case_ = version
snake_case_ = max_n_lyric_tokens
snake_case_ = n_genres
with open(UpperCAmelCase_ , encoding="utf-8" ) as vocab_handle:
snake_case_ = json.load(UpperCAmelCase_ )
with open(UpperCAmelCase_ , encoding="utf-8" ) as vocab_handle:
snake_case_ = json.load(UpperCAmelCase_ )
with open(UpperCAmelCase_ , encoding="utf-8" ) as vocab_handle:
snake_case_ = json.load(UpperCAmelCase_ )
snake_case_ = R"[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+"
# In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters.
if len(self.lyrics_encoder ) == 79:
snake_case_ = oov.replace(R"\-'" , R"\-+'" )
snake_case_ = regex.compile(UpperCAmelCase_ )
snake_case_ = {v: k for k, v in self.artists_encoder.items()}
snake_case_ = {v: k for k, v in self.genres_encoder.items()}
snake_case_ = {v: k for k, v in self.lyrics_encoder.items()}
@property
def _lowercase ( self ):
return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder )
def _lowercase ( self ):
return dict(self.artists_encoder , self.genres_encoder , self.lyrics_encoder )
def _lowercase ( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ):
snake_case_ = [self.artists_encoder.get(UpperCAmelCase_ , 0 ) for artist in list_artists]
for genres in range(len(UpperCAmelCase_ ) ):
snake_case_ = [self.genres_encoder.get(UpperCAmelCase_ , 0 ) for genre in list_genres[genres]]
snake_case_ = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] ))
snake_case_ = [[self.lyrics_encoder.get(UpperCAmelCase_ , 0 ) for character in list_lyrics[0]], [], []]
return artists_id, list_genres, lyric_ids
def _lowercase ( self , UpperCAmelCase_ ):
return list(UpperCAmelCase_ )
def _lowercase ( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ ):
snake_case_ , snake_case_ , snake_case_ = self.prepare_for_tokenization(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
snake_case_ = self._tokenize(UpperCAmelCase_ )
return artist, genre, lyrics
def _lowercase ( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = False ):
for idx in range(len(self.version ) ):
if self.version[idx] == "v3":
snake_case_ = artists[idx].lower()
snake_case_ = [genres[idx].lower()]
else:
snake_case_ = self._normalize(artists[idx] ) + ".v2"
snake_case_ = [
self._normalize(UpperCAmelCase_ ) + ".v2" for genre in genres[idx].split("_" )
] # split is for the full dictionary with combined genres
if self.version[0] == "v2":
snake_case_ = regex.compile(R"[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+" )
snake_case_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+'\"()[] \t\n"
snake_case_ = {vocab[index]: index + 1 for index in range(len(UpperCAmelCase_ ) )}
snake_case_ = 0
snake_case_ = len(UpperCAmelCase_ ) + 1
snake_case_ = self.vocab
snake_case_ = {v: k for k, v in self.vocab.items()}
snake_case_ = ""
else:
snake_case_ = regex.compile(R"[^A-Za-z0-9.,:;!?\-+'\"()\[\] \t\n]+" )
snake_case_ = self._run_strip_accents(UpperCAmelCase_ )
snake_case_ = lyrics.replace("\\" , "\n" )
snake_case_ = self.out_of_vocab.sub("" , UpperCAmelCase_ ), [], []
return artists, genres, lyrics
def _lowercase ( self , UpperCAmelCase_ ):
snake_case_ = unicodedata.normalize("NFD" , UpperCAmelCase_ )
snake_case_ = []
for char in text:
snake_case_ = unicodedata.category(UpperCAmelCase_ )
if cat == "Mn":
continue
output.append(UpperCAmelCase_ )
return "".join(UpperCAmelCase_ )
def _lowercase ( self , UpperCAmelCase_ ):
snake_case_ = (
[chr(UpperCAmelCase_ ) for i in range(ord("a" ) , ord("z" ) + 1 )]
+ [chr(UpperCAmelCase_ ) for i in range(ord("A" ) , ord("Z" ) + 1 )]
+ [chr(UpperCAmelCase_ ) for i in range(ord("0" ) , ord("9" ) + 1 )]
+ ["."]
)
snake_case_ = frozenset(UpperCAmelCase_ )
snake_case_ = re.compile(R"_+" )
snake_case_ = "".join([c if c in accepted else "_" for c in text.lower()] )
snake_case_ = pattern.sub("_" , UpperCAmelCase_ ).strip("_" )
return text
def _lowercase ( self , UpperCAmelCase_ ):
return " ".join(UpperCAmelCase_ )
def _lowercase ( self , UpperCAmelCase_ , UpperCAmelCase_ = None , UpperCAmelCase_ = False ):
# Convert to TensorType
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ):
snake_case_ = TensorType(UpperCAmelCase_ )
# Get a function reference for the correct framework
if tensor_type == TensorType.TENSORFLOW:
if not is_tf_available():
raise ImportError(
"Unable to convert output to TensorFlow tensors format, TensorFlow is not installed." )
import tensorflow as tf
snake_case_ = tf.constant
snake_case_ = tf.is_tensor
elif tensor_type == TensorType.PYTORCH:
if not is_torch_available():
raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed." )
import torch
snake_case_ = torch.tensor
snake_case_ = torch.is_tensor
elif tensor_type == TensorType.JAX:
if not is_flax_available():
raise ImportError("Unable to convert output to JAX tensors format, JAX is not installed." )
import jax.numpy as jnp # noqa: F811
snake_case_ = jnp.array
snake_case_ = _is_jax
else:
snake_case_ = np.asarray
snake_case_ = _is_numpy
# Do the tensor conversion in batch
try:
if prepend_batch_axis:
snake_case_ = [inputs]
if not is_tensor(UpperCAmelCase_ ):
snake_case_ = as_tensor(UpperCAmelCase_ )
except: # noqa E722
raise ValueError(
"Unable to create tensor, you should probably activate truncation and/or padding "
"with 'padding=True' 'truncation=True' to have batched tensors with the same length." )
return inputs
def __call__( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_="" , UpperCAmelCase_="pt" ):
snake_case_ = [0, 0, 0]
snake_case_ = [artist] * len(self.version )
snake_case_ = [genres] * len(self.version )
snake_case_ , snake_case_ , snake_case_ = self.tokenize(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
snake_case_ , snake_case_ , snake_case_ = self._convert_token_to_id(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
snake_case_ = [-INFINITY] * len(full_tokens[-1] )
snake_case_ = [
self.convert_to_tensors(
[input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] , tensor_type=UpperCAmelCase_ )
for i in range(len(self.version ) )
]
return BatchEncoding({"input_ids": input_ids, "attention_masks": attention_masks} )
def _lowercase ( self , UpperCAmelCase_ , UpperCAmelCase_ = None ):
if not os.path.isdir(UpperCAmelCase_ ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
return
snake_case_ = os.path.join(
UpperCAmelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["artists_file"] )
with open(UpperCAmelCase_ , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(self.artists_encoder , ensure_ascii=UpperCAmelCase_ ) )
snake_case_ = os.path.join(
UpperCAmelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["genres_file"] )
with open(UpperCAmelCase_ , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(self.genres_encoder , ensure_ascii=UpperCAmelCase_ ) )
snake_case_ = os.path.join(
UpperCAmelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["lyrics_file"] )
with open(UpperCAmelCase_ , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(self.lyrics_encoder , ensure_ascii=UpperCAmelCase_ ) )
return (artists_file, genres_file, lyrics_file)
def _lowercase ( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ):
snake_case_ = self.artists_decoder.get(UpperCAmelCase_ )
snake_case_ = [self.genres_decoder.get(UpperCAmelCase_ ) for genre in genres_index]
snake_case_ = [self.lyrics_decoder.get(UpperCAmelCase_ ) for character in lyric_index]
return artist, genres, lyrics
| 420 | 1 |
'''simple docstring'''
import argparse
import torch
from transformers import (
UniSpeechSatConfig,
UniSpeechSatForAudioFrameClassification,
UniSpeechSatForSequenceClassification,
UniSpeechSatForXVector,
WavaVecaFeatureExtractor,
logging,
)
logging.set_verbosity_info()
__SCREAMING_SNAKE_CASE : Optional[Any] = logging.get_logger(__name__)
def a_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ):
A_ = UniSpeechSatForSequenceClassification.from_pretrained(UpperCAmelCase_ , config=UpperCAmelCase_ )
A_ = downstream_dict['projector.weight']
A_ = downstream_dict['projector.bias']
A_ = downstream_dict['model.post_net.linear.weight']
A_ = downstream_dict['model.post_net.linear.bias']
return model
def a_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ):
A_ = UniSpeechSatForAudioFrameClassification.from_pretrained(UpperCAmelCase_ , config=UpperCAmelCase_ )
A_ = downstream_dict['model.linear.weight']
A_ = downstream_dict['model.linear.bias']
return model
def a_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ):
A_ = UniSpeechSatForXVector.from_pretrained(UpperCAmelCase_ , config=UpperCAmelCase_ )
A_ = downstream_dict['connector.weight']
A_ = downstream_dict['connector.bias']
for i, kernel_size in enumerate(hf_config.tdnn_kernel ):
A_ = downstream_dict[
f"model.framelevel_feature_extractor.module.{i}.kernel.weight"
]
A_ = downstream_dict[f"model.framelevel_feature_extractor.module.{i}.kernel.bias"]
A_ = downstream_dict['model.utterancelevel_feature_extractor.linear1.weight']
A_ = downstream_dict['model.utterancelevel_feature_extractor.linear1.bias']
A_ = downstream_dict['model.utterancelevel_feature_extractor.linear2.weight']
A_ = downstream_dict['model.utterancelevel_feature_extractor.linear2.bias']
A_ = downstream_dict['objective.W']
return model
@torch.no_grad()
def a_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ):
A_ = torch.load(UpperCAmelCase_ , map_location="cpu" )
A_ = checkpoint['Downstream']
A_ = UniSpeechSatConfig.from_pretrained(UpperCAmelCase_ )
A_ = WavaVecaFeatureExtractor.from_pretrained(
UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , do_normalize=UpperCAmelCase_ )
A_ = hf_config.architectures[0]
if arch.endswith("ForSequenceClassification" ):
A_ = convert_classification(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
elif arch.endswith("ForAudioFrameClassification" ):
A_ = convert_diarization(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
elif arch.endswith("ForXVector" ):
A_ = convert_xvector(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
else:
raise NotImplementedError(f"S3PRL weights conversion is not supported for {arch}" )
if hf_config.use_weighted_layer_sum:
A_ = checkpoint['Featurizer']['weights']
hf_feature_extractor.save_pretrained(UpperCAmelCase_ )
hf_model.save_pretrained(UpperCAmelCase_ )
if __name__ == "__main__":
__SCREAMING_SNAKE_CASE : str = 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.''')
__SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_args()
convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
| 452 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
if is_sentencepiece_available():
from ..ta.tokenization_ta import TaTokenizer
else:
from ...utils.dummy_sentencepiece_objects import TaTokenizer
A__ : int = TaTokenizer
if is_tokenizers_available():
from ..ta.tokenization_ta_fast import TaTokenizerFast
else:
from ...utils.dummy_tokenizers_objects import TaTokenizerFast
A__ : Dict = TaTokenizerFast
A__ : Dict = {"""configuration_mt5""": ["""MT5Config""", """MT5OnnxConfig"""]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A__ : Any = [
"""MT5EncoderModel""",
"""MT5ForConditionalGeneration""",
"""MT5ForQuestionAnswering""",
"""MT5Model""",
"""MT5PreTrainedModel""",
"""MT5Stack""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A__ : str = ["""TFMT5EncoderModel""", """TFMT5ForConditionalGeneration""", """TFMT5Model"""]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A__ : str = ["""FlaxMT5EncoderModel""", """FlaxMT5ForConditionalGeneration""", """FlaxMT5Model"""]
if TYPE_CHECKING:
from .configuration_mta import MTaConfig, MTaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mta import (
MTaEncoderModel,
MTaForConditionalGeneration,
MTaForQuestionAnswering,
MTaModel,
MTaPreTrainedModel,
MTaStack,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel
else:
import sys
A__ : Union[str, Any] = _LazyModule(
__name__,
globals()["""__file__"""],
_import_structure,
extra_objects={"""MT5Tokenizer""": MTaTokenizer, """MT5TokenizerFast""": MTaTokenizerFast},
module_spec=__spec__,
)
| 13 | 0 |
'''simple docstring'''
import json
import os
import unittest
from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer
from transformers.testing_utils import slow
from ...test_tokenization_common import TokenizerTesterMixin
class A_ ( _A , unittest.TestCase ):
_lowerCamelCase : Optional[Any] = XLMTokenizer
_lowerCamelCase : Optional[Any] = False
def lowercase ( self : List[Any] ):
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
_UpperCAmelCase = [
"l",
"o",
"w",
"e",
"r",
"s",
"t",
"i",
"d",
"n",
"w</w>",
"r</w>",
"t</w>",
"lo",
"low",
"er</w>",
"low</w>",
"lowest</w>",
"newer</w>",
"wider</w>",
"<unk>",
]
_UpperCAmelCase = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) )
_UpperCAmelCase = ["l o 123", "lo w 1456", "e r</w> 1789", ""]
_UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
_UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] )
with open(self.vocab_file , "w" ) as fp:
fp.write(json.dumps(__lowerCamelCase ) )
with open(self.merges_file , "w" ) as fp:
fp.write("\n".join(__lowerCamelCase ) )
def lowercase ( self : List[str] , snake_case_ : Tuple ):
_UpperCAmelCase = "lower newer"
_UpperCAmelCase = "lower newer"
return input_text, output_text
def lowercase ( self : Dict ):
_UpperCAmelCase = XLMTokenizer(self.vocab_file , self.merges_file )
_UpperCAmelCase = "lower"
_UpperCAmelCase = ["low", "er</w>"]
_UpperCAmelCase = tokenizer.tokenize(__lowerCamelCase )
self.assertListEqual(__lowerCamelCase , __lowerCamelCase )
_UpperCAmelCase = tokens + ["<unk>"]
_UpperCAmelCase = [1_4, 1_5, 2_0]
self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , __lowerCamelCase )
@slow
def lowercase ( self : Optional[int] ):
_UpperCAmelCase = XLMTokenizer.from_pretrained("xlm-mlm-en-2048" )
_UpperCAmelCase = tokenizer.encode("sequence builders" , add_special_tokens=__lowerCamelCase )
_UpperCAmelCase = tokenizer.encode("multi-sequence build" , add_special_tokens=__lowerCamelCase )
_UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(__lowerCamelCase )
_UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(__lowerCamelCase , __lowerCamelCase )
assert encoded_sentence == [0] + text + [1]
assert encoded_pair == [0] + text + [1] + text_a + [1]
| 717 |
'''simple docstring'''
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_torch
if is_torch_available():
import torch
from transformers.activations import gelu_new, gelu_python, get_activation
@require_torch
class A_ ( unittest.TestCase ):
def lowercase ( self : List[str] ):
_UpperCAmelCase = torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0] )
_UpperCAmelCase = get_activation("gelu" )
self.assertTrue(torch.allclose(gelu_python(snake_case_ ) , torch_builtin(snake_case_ ) ) )
self.assertFalse(torch.allclose(gelu_python(snake_case_ ) , gelu_new(snake_case_ ) ) )
def lowercase ( self : int ):
_UpperCAmelCase = torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0] )
_UpperCAmelCase = get_activation("gelu" )
_UpperCAmelCase = get_activation("gelu_10" )
_UpperCAmelCase = torch_builtin(snake_case_ )
_UpperCAmelCase = geluaa(snake_case_ )
_UpperCAmelCase = torch.where(y_gelu_aa < 1_0.0 , 1 , 0 )
self.assertTrue(torch.max(snake_case_ ).item() == 1_0.0 )
self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) )
def lowercase ( self : Any ):
get_activation("gelu" )
get_activation("gelu_10" )
get_activation("gelu_fast" )
get_activation("gelu_new" )
get_activation("gelu_python" )
get_activation("gelu_pytorch_tanh" )
get_activation("linear" )
get_activation("mish" )
get_activation("quick_gelu" )
get_activation("relu" )
get_activation("sigmoid" )
get_activation("silu" )
get_activation("swish" )
get_activation("tanh" )
with self.assertRaises(snake_case_ ):
get_activation("bogus" )
with self.assertRaises(snake_case_ ):
get_activation(snake_case_ )
def lowercase ( self : Dict ):
_UpperCAmelCase = get_activation("gelu" )
_UpperCAmelCase = 1
_UpperCAmelCase = get_activation("gelu" )
self.assertEqual(acta.a , 1 )
with self.assertRaises(snake_case_ ):
_UpperCAmelCase = acta.a
| 119 | 0 |
'''simple docstring'''
import inspect
import unittest
from transformers import ViTMSNConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ViTMSNForImageClassification, ViTMSNModel
from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class UpperCamelCase__ :
'''simple docstring'''
def __init__( self ,_lowerCAmelCase ,_lowerCAmelCase=13 ,_lowerCAmelCase=30 ,_lowerCAmelCase=2 ,_lowerCAmelCase=3 ,_lowerCAmelCase=True ,_lowerCAmelCase=True ,_lowerCAmelCase=32 ,_lowerCAmelCase=5 ,_lowerCAmelCase=4 ,_lowerCAmelCase=37 ,_lowerCAmelCase="gelu" ,_lowerCAmelCase=0.1 ,_lowerCAmelCase=0.1 ,_lowerCAmelCase=10 ,_lowerCAmelCase=0.02 ,_lowerCAmelCase=None ,):
lowerCamelCase__ = parent
lowerCamelCase__ = batch_size
lowerCamelCase__ = image_size
lowerCamelCase__ = patch_size
lowerCamelCase__ = num_channels
lowerCamelCase__ = is_training
lowerCamelCase__ = use_labels
lowerCamelCase__ = hidden_size
lowerCamelCase__ = num_hidden_layers
lowerCamelCase__ = num_attention_heads
lowerCamelCase__ = intermediate_size
lowerCamelCase__ = hidden_act
lowerCamelCase__ = hidden_dropout_prob
lowerCamelCase__ = attention_probs_dropout_prob
lowerCamelCase__ = type_sequence_label_size
lowerCamelCase__ = initializer_range
lowerCamelCase__ = scope
# in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
lowerCamelCase__ = (image_size // patch_size) ** 2
lowerCamelCase__ = num_patches + 1
def UpperCamelCase_ ( self ):
lowerCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowerCamelCase__ = None
if self.use_labels:
lowerCamelCase__ = ids_tensor([self.batch_size] ,self.type_sequence_label_size )
lowerCamelCase__ = self.get_config()
return config, pixel_values, labels
def UpperCamelCase_ ( self ):
return ViTMSNConfig(
image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,initializer_range=self.initializer_range ,)
def UpperCamelCase_ ( self ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ):
lowerCamelCase__ = ViTMSNModel(config=_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.eval()
lowerCamelCase__ = model(_lowerCAmelCase )
self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) )
def UpperCamelCase_ ( self ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ):
lowerCamelCase__ = self.type_sequence_label_size
lowerCamelCase__ = ViTMSNForImageClassification(_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.eval()
lowerCamelCase__ = model(_lowerCAmelCase ,labels=_lowerCAmelCase )
print("""Pixel and labels shape: {pixel_values.shape}, {labels.shape}""" )
print("""Labels: {labels}""" )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) )
# test greyscale images
lowerCamelCase__ = 1
lowerCamelCase__ = ViTMSNForImageClassification(_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.eval()
lowerCamelCase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
lowerCamelCase__ = model(_lowerCAmelCase )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) )
def UpperCamelCase_ ( self ):
lowerCamelCase__ = self.prepare_config_and_inputs()
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = config_and_inputs
lowerCamelCase__ = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_torch
class UpperCamelCase__ (a ,a ,unittest.TestCase ):
'''simple docstring'''
_UpperCamelCase = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
_UpperCamelCase = (
{'feature-extraction': ViTMSNModel, 'image-classification': ViTMSNForImageClassification}
if is_torch_available()
else {}
)
_UpperCamelCase = False
_UpperCamelCase = False
_UpperCamelCase = False
_UpperCamelCase = False
def UpperCamelCase_ ( self ):
lowerCamelCase__ = ViTMSNModelTester(self )
lowerCamelCase__ = ConfigTester(self ,config_class=_lowerCAmelCase ,has_text_modality=_lowerCAmelCase ,hidden_size=37 )
def UpperCamelCase_ ( self ):
self.config_tester.run_common_tests()
@unittest.skip(reason="""ViTMSN does not use inputs_embeds""" )
def UpperCamelCase_ ( self ):
pass
def UpperCamelCase_ ( self ):
lowerCamelCase__ , lowerCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCamelCase__ = model_class(_lowerCAmelCase )
self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) )
lowerCamelCase__ = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(_lowerCAmelCase ,nn.Linear ) )
def UpperCamelCase_ ( self ):
lowerCamelCase__ , lowerCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCamelCase__ = model_class(_lowerCAmelCase )
lowerCamelCase__ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowerCamelCase__ = [*signature.parameters.keys()]
lowerCamelCase__ = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] ,_lowerCAmelCase )
def UpperCamelCase_ ( self ):
lowerCamelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_lowerCAmelCase )
def UpperCamelCase_ ( self ):
lowerCamelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase )
@slow
def UpperCamelCase_ ( self ):
for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCamelCase__ = ViTMSNModel.from_pretrained(_lowerCAmelCase )
self.assertIsNotNone(_lowerCAmelCase )
def A__ ( ):
lowerCamelCase__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
return image
@require_torch
@require_vision
class UpperCamelCase__ (unittest.TestCase ):
'''simple docstring'''
@cached_property
def UpperCamelCase_ ( self ):
return ViTImageProcessor.from_pretrained("""facebook/vit-msn-small""" ) if is_vision_available() else None
@slow
def UpperCamelCase_ ( self ):
torch.manual_seed(2 )
lowerCamelCase__ = ViTMSNForImageClassification.from_pretrained("""facebook/vit-msn-small""" ).to(_lowerCAmelCase )
lowerCamelCase__ = self.default_image_processor
lowerCamelCase__ = prepare_img()
lowerCamelCase__ = image_processor(images=_lowerCAmelCase ,return_tensors="""pt""" ).to(_lowerCAmelCase )
# forward pass
with torch.no_grad():
lowerCamelCase__ = model(**_lowerCAmelCase )
# verify the logits
lowerCamelCase__ = torch.Size((1, 10_00) )
self.assertEqual(outputs.logits.shape ,_lowerCAmelCase )
lowerCamelCase__ = torch.tensor([-0.0803, -0.4454, -0.2375] ).to(_lowerCAmelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] ,_lowerCAmelCase ,atol=1E-4 ) )
| 50 |
import json
import os
import tempfile
import datasets
from utils import generate_example_dataset, get_duration
lowerCAmelCase__ = 5_0_0_0_0
lowerCAmelCase__ = 5_0_0_0
lowerCAmelCase__ , lowerCAmelCase__ = os.path.split(__file__)
lowerCAmelCase__ = os.path.join(RESULTS_BASEPATH, """results""", RESULTS_FILENAME.replace(""".py""", """.json"""))
@get_duration
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: datasets.Dataset , SCREAMING_SNAKE_CASE_: List[Any] ) -> str:
'''simple docstring'''
for i in range(SCREAMING_SNAKE_CASE_ ):
A__ = dataset[i]
@get_duration
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: datasets.Dataset , SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: List[str] ) -> str:
'''simple docstring'''
for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ):
A__ = dataset[i : i + batch_size]
@get_duration
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: datasets.Dataset , SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: List[str] ) -> Optional[int]:
'''simple docstring'''
with dataset.formatted_as(type=SCREAMING_SNAKE_CASE_ ):
for i in range(SCREAMING_SNAKE_CASE_ ):
A__ = dataset[i]
@get_duration
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: datasets.Dataset , SCREAMING_SNAKE_CASE_: int , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: List[Any] ) -> Any:
'''simple docstring'''
with dataset.formatted_as(type=SCREAMING_SNAKE_CASE_ ):
for i in range(0 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
A__ = dataset[i : i + batch_size]
def lowerCAmelCase__ ( ) -> Any:
'''simple docstring'''
A__ = {"num examples": SPEED_TEST_N_EXAMPLES}
A__ = [
(read, {"length": SMALL_TEST}),
(read, {"length": SPEED_TEST_N_EXAMPLES}),
(read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 1_0}),
(read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 1_0_0}),
(read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 1_0_0_0}),
(read_formatted, {"type": "numpy", "length": SMALL_TEST}),
(read_formatted, {"type": "pandas", "length": SMALL_TEST}),
(read_formatted, {"type": "torch", "length": SMALL_TEST}),
(read_formatted, {"type": "tensorflow", "length": SMALL_TEST}),
(read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 1_0}),
(read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 1_0_0_0}),
]
A__ = [
(read, {"length": SMALL_TEST}),
(read, {"length": SPEED_TEST_N_EXAMPLES}),
(read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 1_0}),
(read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 1_0_0}),
(read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 1_0_0_0}),
(read_formatted, {"type": "numpy", "length": SMALL_TEST}),
(read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 1_0}),
(read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 1_0_0_0}),
]
with tempfile.TemporaryDirectory() as tmp_dir:
print("generating dataset" )
A__ = datasets.Features(
{"list": datasets.Sequence(datasets.Value("float32" ) ), "numbers": datasets.Value("float32" )} )
A__ = generate_example_dataset(
os.path.join(SCREAMING_SNAKE_CASE_ , "dataset.arrow" ) , SCREAMING_SNAKE_CASE_ , num_examples=SCREAMING_SNAKE_CASE_ , seq_shapes={"list": (1_0_0,)} , )
print("first set of iterations" )
for func, kwargs in functions:
print(func.__name__ , str(SCREAMING_SNAKE_CASE_ ) )
A__ = func(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
print("shuffling dataset" )
A__ = dataset.shuffle()
print("Second set of iterations (after shuffling" )
for func, kwargs in functions_shuffled:
print("shuffled " , func.__name__ , str(SCREAMING_SNAKE_CASE_ ) )
A__ = func(
SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
with open(SCREAMING_SNAKE_CASE_ , "wb" ) as f:
f.write(json.dumps(SCREAMING_SNAKE_CASE_ ).encode("utf-8" ) )
if __name__ == "__main__": # useful to run the profiler
benchmark_iterating()
| 514 | 0 |
'''simple docstring'''
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union
import pyarrow as pa
if TYPE_CHECKING:
from .features import FeatureType
@dataclass
class lowerCAmelCase__ :
"""simple docstring"""
__UpperCamelCase = 42
__UpperCamelCase = None
# Automatically constructed
__UpperCamelCase = "dict"
__UpperCamelCase = None
__UpperCamelCase = field(default="Translation" , init=lowerCAmelCase_ , repr=lowerCAmelCase_ )
def __call__( self : List[Any] ) -> List[str]:
'''simple docstring'''
return pa.struct({lang: pa.string() for lang in sorted(self.languages )} )
def __lowerCAmelCase ( self : List[Any] ) -> str:
'''simple docstring'''
from .features import Value
return {k: Value('''string''' ) for k in sorted(self.languages )}
@dataclass
class lowerCAmelCase__ :
"""simple docstring"""
__UpperCamelCase = None
__UpperCamelCase = None
__UpperCamelCase = None
# Automatically constructed
__UpperCamelCase = "dict"
__UpperCamelCase = None
__UpperCamelCase = field(default="TranslationVariableLanguages" , init=lowerCAmelCase_ , repr=lowerCAmelCase_ )
def __lowerCAmelCase ( self : int ) -> Optional[int]:
'''simple docstring'''
a__ : Any = sorted(set(self.languages ) ) if self.languages else None
a__ : List[str] = len(self.languages ) if self.languages else None
def __call__( self : List[str] ) -> str:
'''simple docstring'''
return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} )
def __lowerCAmelCase ( self : Optional[Any] , A__ : List[Any] ) -> Union[str, Any]:
'''simple docstring'''
a__ : Union[str, Any] = set(self.languages )
if self.languages and set(__lowerCAmelCase ) - lang_set:
raise ValueError(
F'Some languages in example ({", ".join(sorted(set(__lowerCAmelCase ) - lang_set ) )}) are not in valid set ({", ".join(__lowerCAmelCase )}).' )
# Convert dictionary into tuples, splitting out cases where there are
# multiple translations for a single language.
a__ : Optional[int] = []
for lang, text in translation_dict.items():
if isinstance(__lowerCAmelCase , __lowerCAmelCase ):
translation_tuples.append((lang, text) )
else:
translation_tuples.extend([(lang, el) for el in text] )
# Ensure translations are in ascending order by language code.
a__ , a__ : Any = zip(*sorted(__lowerCAmelCase ) )
return {"language": languages, "translation": translations}
def __lowerCAmelCase ( self : Optional[int] ) -> str:
'''simple docstring'''
from .features import Sequence, Value
return {
"language": Sequence(Value('''string''' ) ),
"translation": Sequence(Value('''string''' ) ),
}
| 707 |
'''simple docstring'''
from typing import List, Optional, Union
import numpy as np
import PIL.Image
from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
ChannelDimension,
PILImageResampling,
get_image_size,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, logging
__SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
class lowerCAmelCase__ ( lowerCAmelCase_ ):
"""simple docstring"""
__UpperCamelCase = ["pixel_values"]
def __init__( self : str , A__ : bool = True , A__ : int = 3_2 , A__ : List[str]=PILImageResampling.BILINEAR , A__ : bool = True , **A__ : Tuple , ) -> None:
'''simple docstring'''
a__ : Optional[int] = do_resize
a__ : List[str] = do_rescale
a__ : Optional[int] = size_divisor
a__ : Any = resample
super().__init__(**A__ )
def __lowerCAmelCase ( self : int , A__ : np.ndarray , A__ : int , A__ : Optional[int] , A__ : Optional[ChannelDimension] = None , **A__ : List[Any] ) -> np.ndarray:
'''simple docstring'''
a__ , a__ : Optional[int] = get_image_size(A__ )
# Rounds the height and width down to the closest multiple of size_divisor
a__ : List[Any] = height // size_divisor * size_divisor
a__ : List[str] = width // size_divisor * size_divisor
a__ : int = resize(A__ , (new_h, new_w) , resample=A__ , data_format=A__ , **A__ )
return image
def __lowerCAmelCase ( self : int , A__ : np.ndarray , A__ : float , A__ : Optional[ChannelDimension] = None , **A__ : Optional[int] ) -> np.ndarray:
'''simple docstring'''
return rescale(image=A__ , scale=A__ , data_format=A__ , **A__ )
def __lowerCAmelCase ( self : List[str] , A__ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , A__ : Optional[bool] = None , A__ : Optional[int] = None , A__ : int=None , A__ : Optional[bool] = None , A__ : Optional[Union[TensorType, str]] = None , A__ : ChannelDimension = ChannelDimension.FIRST , **A__ : str , ) -> BatchFeature:
'''simple docstring'''
a__ : Tuple = do_resize if do_resize is not None else self.do_resize
a__ : List[Any] = do_rescale if do_rescale is not None else self.do_rescale
a__ : Tuple = size_divisor if size_divisor is not None else self.size_divisor
a__ : int = resample if resample is not None else self.resample
if do_resize and size_divisor is None:
raise ValueError('''size_divisor is required for resizing''' )
a__ : int = make_list_of_images(A__ )
if not valid_images(A__ ):
raise ValueError('''Invalid image(s)''' )
# All transformations expect numpy arrays.
a__ : Any = [to_numpy_array(A__ ) for img in images]
if do_resize:
a__ : Optional[Any] = [self.resize(A__ , size_divisor=A__ , resample=A__ ) for image in images]
if do_rescale:
a__ : str = [self.rescale(A__ , scale=1 / 2_5_5 ) for image in images]
a__ : Dict = [to_channel_dimension_format(A__ , A__ ) for image in images]
a__ : List[Any] = {'''pixel_values''': images}
return BatchFeature(data=A__ , tensor_type=A__ )
| 340 | 0 |
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments
def UpperCamelCase_ ( ) -> Optional[Any]:
a__ : Tuple = HfArgumentParser(_UpperCAmelCase )
a__ : Optional[Any] = parser.parse_args_into_dataclasses()[0]
a__ : Union[str, Any] = TensorFlowBenchmark(args=_UpperCAmelCase )
try:
a__ : str = parser.parse_args_into_dataclasses()[0]
except ValueError as e:
a__ : Optional[Any] = "Arg --no_{0} is no longer used, please use --no-{0} instead."
a__ : Optional[int] = " ".join(str(_UpperCAmelCase ).split(" " )[:-1] )
a__ : Optional[int] = ""
a__ : int = eval(str(_UpperCAmelCase ).split(" " )[-1] )
a__ : Optional[int] = []
for arg in depreciated_args:
# arg[2:] removes '--'
if arg[2:] in TensorFlowBenchmark.deprecated_args:
# arg[5:] removes '--no_'
full_error_msg += arg_error_msg.format(arg[5:] )
else:
wrong_args.append(_UpperCAmelCase )
if len(_UpperCAmelCase ) > 0:
a__ : List[str] = full_error_msg + begin_error_msg + str(_UpperCAmelCase )
raise ValueError(_UpperCAmelCase )
benchmark.run()
if __name__ == "__main__":
main()
| 37 |
import argparse
import json
import logging
import os
import shutil
import sys
import tempfile
import unittest
from unittest import mock
import torch
from accelerate.utils import write_basic_config
from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device
from transformers.utils import is_apex_available
logging.basicConfig(level=logging.DEBUG)
a__ : Any = logging.getLogger()
def UpperCAmelCase_ ( ) -> Any:
'''simple docstring'''
A_ = argparse.ArgumentParser()
parser.add_argument('''-f''' )
A_ = parser.parse_args()
return args.f
def UpperCAmelCase_ ( _UpperCAmelCase :Union[str, Any] ) -> str:
'''simple docstring'''
A_ = {}
A_ = os.path.join(_UpperCAmelCase , '''all_results.json''' )
if os.path.exists(_UpperCAmelCase ):
with open(_UpperCAmelCase , '''r''' ) as f:
A_ = json.load(_UpperCAmelCase )
else:
raise ValueError(f'can\'t find {path}' )
return results
def UpperCAmelCase_ ( ) -> Union[str, Any]:
'''simple docstring'''
A_ = torch.cuda.is_available() and torch_device == '''cuda'''
return is_using_cuda and is_apex_available()
a__ : List[Any] = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ):
@classmethod
def __UpperCAmelCase ( cls ):
"""simple docstring"""
A_ = tempfile.mkdtemp()
A_ = os.path.join(cls.tmpdir ,'''default_config.yml''' )
write_basic_config(save_location=cls.configPath )
A_ = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath]
@classmethod
def __UpperCAmelCase ( cls ):
"""simple docstring"""
shutil.rmtree(cls.tmpdir )
@mock.patch.dict(os.environ ,{'''WANDB_MODE''': '''offline'''} )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.get_auto_remove_tmp_dir()
A_ = f'\n {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --seed=42\n --checkpointing_steps epoch\n --with_tracking\n '.split()
if is_cuda_and_apex_available():
testargs.append('''--fp16''' )
run_command(self._launch_args + testargs )
A_ = get_results(__snake_case )
self.assertGreaterEqual(result['''eval_accuracy'''] ,0.75 )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''glue_no_trainer''' ) ) )
@mock.patch.dict(os.environ ,{'''WANDB_MODE''': '''offline'''} )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.get_auto_remove_tmp_dir()
A_ = f'\n {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py\n --model_name_or_path distilgpt2\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --block_size 128\n --per_device_train_batch_size 5\n --per_device_eval_batch_size 5\n --num_train_epochs 2\n --output_dir {tmp_dir}\n --checkpointing_steps epoch\n --with_tracking\n '.split()
if torch.cuda.device_count() > 1:
# Skipping because there are not enough batches to train the model + would need a drop_last to work.
return
run_command(self._launch_args + testargs )
A_ = get_results(__snake_case )
self.assertLess(result['''perplexity'''] ,1_0_0 )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''clm_no_trainer''' ) ) )
@mock.patch.dict(os.environ ,{'''WANDB_MODE''': '''offline'''} )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.get_auto_remove_tmp_dir()
A_ = f'\n {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py\n --model_name_or_path distilroberta-base\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --output_dir {tmp_dir}\n --num_train_epochs=1\n --checkpointing_steps epoch\n --with_tracking\n '.split()
run_command(self._launch_args + testargs )
A_ = get_results(__snake_case )
self.assertLess(result['''perplexity'''] ,4_2 )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''mlm_no_trainer''' ) ) )
@mock.patch.dict(os.environ ,{'''WANDB_MODE''': '''offline'''} )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = 7 if get_gpu_count() > 1 else 2
A_ = self.get_auto_remove_tmp_dir()
A_ = f'\n {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/conll/sample.json\n --validation_file tests/fixtures/tests_samples/conll/sample.json\n --output_dir {tmp_dir}\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=2\n --num_train_epochs={epochs}\n --seed 7\n --checkpointing_steps epoch\n --with_tracking\n '.split()
run_command(self._launch_args + testargs )
A_ = get_results(__snake_case )
self.assertGreaterEqual(result['''eval_accuracy'''] ,0.75 )
self.assertLess(result['''train_loss'''] ,0.5 )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''ner_no_trainer''' ) ) )
@unittest.skip(reason='''Fix me @muellerzr''' )
@mock.patch.dict(os.environ ,{'''WANDB_MODE''': '''offline'''} )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.get_auto_remove_tmp_dir()
A_ = f'\n {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py\n --model_name_or_path bert-base-uncased\n --version_2_with_negative\n --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n --output_dir {tmp_dir}\n --seed=42\n --max_train_steps=10\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n --with_tracking\n '.split()
run_command(self._launch_args + testargs )
A_ = get_results(__snake_case )
# Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics.
self.assertGreaterEqual(result['''eval_f1'''] ,2_8 )
self.assertGreaterEqual(result['''eval_exact'''] ,2_8 )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''qa_no_trainer''' ) ) )
@mock.patch.dict(os.environ ,{'''WANDB_MODE''': '''offline'''} )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.get_auto_remove_tmp_dir()
A_ = f'\n {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/swag/sample.json\n --validation_file tests/fixtures/tests_samples/swag/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=20\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --with_tracking\n '.split()
run_command(self._launch_args + testargs )
A_ = get_results(__snake_case )
self.assertGreaterEqual(result['''eval_accuracy'''] ,0.8 )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''swag_no_trainer''' ) ) )
@slow
@mock.patch.dict(os.environ ,{'''WANDB_MODE''': '''offline'''} )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.get_auto_remove_tmp_dir()
A_ = f'\n {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py\n --model_name_or_path t5-small\n --train_file tests/fixtures/tests_samples/xsum/sample.json\n --validation_file tests/fixtures/tests_samples/xsum/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=50\n --num_warmup_steps=8\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n --with_tracking\n '.split()
run_command(self._launch_args + testargs )
A_ = get_results(__snake_case )
self.assertGreaterEqual(result['''eval_rouge1'''] ,1_0 )
self.assertGreaterEqual(result['''eval_rouge2'''] ,2 )
self.assertGreaterEqual(result['''eval_rougeL'''] ,7 )
self.assertGreaterEqual(result['''eval_rougeLsum'''] ,7 )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''summarization_no_trainer''' ) ) )
@slow
@mock.patch.dict(os.environ ,{'''WANDB_MODE''': '''offline'''} )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.get_auto_remove_tmp_dir()
A_ = f'\n {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py\n --model_name_or_path sshleifer/student_marian_en_ro_6_1\n --source_lang en\n --target_lang ro\n --train_file tests/fixtures/tests_samples/wmt16/sample.json\n --validation_file tests/fixtures/tests_samples/wmt16/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=50\n --num_warmup_steps=8\n --num_beams=6\n --learning_rate=3e-3\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --source_lang en_XX\n --target_lang ro_RO\n --checkpointing_steps epoch\n --with_tracking\n '.split()
run_command(self._launch_args + testargs )
A_ = get_results(__snake_case )
self.assertGreaterEqual(result['''eval_bleu'''] ,3_0 )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''translation_no_trainer''' ) ) )
@slow
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = logging.StreamHandler(sys.stdout )
logger.addHandler(__snake_case )
A_ = self.get_auto_remove_tmp_dir()
A_ = f'\n {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py\n --dataset_name huggingface/semantic-segmentation-test-sample\n --output_dir {tmp_dir}\n --max_train_steps=10\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n '.split()
run_command(self._launch_args + testargs )
A_ = get_results(__snake_case )
self.assertGreaterEqual(result['''eval_overall_accuracy'''] ,0.10 )
@mock.patch.dict(os.environ ,{'''WANDB_MODE''': '''offline'''} )
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = self.get_auto_remove_tmp_dir()
A_ = f'\n {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py\n --model_name_or_path google/vit-base-patch16-224-in21k\n --dataset_name hf-internal-testing/cats_vs_dogs_sample\n --learning_rate 1e-4\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 1\n --max_train_steps 2\n --train_val_split 0.1\n --seed 42\n --output_dir {tmp_dir}\n --with_tracking\n --checkpointing_steps 1\n '.split()
if is_cuda_and_apex_available():
testargs.append('''--fp16''' )
run_command(self._launch_args + testargs )
A_ = get_results(__snake_case )
# The base model scores a 25%
self.assertGreaterEqual(result['''eval_accuracy'''] ,0.6 )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''step_1''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__snake_case ,'''image_classification_no_trainer''' ) ) )
| 188 | 0 |
"""simple docstring"""
from math import sqrt
def lowercase (_snake_case ) -> List[Any]:
'''simple docstring'''
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 ,int(sqrt(UpperCAmelCase__ ) + 1 ) ,6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def lowercase (_snake_case = 10001 ) -> Optional[int]:
'''simple docstring'''
__UpperCamelCase = 0
__UpperCamelCase = 1
while count != nth and number < 3:
number += 1
if is_prime(UpperCAmelCase__ ):
count += 1
while count != nth:
number += 2
if is_prime(UpperCAmelCase__ ):
count += 1
return number
if __name__ == "__main__":
print(f"""{solution() = }""")
| 714 |
"""simple docstring"""
from typing import List, Union
from ..utils import (
add_end_docstrings,
is_tf_available,
is_torch_available,
is_vision_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_tf_available():
import tensorflow as tf
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
from ..tf_utils import stable_softmax
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
_A = logging.get_logger(__name__)
@add_end_docstrings(snake_case__ )
class __UpperCAmelCase ( snake_case__ ):
"""simple docstring"""
def __init__( self : List[str] , *A_ : Dict , **A_ : Any )-> Any:
super().__init__(*A_ , **A_ )
requires_backends(self , "vision" )
self.check_model_type(
TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
if self.framework == "tf"
else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING )
def A ( self : int , A_ : List[Any]=None )-> Tuple:
__UpperCamelCase = {}
if top_k is not None:
__UpperCamelCase = top_k
return {}, {}, postprocess_params
def __call__( self : str , A_ : Union[str, List[str], "Image.Image", List["Image.Image"]] , **A_ : Tuple )-> str:
return super().__call__(A_ , **A_ )
def A ( self : Union[str, Any] , A_ : int )-> Tuple:
__UpperCamelCase = load_image(A_ )
__UpperCamelCase = self.image_processor(images=A_ , return_tensors=self.framework )
return model_inputs
def A ( self : str , A_ : Union[str, Any] )-> Union[str, Any]:
__UpperCamelCase = self.model(**A_ )
return model_outputs
def A ( self : Union[str, Any] , A_ : Any , A_ : Tuple=5 )-> int:
if top_k > self.model.config.num_labels:
__UpperCamelCase = self.model.config.num_labels
if self.framework == "pt":
__UpperCamelCase = model_outputs.logits.softmax(-1 )[0]
__UpperCamelCase , __UpperCamelCase = probs.topk(A_ )
elif self.framework == "tf":
__UpperCamelCase = stable_softmax(model_outputs.logits , axis=-1 )[0]
__UpperCamelCase = tf.math.top_k(A_ , k=A_ )
__UpperCamelCase , __UpperCamelCase = topk.values.numpy(), topk.indices.numpy()
else:
raise ValueError(f"""Unsupported framework: {self.framework}""" )
__UpperCamelCase = scores.tolist()
__UpperCamelCase = ids.tolist()
return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(A_ , A_ )]
| 228 | 0 |
'''simple docstring'''
import math
import sys
import cva
import numpy as np
def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> np.ndarray:
# For applying gaussian function for each element in matrix.
_a : Optional[Any] = math.sqrt(lowerCAmelCase_ )
_a : str = 1 / (sigma * math.sqrt(2 * math.pi ))
return cons * np.exp(-((img / sigma) ** 2) * 0.5 )
def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> np.ndarray:
_a : Optional[int] = kernel_size // 2
return img[x - half : x + half + 1, y - half : y + half + 1]
def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> np.ndarray:
# Creates a gaussian kernel of given dimension.
_a : str = np.zeros((kernel_size, kernel_size) )
for i in range(0 , lowerCAmelCase_ ):
for j in range(0 , lowerCAmelCase_ ):
_a : Union[str, Any] = math.sqrt(
abs(i - kernel_size // 2 ) ** 2 + abs(j - kernel_size // 2 ) ** 2 )
return vec_gaussian(lowerCAmelCase_ , lowerCAmelCase_ )
def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) -> np.ndarray:
_a : int = np.zeros(img.shape )
_a : List[str] = get_gauss_kernel(lowerCAmelCase_ , lowerCAmelCase_ )
_a , _a : List[Any] = img.shape
for i in range(kernel_size // 2 , size_x - kernel_size // 2 ):
for j in range(kernel_size // 2 , size_y - kernel_size // 2 ):
_a : Optional[int] = get_slice(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
_a : Optional[Any] = img_s - img_s[kernel_size // 2, kernel_size // 2]
_a : Tuple = vec_gaussian(lowerCAmelCase_ , lowerCAmelCase_ )
_a : Union[str, Any] = np.multiply(lowerCAmelCase_ , lowerCAmelCase_ )
_a : Any = np.multiply(lowerCAmelCase_ , lowerCAmelCase_ )
_a : Optional[int] = np.sum(lowerCAmelCase_ ) / np.sum(lowerCAmelCase_ )
_a : int = val
return imga
def __lowerCamelCase ( lowerCAmelCase_ ) -> tuple:
_a : Tuple = args[1] if args[1:] else '../image_data/lena.jpg'
_a : Dict = float(args[2] ) if args[2:] else 1.0
_a : Any = float(args[3] ) if args[3:] else 1.0
if args[4:]:
_a : List[str] = int(args[4] )
_a : Union[str, Any] = kernel_size + abs(kernel_size % 2 - 1 )
else:
_a : List[Any] = 5
return filename, spatial_variance, intensity_variance, kernel_size
if __name__ == "__main__":
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = parse_args(sys.argv)
__lowerCAmelCase = cva.imread(filename, 0)
cva.imshow('''input image''', img)
__lowerCAmelCase = img / 255
__lowerCAmelCase = out.astype('''float32''')
__lowerCAmelCase = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size)
__lowerCAmelCase = out * 255
__lowerCAmelCase = np.uinta(out)
cva.imshow('''output image''', out)
cva.waitKey(0)
cva.destroyAllWindows()
| 358 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available
__lowerCAmelCase = {
'''configuration_ernie''': ['''ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ErnieConfig''', '''ErnieOnnxConfig'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase = [
'''ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''ErnieForCausalLM''',
'''ErnieForMaskedLM''',
'''ErnieForMultipleChoice''',
'''ErnieForNextSentencePrediction''',
'''ErnieForPreTraining''',
'''ErnieForQuestionAnswering''',
'''ErnieForSequenceClassification''',
'''ErnieForTokenClassification''',
'''ErnieModel''',
'''ErniePreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_ernie import (
ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,
ErnieForCausalLM,
ErnieForMaskedLM,
ErnieForMultipleChoice,
ErnieForNextSentencePrediction,
ErnieForPreTraining,
ErnieForQuestionAnswering,
ErnieForSequenceClassification,
ErnieForTokenClassification,
ErnieModel,
ErniePreTrainedModel,
)
else:
import sys
__lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 358 | 1 |
"""simple docstring"""
import inspect
import os
import sys
import unittest
import accelerate
from accelerate.test_utils import execute_subprocess_async, require_tpu
class A_ ( unittest.TestCase ):
def _snake_case ( self : int ) -> str:
__magic_name__ = inspect.getfile(accelerate.test_utils )
__magic_name__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["scripts", "test_script.py"] )
__magic_name__ = os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] )
@require_tpu
def _snake_case ( self : str ) -> Union[str, Any]:
__magic_name__ = f'''
{self.test_dir}/xla_spawn.py
--num_cores 8
{self.test_file_path}
'''.split()
__magic_name__ = [sys.executable] + distributed_args
execute_subprocess_async(__lowerCamelCase , env=os.environ.copy() )
| 468 |
"""simple docstring"""
import unittest
import numpy as np
import torch
from torch import nn
from transformers import (
CLIPImageProcessor,
CLIPTextConfig,
CLIPTextModelWithProjection,
CLIPTokenizer,
CLIPVisionConfig,
CLIPVisionModelWithProjection,
)
from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class A_ ( snake_case_ , unittest.TestCase ):
UpperCAmelCase__ = KandinskyVaaPriorPipeline
UpperCAmelCase__ = ['''prompt''']
UpperCAmelCase__ = ['''prompt''', '''negative_prompt''']
UpperCAmelCase__ = [
'''num_images_per_prompt''',
'''generator''',
'''num_inference_steps''',
'''latents''',
'''negative_prompt''',
'''guidance_scale''',
'''output_type''',
'''return_dict''',
]
UpperCAmelCase__ = False
@property
def _snake_case ( self : Dict ) -> Dict:
return 3_2
@property
def _snake_case ( self : Tuple ) -> Tuple:
return 3_2
@property
def _snake_case ( self : Dict ) -> Optional[int]:
return self.time_input_dim
@property
def _snake_case ( self : List[Any] ) -> str:
return self.time_input_dim * 4
@property
def _snake_case ( self : List[str] ) -> List[Any]:
return 1_0_0
@property
def _snake_case ( self : List[str] ) -> Tuple:
__magic_name__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
return tokenizer
@property
def _snake_case ( self : Optional[int] ) -> Optional[int]:
torch.manual_seed(0 )
__magic_name__ = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , )
return CLIPTextModelWithProjection(__lowerCamelCase )
@property
def _snake_case ( self : List[str] ) -> Union[str, Any]:
torch.manual_seed(0 )
__magic_name__ = {
"num_attention_heads": 2,
"attention_head_dim": 1_2,
"embedding_dim": self.text_embedder_hidden_size,
"num_layers": 1,
}
__magic_name__ = PriorTransformer(**__lowerCamelCase )
# clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
__magic_name__ = nn.Parameter(torch.ones(model.clip_std.shape ) )
return model
@property
def _snake_case ( self : Union[str, Any] ) -> Union[str, Any]:
torch.manual_seed(0 )
__magic_name__ = CLIPVisionConfig(
hidden_size=self.text_embedder_hidden_size , image_size=2_2_4 , projection_dim=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1_4 , )
__magic_name__ = CLIPVisionModelWithProjection(__lowerCamelCase )
return model
@property
def _snake_case ( self : Union[str, Any] ) -> int:
__magic_name__ = CLIPImageProcessor(
crop_size=2_2_4 , do_center_crop=__lowerCamelCase , do_normalize=__lowerCamelCase , do_resize=__lowerCamelCase , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=2_2_4 , )
return image_processor
def _snake_case ( self : List[Any] ) -> Optional[Any]:
__magic_name__ = self.dummy_prior
__magic_name__ = self.dummy_image_encoder
__magic_name__ = self.dummy_text_encoder
__magic_name__ = self.dummy_tokenizer
__magic_name__ = self.dummy_image_processor
__magic_name__ = UnCLIPScheduler(
variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=1_0_0_0 , clip_sample=__lowerCamelCase , clip_sample_range=10.0 , )
__magic_name__ = {
"prior": prior,
"image_encoder": image_encoder,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"scheduler": scheduler,
"image_processor": image_processor,
}
return components
def _snake_case ( self : int , __lowerCamelCase : List[Any] , __lowerCamelCase : str=0 ) -> Optional[int]:
if str(__lowerCamelCase ).startswith("mps" ):
__magic_name__ = torch.manual_seed(__lowerCamelCase )
else:
__magic_name__ = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase )
__magic_name__ = {
"prompt": "horse",
"generator": generator,
"guidance_scale": 4.0,
"num_inference_steps": 2,
"output_type": "np",
}
return inputs
def _snake_case ( self : Optional[Any] ) -> Optional[Any]:
__magic_name__ = "cpu"
__magic_name__ = self.get_dummy_components()
__magic_name__ = self.pipeline_class(**__lowerCamelCase )
__magic_name__ = pipe.to(__lowerCamelCase )
pipe.set_progress_bar_config(disable=__lowerCamelCase )
__magic_name__ = pipe(**self.get_dummy_inputs(__lowerCamelCase ) )
__magic_name__ = output.image_embeds
__magic_name__ = pipe(
**self.get_dummy_inputs(__lowerCamelCase ) , return_dict=__lowerCamelCase , )[0]
__magic_name__ = image[0, -1_0:]
__magic_name__ = image_from_tuple[0, -1_0:]
assert image.shape == (1, 3_2)
__magic_name__ = np.array(
[-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
@skip_mps
def _snake_case ( self : Dict ) -> List[str]:
__magic_name__ = torch_device == "cpu"
__magic_name__ = True
__magic_name__ = False
self._test_inference_batch_single_identical(
test_max_difference=__lowerCamelCase , relax_max_difference=__lowerCamelCase , test_mean_pixel_difference=__lowerCamelCase , )
@skip_mps
def _snake_case ( self : Tuple ) -> Tuple:
__magic_name__ = torch_device == "cpu"
__magic_name__ = False
self._test_attention_slicing_forward_pass(
test_max_difference=__lowerCamelCase , test_mean_pixel_difference=__lowerCamelCase , )
| 468 | 1 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
from ..models.clipseg import CLIPSegForImageSegmentation
from ..utils import is_vision_available, requires_backends
from .base import PipelineTool
if is_vision_available():
from PIL import Image
class _snake_case ( A__ ):
_lowercase : List[Any] = (
'''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.'''
'''It takes two arguments named `image` which should be the original image, and `label` which should be a text '''
'''describing the elements what should be identified in the segmentation mask. The tool returns the mask.'''
)
_lowercase : Any = '''CIDAS/clipseg-rd64-refined'''
_lowercase : List[str] = '''image_segmenter'''
_lowercase : str = CLIPSegForImageSegmentation
_lowercase : List[Any] = ['''image''', '''text''']
_lowercase : List[str] = ['''image''']
def __init__( self , *a , **a) -> str:
requires_backends(self , ['vision'])
super().__init__(*a , **a)
def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[Any]:
return self.pre_processor(text=[label] , images=[image] , padding=a , return_tensors='pt')
def SCREAMING_SNAKE_CASE__ ( self , a) -> str:
with torch.no_grad():
SCREAMING_SNAKE_CASE = self.model(**a).logits
return logits
def SCREAMING_SNAKE_CASE__ ( self , a) -> Tuple:
SCREAMING_SNAKE_CASE = outputs.cpu().detach().numpy()
SCREAMING_SNAKE_CASE = 0
SCREAMING_SNAKE_CASE = 1
return Image.fromarray((array * 255).astype(np.uinta))
| 73 |
import os
def __UpperCAmelCase( ):
with open(os.path.dirname(lowercase_ ) + '''/p022_names.txt''' ) as file:
_lowerCamelCase : Optional[int] = str(file.readlines()[0] )
_lowerCamelCase : List[Any] = names.replace('''"''' , '''''' ).split(''',''' )
names.sort()
_lowerCamelCase : Optional[int] = 0
_lowerCamelCase : Tuple = 0
for i, name in enumerate(lowercase_ ):
for letter in name:
name_score += ord(lowercase_ ) - 64
total_score += (i + 1) * name_score
_lowerCamelCase : Optional[int] = 0
return total_score
if __name__ == "__main__":
print(solution())
| 114 | 0 |
'''simple docstring'''
import requests
SCREAMING_SNAKE_CASE_ = 'YOUR API KEY'
def UpperCamelCase__ ( _lowercase : str , _lowercase : str = giphy_api_key ) -> list:
__UpperCAmelCase: Optional[int] = """+""".join(query.split() )
__UpperCAmelCase: List[str] = F'''https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}'''
__UpperCAmelCase: Union[str, Any] = requests.get(_lowercase ).json()["""data"""]
return [gif["url"] for gif in gifs]
if __name__ == "__main__":
print('\n'.join(get_gifs('space ship')))
| 466 |
'''simple docstring'''
from __future__ import annotations
import time
import numpy as np
SCREAMING_SNAKE_CASE_ = [8, 5, 9, 7]
SCREAMING_SNAKE_CASE_ = [
[2, 0, 1, 1],
[0, 1, 2, 1],
[4, 0, 0, 3],
[0, 2, 1, 0],
[1, 0, 3, 0],
]
SCREAMING_SNAKE_CASE_ = [
[3, 2, 1, 4],
[0, 2, 5, 2],
[5, 1, 0, 5],
[1, 5, 3, 0],
[3, 0, 3, 3],
]
class a :
"""simple docstring"""
def __init__( self , snake_case_ , snake_case_ , snake_case_ , ):
'''simple docstring'''
__UpperCAmelCase: str = claim_vector
__UpperCAmelCase: Optional[Any] = allocated_resources_table
__UpperCAmelCase: List[str] = maximum_claim_table
def lowercase_ ( self ):
'''simple docstring'''
return [
sum(p_item[i] for p_item in self.__allocated_resources_table )
for i in range(len(self.__allocated_resources_table[0] ) )
]
def lowercase_ ( self ):
'''simple docstring'''
return np.array(self.__claim_vector ) - np.array(
self.__processes_resource_summation() )
def lowercase_ ( self ):
'''simple docstring'''
return [
list(np.array(self.__maximum_claim_table[i] ) - np.array(snake_case_ ) )
for i, allocated_resource in enumerate(self.__allocated_resources_table )
]
def lowercase_ ( self ):
'''simple docstring'''
return {self.__need().index(snake_case_ ): i for i in self.__need()}
def lowercase_ ( self , **snake_case_ ):
'''simple docstring'''
__UpperCAmelCase: Dict = self.__need()
__UpperCAmelCase: Optional[Any] = self.__allocated_resources_table
__UpperCAmelCase: int = self.__available_resources()
__UpperCAmelCase: List[Any] = self.__need_index_manager()
for kw, val in kwargs.items():
if kw and val is True:
self.__pretty_data()
print("""_""" * 50 + """\n""" )
while need_list:
__UpperCAmelCase: Any = False
for each_need in need_list:
__UpperCAmelCase: Any = True
for index, need in enumerate(snake_case_ ):
if need > available_resources[index]:
__UpperCAmelCase: Tuple = False
break
if execution:
__UpperCAmelCase: Optional[int] = True
# get the original index of the process from ind_ctrl db
for original_need_index, need_clone in need_index_manager.items():
if each_need == need_clone:
__UpperCAmelCase: Tuple = original_need_index
print(F'''Process {process_number + 1} is executing.''' )
# remove the process run from stack
need_list.remove(snake_case_ )
# update available/freed resources stack
__UpperCAmelCase: Dict = np.array(snake_case_ ) + np.array(
alloc_resources_table[process_number] )
print(
"""Updated available resource stack for processes: """
+ """ """.join([str(snake_case_ ) for x in available_resources] ) )
break
if safe:
print("""The process is in a safe state.\n""" )
else:
print("""System in unsafe state. Aborting...\n""" )
break
def lowercase_ ( self ):
'''simple docstring'''
print(""" """ * 9 + """Allocated Resource Table""" )
for item in self.__allocated_resources_table:
print(
F'''P{self.__allocated_resources_table.index(snake_case_ ) + 1}'''
+ """ """.join(F'''{it:>8}''' for it in item )
+ """\n""" )
print(""" """ * 9 + """System Resource Table""" )
for item in self.__maximum_claim_table:
print(
F'''P{self.__maximum_claim_table.index(snake_case_ ) + 1}'''
+ """ """.join(F'''{it:>8}''' for it in item )
+ """\n""" )
print(
"""Current Usage by Active Processes: """
+ """ """.join(str(snake_case_ ) for x in self.__claim_vector ) )
print(
"""Initial Available Resources: """
+ """ """.join(str(snake_case_ ) for x in self.__available_resources() ) )
time.sleep(1 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 466 | 1 |
"""simple docstring"""
from abc import ABC, abstractmethod
from typing import Optional, Union
from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit
from ..utils.typing import NestedDataStructureLike, PathLike
class lowercase__ ( A_ ):
def __init__( self , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ) -> str:
_lowerCamelCase : str = path_or_paths
_lowerCamelCase : Optional[Any] = split if split or isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) else """train"""
_lowerCamelCase : int = features
_lowerCamelCase : Any = cache_dir
_lowerCamelCase : Optional[Any] = keep_in_memory
_lowerCamelCase : Optional[int] = streaming
_lowerCamelCase : Union[str, Any] = num_proc
_lowerCamelCase : Union[str, Any] = kwargs
@abstractmethod
def UpperCamelCase_ ( self) -> Union[Dataset, DatasetDict, IterableDataset, IterableDatasetDict]:
pass
class lowercase__ ( A_ ):
def __init__( self , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ) -> Tuple:
_lowerCamelCase : Tuple = features
_lowerCamelCase : Any = cache_dir
_lowerCamelCase : int = keep_in_memory
_lowerCamelCase : Dict = streaming
_lowerCamelCase : List[str] = num_proc
_lowerCamelCase : List[Any] = kwargs
@abstractmethod
def UpperCamelCase_ ( self) -> Union[Dataset, IterableDataset]:
pass
| 88 |
from typing import Any, Dict, Optional
import torch
import torch.nn.functional as F
from torch import nn
from ..utils import maybe_allow_in_graph
from .activations import get_activation
from .attention_processor import Attention
from .embeddings import CombinedTimestepLabelEmbeddings
@maybe_allow_in_graph
class SCREAMING_SNAKE_CASE__ ( nn.Module ):
"""simple docstring"""
def __init__( self : Optional[int] , __A : int , __A : int , __A : int , __A : Union[str, Any]=0.0 , __A : Optional[int] = None , __A : str = "geglu" , __A : Optional[int] = None , __A : bool = False , __A : bool = False , __A : bool = False , __A : bool = False , __A : bool = True , __A : str = "layer_norm" , __A : bool = False , ):
super().__init__()
snake_case__ : str = only_cross_attention
snake_case__ : str = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
snake_case__ : Optional[Any] = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
raise ValueError(
f'''`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to'''
f''' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.''' )
# Define 3 blocks. Each block has its own normalization layer.
# 1. Self-Attn
if self.use_ada_layer_norm:
snake_case__ : Tuple = AdaLayerNorm(__A , __A )
elif self.use_ada_layer_norm_zero:
snake_case__ : Optional[Any] = AdaLayerNormZero(__A , __A )
else:
snake_case__ : List[str] = nn.LayerNorm(__A , elementwise_affine=__A )
snake_case__ : Optional[Any] = Attention(
query_dim=__A , heads=__A , dim_head=__A , dropout=__A , bias=__A , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=__A , )
# 2. Cross-Attn
if cross_attention_dim is not None or double_self_attention:
# We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
# I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
# the second cross attention block.
snake_case__ : Union[str, Any] = (
AdaLayerNorm(__A , __A )
if self.use_ada_layer_norm
else nn.LayerNorm(__A , elementwise_affine=__A )
)
snake_case__ : List[Any] = Attention(
query_dim=__A , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=__A , dim_head=__A , dropout=__A , bias=__A , upcast_attention=__A , ) # is self-attn if encoder_hidden_states is none
else:
snake_case__ : Tuple = None
snake_case__ : List[str] = None
# 3. Feed-forward
snake_case__ : Optional[int] = nn.LayerNorm(__A , elementwise_affine=__A )
snake_case__ : str = FeedForward(__A , dropout=__A , activation_fn=__A , final_dropout=__A )
# let chunk size default to None
snake_case__ : List[Any] = None
snake_case__ : str = 0
def _lowercase ( self : int , __A : Optional[int] , __A : int ):
# Sets chunk feed-forward
snake_case__ : Dict = chunk_size
snake_case__ : str = dim
def _lowercase ( self : List[str] , __A : torch.FloatTensor , __A : Optional[torch.FloatTensor] = None , __A : Optional[torch.FloatTensor] = None , __A : Optional[torch.FloatTensor] = None , __A : Optional[torch.LongTensor] = None , __A : Dict[str, Any] = None , __A : Optional[torch.LongTensor] = None , ):
# Notice that normalization is always applied before the real computation in the following blocks.
# 1. Self-Attention
if self.use_ada_layer_norm:
snake_case__ : Tuple = self.norma(__A , __A )
elif self.use_ada_layer_norm_zero:
snake_case__, snake_case__, snake_case__, snake_case__, snake_case__ : Dict = self.norma(
__A , __A , __A , hidden_dtype=hidden_states.dtype )
else:
snake_case__ : str = self.norma(__A )
snake_case__ : Union[str, Any] = cross_attention_kwargs if cross_attention_kwargs is not None else {}
snake_case__ : Union[str, Any] = self.attna(
__A , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=__A , **__A , )
if self.use_ada_layer_norm_zero:
snake_case__ : str = gate_msa.unsqueeze(1 ) * attn_output
snake_case__ : Dict = attn_output + hidden_states
# 2. Cross-Attention
if self.attna is not None:
snake_case__ : List[str] = (
self.norma(__A , __A ) if self.use_ada_layer_norm else self.norma(__A )
)
snake_case__ : int = self.attna(
__A , encoder_hidden_states=__A , attention_mask=__A , **__A , )
snake_case__ : Dict = attn_output + hidden_states
# 3. Feed-forward
snake_case__ : Any = self.norma(__A )
if self.use_ada_layer_norm_zero:
snake_case__ : int = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
if self._chunk_size is not None:
# "feed_forward_chunk_size" can be used to save memory
if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
raise ValueError(
f'''`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.''' )
snake_case__ : Dict = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
snake_case__ : str = torch.cat(
[self.ff(__A ) for hid_slice in norm_hidden_states.chunk(__A , dim=self._chunk_dim )] , dim=self._chunk_dim , )
else:
snake_case__ : Dict = self.ff(__A )
if self.use_ada_layer_norm_zero:
snake_case__ : List[Any] = gate_mlp.unsqueeze(1 ) * ff_output
snake_case__ : str = ff_output + hidden_states
return hidden_states
class SCREAMING_SNAKE_CASE__ ( nn.Module ):
"""simple docstring"""
def __init__( self : Optional[Any] , __A : int , __A : Optional[int] = None , __A : int = 4 , __A : float = 0.0 , __A : str = "geglu" , __A : bool = False , ):
super().__init__()
snake_case__ : str = int(dim * mult )
snake_case__ : Any = dim_out if dim_out is not None else dim
if activation_fn == "gelu":
snake_case__ : Tuple = GELU(__A , __A )
if activation_fn == "gelu-approximate":
snake_case__ : Union[str, Any] = GELU(__A , __A , approximate="tanh" )
elif activation_fn == "geglu":
snake_case__ : Dict = GEGLU(__A , __A )
elif activation_fn == "geglu-approximate":
snake_case__ : Dict = ApproximateGELU(__A , __A )
snake_case__ : Tuple = nn.ModuleList([] )
# project in
self.net.append(__A )
# project dropout
self.net.append(nn.Dropout(__A ) )
# project out
self.net.append(nn.Linear(__A , __A ) )
# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
if final_dropout:
self.net.append(nn.Dropout(__A ) )
def _lowercase ( self : int , __A : Dict ):
for module in self.net:
snake_case__ : Optional[Any] = module(__A )
return hidden_states
class SCREAMING_SNAKE_CASE__ ( nn.Module ):
"""simple docstring"""
def __init__( self : Union[str, Any] , __A : int , __A : int , __A : str = "none" ):
super().__init__()
snake_case__ : Optional[int] = nn.Linear(__A , __A )
snake_case__ : List[str] = approximate
def _lowercase ( self : List[str] , __A : Optional[Any] ):
if gate.device.type != "mps":
return F.gelu(__A , approximate=self.approximate )
# mps: gelu is not implemented for float16
return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype )
def _lowercase ( self : Any , __A : str ):
snake_case__ : List[str] = self.proj(__A )
snake_case__ : List[Any] = self.gelu(__A )
return hidden_states
class SCREAMING_SNAKE_CASE__ ( nn.Module ):
"""simple docstring"""
def __init__( self : int , __A : int , __A : int ):
super().__init__()
snake_case__ : Any = nn.Linear(__A , dim_out * 2 )
def _lowercase ( self : Dict , __A : Optional[int] ):
if gate.device.type != "mps":
return F.gelu(__A )
# mps: gelu is not implemented for float16
return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype )
def _lowercase ( self : str , __A : List[Any] ):
snake_case__, snake_case__ : Optional[int] = self.proj(__A ).chunk(2 , dim=-1 )
return hidden_states * self.gelu(__A )
class SCREAMING_SNAKE_CASE__ ( nn.Module ):
"""simple docstring"""
def __init__( self : Union[str, Any] , __A : int , __A : int ):
super().__init__()
snake_case__ : Optional[int] = nn.Linear(__A , __A )
def _lowercase ( self : Union[str, Any] , __A : Tuple ):
snake_case__ : List[str] = self.proj(__A )
return x * torch.sigmoid(1.7_0_2 * x )
class SCREAMING_SNAKE_CASE__ ( nn.Module ):
"""simple docstring"""
def __init__( self : Optional[int] , __A : List[Any] , __A : str ):
super().__init__()
snake_case__ : Union[str, Any] = nn.Embedding(__A , __A )
snake_case__ : Optional[int] = nn.SiLU()
snake_case__ : Optional[int] = nn.Linear(__A , embedding_dim * 2 )
snake_case__ : Tuple = nn.LayerNorm(__A , elementwise_affine=__A )
def _lowercase ( self : Any , __A : Dict , __A : str ):
snake_case__ : Any = self.linear(self.silu(self.emb(__A ) ) )
snake_case__, snake_case__ : List[Any] = torch.chunk(__A , 2 )
snake_case__ : Tuple = self.norm(__A ) * (1 + scale) + shift
return x
class SCREAMING_SNAKE_CASE__ ( nn.Module ):
"""simple docstring"""
def __init__( self : str , __A : int , __A : List[str] ):
super().__init__()
snake_case__ : List[str] = CombinedTimestepLabelEmbeddings(__A , __A )
snake_case__ : str = nn.SiLU()
snake_case__ : Optional[Any] = nn.Linear(__A , 6 * embedding_dim , bias=__A )
snake_case__ : Tuple = nn.LayerNorm(__A , elementwise_affine=__A , eps=1e-6 )
def _lowercase ( self : Dict , __A : List[str] , __A : Optional[int] , __A : Any , __A : Optional[Any]=None ):
snake_case__ : List[str] = self.linear(self.silu(self.emb(__A , __A , hidden_dtype=__A ) ) )
snake_case__, snake_case__, snake_case__, snake_case__, snake_case__, snake_case__ : Optional[int] = emb.chunk(6 , dim=1 )
snake_case__ : List[Any] = self.norm(__A ) * (1 + scale_msa[:, None]) + shift_msa[:, None]
return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
class SCREAMING_SNAKE_CASE__ ( nn.Module ):
"""simple docstring"""
def __init__( self : List[Any] , __A : int , __A : int , __A : int , __A : Optional[str] = None , __A : float = 1e-5 ):
super().__init__()
snake_case__ : int = num_groups
snake_case__ : Any = eps
if act_fn is None:
snake_case__ : Dict = None
else:
snake_case__ : Any = get_activation(__A )
snake_case__ : List[str] = nn.Linear(__A , out_dim * 2 )
def _lowercase ( self : str , __A : Optional[Any] , __A : Tuple ):
if self.act:
snake_case__ : List[Any] = self.act(__A )
snake_case__ : Union[str, Any] = self.linear(__A )
snake_case__ : Optional[int] = emb[:, :, None, None]
snake_case__, snake_case__ : List[str] = emb.chunk(2 , dim=1 )
snake_case__ : Dict = F.group_norm(__A , self.num_groups , eps=self.eps )
snake_case__ : List[str] = x * (1 + scale) + shift
return x
| 297 | 0 |
"""simple docstring"""
from diffusers.utils.testing_utils import require_onnxruntime
@require_onnxruntime
class a :
pass
| 254 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCamelCase__ = {'configuration_vit_msn': ['VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMSNConfig']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ = [
'VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST',
'ViTMSNModel',
'ViTMSNForImageClassification',
'ViTMSNPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_vit_msn import (
VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST,
ViTMSNForImageClassification,
ViTMSNModel,
ViTMSNPreTrainedModel,
)
else:
import sys
UpperCamelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 254 | 1 |
from math import factorial
class _lowercase :
'''simple docstring'''
def __init__( self , lowerCamelCase__ , lowerCamelCase__ ):
lowerCAmelCase_: int = real
if isinstance(A_ , A_ ):
lowerCAmelCase_: Dict = [1] * rank
else:
lowerCAmelCase_: Optional[int] = rank
def __repr__( self ):
return (
F'''{self.real}+'''
F'''{"+".join(str(A_ )+"E"+str(n+1 )for n,dual in enumerate(self.duals ) )}'''
)
def _a ( self ):
lowerCAmelCase_: List[Any] = self.duals.copy()
while cur[-1] == 0:
cur.pop(-1 )
return Dual(self.real , A_ )
def __add__( self , lowerCamelCase__ ):
if not isinstance(A_ , A_ ):
return Dual(self.real + other , self.duals )
lowerCAmelCase_: List[str] = self.duals.copy()
lowerCAmelCase_: Union[str, Any] = other.duals.copy()
if len(A_ ) > len(A_ ):
o_dual.extend([1] * (len(A_ ) - len(A_ )) )
elif len(A_ ) < len(A_ ):
s_dual.extend([1] * (len(A_ ) - len(A_ )) )
lowerCAmelCase_: Union[str, Any] = []
for i in range(len(A_ ) ):
new_duals.append(s_dual[i] + o_dual[i] )
return Dual(self.real + other.real , A_ )
SCREAMING_SNAKE_CASE: Any = __add__
def __sub__( self , lowerCamelCase__ ):
return self + other * -1
def __mul__( self , lowerCamelCase__ ):
if not isinstance(A_ , A_ ):
lowerCAmelCase_: Dict = []
for i in self.duals:
new_duals.append(i * other )
return Dual(self.real * other , A_ )
lowerCAmelCase_: Tuple = [0] * (len(self.duals ) + len(other.duals ) + 1)
for i, item in enumerate(self.duals ):
for j, jtem in enumerate(other.duals ):
new_duals[i + j + 1] += item * jtem
for k in range(len(self.duals ) ):
new_duals[k] += self.duals[k] * other.real
for index in range(len(other.duals ) ):
new_duals[index] += other.duals[index] * self.real
return Dual(self.real * other.real , A_ )
SCREAMING_SNAKE_CASE: str = __mul__
def __truediv__( self , lowerCamelCase__ ):
if not isinstance(A_ , A_ ):
lowerCAmelCase_: Any = []
for i in self.duals:
new_duals.append(i / other )
return Dual(self.real / other , A_ )
raise ValueError
def __floordiv__( self , lowerCamelCase__ ):
if not isinstance(A_ , A_ ):
lowerCAmelCase_: Any = []
for i in self.duals:
new_duals.append(i // other )
return Dual(self.real // other , A_ )
raise ValueError
def __pow__( self , lowerCamelCase__ ):
if n < 0 or isinstance(A_ , A_ ):
raise ValueError("power must be a positive integer" )
if n == 0:
return 1
if n == 1:
return self
lowerCAmelCase_: Dict = self
for _ in range(n - 1 ):
x *= self
return x
def snake_case__ ( lowercase , lowercase , lowercase ):
if not callable(lowercase__ ):
raise ValueError("differentiate() requires a function as input for func" )
if not isinstance(lowercase__ , (float, int) ):
raise ValueError("differentiate() requires a float as input for position" )
if not isinstance(lowercase__ , lowercase__ ):
raise ValueError("differentiate() requires an int as input for order" )
lowerCAmelCase_: Dict = Dual(lowercase__ , 1 )
lowerCAmelCase_: List[Any] = func(lowercase__ )
if order == 0:
return result.real
return result.duals[order - 1] * factorial(lowercase__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
def snake_case__ ( lowercase ):
return y**2 * y**4
print(differentiate(f, 9, 2))
| 613 |
"""simple docstring"""
from collections import defaultdict
def a_ ( lowercase__ :int ):
__lowerCamelCase = 1
__lowerCamelCase = True
for v in tree[start]:
if v not in visited:
ret += dfs(lowercase__ )
if ret % 2 == 0:
cuts.append(lowercase__ )
return ret
def a_ ( ):
dfs(1 )
if __name__ == "__main__":
__magic_name__ , __magic_name__ : Tuple = 1_0, 9
__magic_name__ : Tuple = defaultdict(list)
__magic_name__ : dict[int, bool] = {}
__magic_name__ : list[int] = []
__magic_name__ : List[str] = 0
__magic_name__ : Tuple = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (1_0, 8)]
for u, v in edges:
tree[u].append(v)
tree[v].append(u)
even_tree()
print(len(cuts) - 1)
| 281 | 0 |
# Lint as: python3
# pylint: enable=line-too-long
# pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position
a_ = "2.13.1"
import platform
import pyarrow
from packaging import version
if version.parse(platform.python_version()) < version.parse("3.7"):
raise ImportWarning(
"To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match this condition."
)
if version.parse(pyarrow.__version__).major < 8:
raise ImportWarning(
"To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn't match this condition.\n"
"If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`."
)
del platform
del pyarrow
del version
from .arrow_dataset import Dataset
from .arrow_reader import ReadInstruction
from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder
from .combine import concatenate_datasets, interleave_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .download import *
from .features import *
from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled
from .info import DatasetInfo, MetricInfo
from .inspect import (
get_dataset_config_info,
get_dataset_config_names,
get_dataset_infos,
get_dataset_split_names,
inspect_dataset,
inspect_metric,
list_datasets,
list_metrics,
)
from .iterable_dataset import IterableDataset
from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric
from .metric import Metric
from .splits import (
NamedSplit,
NamedSplitAll,
Split,
SplitBase,
SplitDict,
SplitGenerator,
SplitInfo,
SubSplitInfo,
percent,
)
from .tasks import *
from .utils import *
from .utils import logging
# deprecated modules
from datasets import arrow_dataset as _arrow_dataset # isort:skip
from datasets import utils as _utils # isort:skip
from datasets.utils import download_manager as _deprecated_download_manager # isort:skip
a_ = concatenate_datasets
a_ = DownloadConfig
a_ = DownloadManager
a_ = DownloadMode
a_ = DownloadConfig
a_ = DownloadMode
a_ = DownloadManager
del _arrow_dataset, _utils, _deprecated_download_manager
| 375 |
import sys
import webbrowser
import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent
if __name__ == "__main__":
print("Googling.....")
a_ = "https://www.google.com/search?q=" + " ".join(sys.argv[1:])
a_ = requests.get(url, headers={"UserAgent": UserAgent().random})
# res.raise_for_status()
with open("project1a.html", "wb") as out_file: # only for knowing the class
for data in res.iter_content(1_0000):
out_file.write(data)
a_ = BeautifulSoup(res.text, "html.parser")
a_ = list(soup.select(".eZt8xd"))[:5]
print(len(links))
for link in links:
if link.text == "Maps":
webbrowser.open(link.get("href"))
else:
webbrowser.open(f"""https://google.com{link.get('href')}""")
| 375 | 1 |
"""simple docstring"""
from collections import UserDict
from typing import List, Union
from ..utils import (
add_end_docstrings,
is_tf_available,
is_torch_available,
is_vision_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if is_tf_available():
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
from ..tf_utils import stable_softmax
_A = logging.get_logger(__name__)
@add_end_docstrings(_SCREAMING_SNAKE_CASE )
class lowerCamelCase (_SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__( self : Optional[int] , **_snake_case : Union[str, Any] ) -> List[Any]:
super().__init__(**_snake_case )
requires_backends(self , "vision" )
self.check_model_type(
TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if self.framework == "tf"
else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING )
def __call__( self : int , _snake_case : Union[str, List[str], "Image", List["Image"]] , **_snake_case : Dict ) -> Dict:
return super().__call__(_snake_case , **_snake_case )
def lowerCAmelCase_ ( self : List[Any] , **_snake_case : Union[str, Any] ) -> Optional[int]:
SCREAMING_SNAKE_CASE__ = {}
if "candidate_labels" in kwargs:
SCREAMING_SNAKE_CASE__ = kwargs["candidate_labels"]
if "hypothesis_template" in kwargs:
SCREAMING_SNAKE_CASE__ = kwargs["hypothesis_template"]
return preprocess_params, {}, {}
def lowerCAmelCase_ ( self : Dict , _snake_case : List[Any] , _snake_case : List[Any]=None , _snake_case : List[str]="This is a photo of {}." ) -> Tuple:
SCREAMING_SNAKE_CASE__ = load_image(_snake_case )
SCREAMING_SNAKE_CASE__ = self.image_processor(images=[image] , return_tensors=self.framework )
SCREAMING_SNAKE_CASE__ = candidate_labels
SCREAMING_SNAKE_CASE__ = [hypothesis_template.format(_snake_case ) for x in candidate_labels]
SCREAMING_SNAKE_CASE__ = self.tokenizer(_snake_case , return_tensors=self.framework , padding=_snake_case )
SCREAMING_SNAKE_CASE__ = [text_inputs]
return inputs
def lowerCAmelCase_ ( self : Dict , _snake_case : Optional[Any] ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE__ = model_inputs.pop("candidate_labels" )
SCREAMING_SNAKE_CASE__ = model_inputs.pop("text_inputs" )
if isinstance(text_inputs[0] , _snake_case ):
SCREAMING_SNAKE_CASE__ = text_inputs[0]
else:
# Batching case.
SCREAMING_SNAKE_CASE__ = text_inputs[0][0]
SCREAMING_SNAKE_CASE__ = self.model(**_snake_case , **_snake_case )
SCREAMING_SNAKE_CASE__ = {
"candidate_labels": candidate_labels,
"logits": outputs.logits_per_image,
}
return model_outputs
def lowerCAmelCase_ ( self : Optional[int] , _snake_case : Dict ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE__ = model_outputs.pop("candidate_labels" )
SCREAMING_SNAKE_CASE__ = model_outputs["logits"][0]
if self.framework == "pt":
SCREAMING_SNAKE_CASE__ = logits.softmax(dim=-1 ).squeeze(-1 )
SCREAMING_SNAKE_CASE__ = probs.tolist()
if not isinstance(_snake_case , _snake_case ):
SCREAMING_SNAKE_CASE__ = [scores]
elif self.framework == "tf":
SCREAMING_SNAKE_CASE__ = stable_softmax(_snake_case , axis=-1 )
SCREAMING_SNAKE_CASE__ = probs.numpy().tolist()
else:
raise ValueError(F"""Unsupported framework: {self.framework}""" )
SCREAMING_SNAKE_CASE__ = [
{"score": score, "label": candidate_label}
for score, candidate_label in sorted(zip(_snake_case , _snake_case ) , key=lambda _snake_case : -x[0] )
]
return result
| 159 |
"""simple docstring"""
from __future__ import annotations
from collections.abc import Generator
import requests
from bsa import BeautifulSoup
_A = 'https://www.indeed.co.in/jobs?q=mobile+app+development&l='
def SCREAMING_SNAKE_CASE ( __UpperCAmelCase = "mumbai" ) -> Generator[tuple[str, str], None, None]:
SCREAMING_SNAKE_CASE__ = BeautifulSoup(requests.get(url + location ).content , "html.parser" )
# This attribute finds out all the specifics listed in a job
for job in soup.find_all("div" , attrs={"data-tn-component": "organicJob"} ):
SCREAMING_SNAKE_CASE__ = job.find("a" , attrs={"data-tn-element": "jobTitle"} ).text.strip()
SCREAMING_SNAKE_CASE__ = job.find("span" , {"class": "company"} ).text.strip()
yield job_title, company_name
if __name__ == "__main__":
for i, job in enumerate(fetch_jobs('Bangalore'), 1):
print(F'Job {i:>2} is {job[0]} at {job[1]}')
| 159 | 1 |
import argparse
import logging
import os
from datetime import datetime
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, RandomSampler, TensorDataset
from tqdm import tqdm
from transformers import GPTaLMHeadModel
__magic_name__ = logging.getLogger(__name__)
def _A ( lowerCAmelCase_ , lowerCAmelCase_):
'''simple docstring'''
if os.path.exists(_lowerCamelCase):
if os.path.exists(os.path.join(_lowerCamelCase , "config.json")) and os.path.isfile(
os.path.join(_lowerCamelCase , "config.json")):
os.remove(os.path.join(_lowerCamelCase , "config.json"))
if os.path.exists(os.path.join(_lowerCamelCase , "pytorch_model.bin")) and os.path.isfile(
os.path.join(_lowerCamelCase , "pytorch_model.bin")):
os.remove(os.path.join(_lowerCamelCase , "pytorch_model.bin"))
else:
os.makedirs(_lowerCamelCase)
model.save_pretrained(_lowerCamelCase)
def _A ( lowerCAmelCase_ , lowerCAmelCase_=False):
'''simple docstring'''
lowerCamelCase_ : str = 2
if unlogit:
lowerCamelCase_ : Tuple = torch.pow(_lowerCamelCase , _lowerCamelCase)
lowerCamelCase_ : Optional[int] = p * torch.log(_lowerCamelCase)
lowerCamelCase_ : Optional[int] = 0
return -plogp.sum(dim=-1)
def _A ( lowerCAmelCase_):
'''simple docstring'''
logger.info("lv, h >\t" + "\t".join(F"""{x + 1}""" for x in range(len(_lowerCamelCase))))
for row in range(len(_lowerCamelCase)):
if tensor.dtype != torch.long:
logger.info(F"""layer {row + 1}:\t""" + "\t".join(F"""{x:.5f}""" for x in tensor[row].cpu().data))
else:
logger.info(F"""layer {row + 1}:\t""" + "\t".join(F"""{x:d}""" for x in tensor[row].cpu().data))
def _A ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=None , lowerCAmelCase_=False):
'''simple docstring'''
lowerCamelCase_ : List[Any] = model.config.num_hidden_layers, model.config.num_attention_heads
lowerCamelCase_ : Optional[Any] = torch.zeros(_lowerCamelCase , _lowerCamelCase).to(args.device)
lowerCamelCase_ : Union[str, Any] = torch.zeros(_lowerCamelCase , _lowerCamelCase).to(args.device)
if head_mask is None:
lowerCamelCase_ : str = torch.ones(_lowerCamelCase , _lowerCamelCase).to(args.device)
head_mask.requires_grad_(requires_grad=_lowerCamelCase)
# If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
if actually_pruned:
lowerCamelCase_ : Optional[Any] = None
lowerCamelCase_ : Dict = 0.0
lowerCamelCase_ : Optional[Any] = 0.0
for step, inputs in enumerate(tqdm(_lowerCamelCase , desc="Iteration" , disable=args.local_rank not in [-1, 0])):
lowerCamelCase_ : int = tuple(t.to(args.device) for t in inputs)
(lowerCamelCase_ ) : Union[str, Any] = inputs
# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
lowerCamelCase_ : Tuple = model(_lowerCamelCase , labels=_lowerCamelCase , head_mask=_lowerCamelCase)
# (loss), lm_logits, presents, (all hidden_states), (attentions)
lowerCamelCase_ : Optional[Any] = (
outputs[0],
outputs[1],
outputs[-1],
) # Loss and logits are the first, attention the last
loss.backward() # Backpropagate to populate the gradients in the head mask
total_loss += loss.detach().cpu().numpy()
if compute_entropy:
for layer, attn in enumerate(_lowerCamelCase):
lowerCamelCase_ : Tuple = entropy(attn.detach() , _lowerCamelCase)
attn_entropy[layer] += masked_entropy.sum(-1).sum(0).sum(0).detach()
if compute_importance:
head_importance += head_mask.grad.abs().detach()
tot_tokens += torch.ones_like(_lowerCamelCase).float().detach().sum().data
# Normalize
attn_entropy /= tot_tokens
head_importance /= tot_tokens
# Layerwise importance normalization
if not args.dont_normalize_importance_by_layer:
lowerCamelCase_ : Optional[int] = 2
lowerCamelCase_ : Dict = torch.pow(torch.pow(_lowerCamelCase , _lowerCamelCase).sum(-1) , 1 / exponent)
head_importance /= norm_by_layer.unsqueeze(-1) + 1E-20
if not args.dont_normalize_global_importance:
lowerCamelCase_ : Optional[Any] = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())
# Print matrices
if compute_entropy:
logger.info("Attention entropies")
print_ad_tensor(_lowerCamelCase)
if compute_importance:
logger.info("Head importance scores")
print_ad_tensor(_lowerCamelCase)
logger.info("Head ranked by importance scores")
lowerCamelCase_ : Any = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device)
lowerCamelCase_ : int = torch.arange(
head_importance.numel() , device=args.device)
lowerCamelCase_ : int = head_ranks.view_as(_lowerCamelCase)
print_ad_tensor(_lowerCamelCase)
return attn_entropy, head_importance, total_loss
def _A ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_):
'''simple docstring'''
lowerCamelCase_ : Tuple = compute_heads_importance(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , compute_entropy=_lowerCamelCase)
lowerCamelCase_ : int = 1 / loss # instead of downsteam score use the LM loss
logger.info("Pruning: original score: %f, threshold: %f" , _lowerCamelCase , original_score * args.masking_threshold)
lowerCamelCase_ : int = torch.ones_like(_lowerCamelCase)
lowerCamelCase_ : List[str] = max(1 , int(new_head_mask.numel() * args.masking_amount))
lowerCamelCase_ : Dict = original_score
while current_score >= original_score * args.masking_threshold:
lowerCamelCase_ : List[str] = new_head_mask.clone().detach() # save current head mask
# heads from least important to most - keep only not-masked heads
lowerCamelCase_ : Optional[int] = float("Inf")
lowerCamelCase_ : Optional[Any] = head_importance.view(-1).sort()[1]
if len(_lowerCamelCase) <= num_to_mask:
print("BREAK BY num_to_mask")
break
# mask heads
lowerCamelCase_ : Tuple = current_heads_to_mask[:num_to_mask]
logger.info("Heads to mask: %s" , str(current_heads_to_mask.tolist()))
lowerCamelCase_ : int = new_head_mask.view(-1)
lowerCamelCase_ : Optional[Any] = 0.0
lowerCamelCase_ : Optional[Any] = new_head_mask.view_as(_lowerCamelCase)
lowerCamelCase_ : Any = new_head_mask.clone().detach()
print_ad_tensor(_lowerCamelCase)
# Compute metric and head importance again
lowerCamelCase_ : Union[str, Any] = compute_heads_importance(
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , compute_entropy=_lowerCamelCase , head_mask=_lowerCamelCase)
lowerCamelCase_ : Optional[Any] = 1 / loss
logger.info(
"Masking: current score: %f, remaining heads %d (%.1f percents)" , _lowerCamelCase , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , )
logger.info("Final head mask")
print_ad_tensor(_lowerCamelCase)
np.save(os.path.join(args.output_dir , "head_mask.npy") , head_mask.detach().cpu().numpy())
return head_mask
def _A ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_):
'''simple docstring'''
lowerCamelCase_ : int = datetime.now()
lowerCamelCase_ : List[str] = compute_heads_importance(
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , compute_entropy=_lowerCamelCase , compute_importance=_lowerCamelCase , head_mask=_lowerCamelCase)
lowerCamelCase_ : int = 1 / loss
lowerCamelCase_ : Optional[Any] = datetime.now() - before_time
lowerCamelCase_ : Tuple = sum(p.numel() for p in model.parameters())
lowerCamelCase_ : Any = {
layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_lowerCamelCase))
}
for k, v in heads_to_prune.items():
if isinstance(_lowerCamelCase , _lowerCamelCase):
lowerCamelCase_ : Optional[Any] = [
v,
]
assert sum(len(_lowerCamelCase) for h in heads_to_prune.values()) == (1 - head_mask.long()).sum().item()
model.prune_heads(_lowerCamelCase)
lowerCamelCase_ : Union[str, Any] = sum(p.numel() for p in model.parameters())
lowerCamelCase_ : Dict = datetime.now()
lowerCamelCase_ : List[Any] = compute_heads_importance(
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , compute_entropy=_lowerCamelCase , compute_importance=_lowerCamelCase , head_mask=_lowerCamelCase , actually_pruned=_lowerCamelCase , )
lowerCamelCase_ : Optional[int] = 1 / loss
lowerCamelCase_ : Optional[int] = datetime.now() - before_time
logger.info(
"Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)" , _lowerCamelCase , _lowerCamelCase , pruned_num_params / original_num_params * 100 , )
logger.info("Pruning: score with masking: %f score with pruning: %f" , _lowerCamelCase , _lowerCamelCase)
logger.info("Pruning: speed ratio (original timing / new timing): %f percents" , original_time / new_time * 100)
save_model(_lowerCamelCase , args.output_dir)
def _A ( ):
'''simple docstring'''
lowerCamelCase_ : Optional[int] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--data_dir" , default=_lowerCamelCase , type=_lowerCamelCase , required=_lowerCamelCase , help="The input data dir. Should contain the .tsv files (or other data files) for the task." , )
parser.add_argument(
"--model_name_or_path" , default=_lowerCamelCase , type=_lowerCamelCase , required=_lowerCamelCase , help="Path to pretrained model or model identifier from huggingface.co/models" , )
parser.add_argument(
"--output_dir" , default=_lowerCamelCase , type=_lowerCamelCase , required=_lowerCamelCase , help="The output directory where the model predictions and checkpoints will be written." , )
# Other parameters
parser.add_argument(
"--config_name" , default="" , type=_lowerCamelCase , help="Pretrained config name or path if not the same as model_name_or_path" , )
parser.add_argument(
"--tokenizer_name" , default="" , type=_lowerCamelCase , help="Pretrained tokenizer name or path if not the same as model_name_or_path" , )
parser.add_argument(
"--cache_dir" , default=_lowerCamelCase , type=_lowerCamelCase , help="Where do you want to store the pre-trained models downloaded from s3" , )
parser.add_argument(
"--data_subset" , type=_lowerCamelCase , default=-1 , help="If > 0: limit the data to a subset of data_subset instances.")
parser.add_argument(
"--overwrite_output_dir" , action="store_true" , help="Whether to overwrite data in output directory")
parser.add_argument(
"--overwrite_cache" , action="store_true" , help="Overwrite the cached training and evaluation sets")
parser.add_argument(
"--dont_normalize_importance_by_layer" , action="store_true" , help="Don't normalize importance score by layers")
parser.add_argument(
"--dont_normalize_global_importance" , action="store_true" , help="Don't normalize all importance scores between 0 and 1" , )
parser.add_argument(
"--try_masking" , action="store_true" , help="Whether to try to mask head until a threshold of accuracy.")
parser.add_argument(
"--masking_threshold" , default=0.9 , type=_lowerCamelCase , help="masking threshold in term of metrics (stop masking when metric < threshold * original metric value)." , )
parser.add_argument(
"--masking_amount" , default=0.1 , type=_lowerCamelCase , help="Amount to heads to masking at each masking step.")
parser.add_argument("--metric_name" , default="acc" , type=_lowerCamelCase , help="Metric to use for head masking.")
parser.add_argument(
"--max_seq_length" , default=128 , type=_lowerCamelCase , help=(
"The maximum total input sequence length after WordPiece tokenization. \n"
"Sequences longer than this will be truncated, sequences shorter padded."
) , )
parser.add_argument("--batch_size" , default=1 , type=_lowerCamelCase , help="Batch size.")
parser.add_argument("--seed" , type=_lowerCamelCase , default=42)
parser.add_argument("--local_rank" , type=_lowerCamelCase , default=-1 , help="local_rank for distributed training on gpus")
parser.add_argument("--no_cuda" , action="store_true" , help="Whether not to use CUDA when available")
parser.add_argument("--server_ip" , type=_lowerCamelCase , default="" , help="Can be used for distant debugging.")
parser.add_argument("--server_port" , type=_lowerCamelCase , default="" , help="Can be used for distant debugging.")
lowerCamelCase_ : Dict = parser.parse_args()
if args.server_ip and args.server_port:
# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
import ptvsd
print("Waiting for debugger attach")
ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_lowerCamelCase)
ptvsd.wait_for_attach()
# Setup devices and distributed training
if args.local_rank == -1 or args.no_cuda:
lowerCamelCase_ : List[str] = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
lowerCamelCase_ : List[Any] = 0 if args.no_cuda else torch.cuda.device_count()
else:
torch.cuda.set_device(args.local_rank)
lowerCamelCase_ : Optional[Any] = torch.device("cuda" , args.local_rank)
lowerCamelCase_ : Optional[int] = 1
torch.distributed.init_process_group(backend="nccl") # Initializes the distributed backend
# Setup logging
logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN)
logger.info("device: {} n_gpu: {}, distributed: {}".format(args.device , args.n_gpu , bool(args.local_rank != -1)))
lowerCamelCase_ : List[str] = GPTaLMHeadModel.from_pretrained(args.model_name_or_path)
# Distributed and parallel training
model.to(args.device)
if args.local_rank != -1:
lowerCamelCase_ : List[Any] = nn.parallel.DistributedDataParallel(
_lowerCamelCase , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_lowerCamelCase)
elif args.n_gpu > 1:
lowerCamelCase_ : Union[str, Any] = nn.DataParallel(_lowerCamelCase)
# Print/save training arguments
os.makedirs(args.output_dir , exist_ok=_lowerCamelCase)
torch.save(_lowerCamelCase , os.path.join(args.output_dir , "run_args.bin"))
logger.info("Training/evaluation parameters %s" , _lowerCamelCase)
# Prepare dataset
lowerCamelCase_ : Union[str, Any] = np.concatenate(
[
np.loadtxt(args.data_dir , dtype=np.intaa),
])
lowerCamelCase_ : str = (torch.from_numpy(_lowerCamelCase),)
lowerCamelCase_ : int = TensorDataset(*_lowerCamelCase)
lowerCamelCase_ : Union[str, Any] = RandomSampler(_lowerCamelCase)
lowerCamelCase_ : List[str] = DataLoader(_lowerCamelCase , sampler=_lowerCamelCase , batch_size=args.batch_size)
# Compute head entropy and importance score
compute_heads_importance(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase)
# Try head masking (set heads to zero until the score goes under a threshole)
# and head pruning (remove masked heads and see the effect on the network)
if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
lowerCamelCase_ : int = mask_heads(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase)
prune_heads(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase)
if __name__ == "__main__":
main()
| 705 |
from __future__ import annotations
from numpy import array, cos, cross, floataa, radians, sin
from numpy.typing import NDArray
def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = False):
'''simple docstring'''
if radian_mode:
return [magnitude * cos(lowerCAmelCase_), magnitude * sin(lowerCAmelCase_)]
return [magnitude * cos(radians(lowerCAmelCase_)), magnitude * sin(radians(lowerCAmelCase_))]
def __magic_name__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 10**-1):
'''simple docstring'''
lowerCamelCase_ : NDArray[floataa] = cross(lowerCAmelCase_ , lowerCAmelCase_)
lowerCamelCase_ : float = sum(lowerCAmelCase_)
return abs(lowerCAmelCase_) < eps
if __name__ == "__main__":
# Test to check if it works
__magic_name__ = array(
[
polar_force(7_18.4, 1_8_0 - 3_0),
polar_force(8_79.54, 4_5),
polar_force(1_0_0, -9_0),
]
)
__magic_name__ = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem 1 in image_data/2D_problems.jpg
__magic_name__ = array(
[
polar_force(3_0 * 9.81, 1_5),
polar_force(2_1_5, 1_8_0 - 4_5),
polar_force(2_6_4, 9_0 - 3_0),
]
)
__magic_name__ = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem in image_data/2D_problems_1.jpg
__magic_name__ = array([[0, -2_0_0_0], [0, -1_2_0_0], [0, 1_5_6_0_0], [0, -1_2_4_0_0]])
__magic_name__ = array([[0, 0], [6, 0], [1_0, 0], [1_2, 0]])
assert in_static_equilibrium(forces, location)
import doctest
doctest.testmod()
| 73 | 0 |
'''simple docstring'''
import math
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> list:
__snake_case = [True] * n
__snake_case = False
__snake_case = False
__snake_case = True
for i in range(3 , int(n**0.5 + 1 ) , 2 ):
__snake_case = i * 2
while index < n:
__snake_case = False
__snake_case = index + i
__snake_case = [2]
for i in range(3 , _UpperCAmelCase , 2 ):
if is_prime[i]:
primes.append(_UpperCAmelCase )
return primes
def __UpperCAmelCase ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int:
__snake_case = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00
__snake_case = prime_sieve(_UpperCAmelCase )
__snake_case = 0
__snake_case = 0
__snake_case = primes[prime_index]
while (last_prime**2) <= limit:
__snake_case = primes[prime_index + 1]
__snake_case = last_prime**2
__snake_case = next_prime**2
# Get numbers divisible by lps(current)
__snake_case = lower_bound + last_prime
while upper_bound > current <= limit:
matches_sum += current
current += last_prime
# Reset the upper_bound
while (upper_bound - next_prime) > limit:
upper_bound -= next_prime
# Add the numbers divisible by ups(current)
__snake_case = upper_bound - next_prime
while current > lower_bound:
matches_sum += current
current -= next_prime
# Remove the numbers divisible by both ups and lps
__snake_case = 0
while upper_bound > current <= limit:
if current <= lower_bound:
# Increment the current number
current += last_prime * next_prime
continue
if current > limit:
break
# Remove twice since it was added by both ups and lps
matches_sum -= current * 2
# Increment the current number
current += last_prime * next_prime
# Setup for next pair
__snake_case = next_prime
prime_index += 1
return matches_sum
if __name__ == "__main__":
print(solution())
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> int:
assert (
isinstance(_UpperCAmelCase , _UpperCAmelCase ) 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
__snake_case , __snake_case = 1, 1
for _ in range(number_of_steps - 1 ):
__snake_case , __snake_case = current + previous, current
return current
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline
else:
from .pipeline_kandinsky import KandinskyPipeline
from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline
from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline
from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput
from .text_encoder import MultilingualCLIP
| 627 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__a = logging.get_logger(__name__)
__a = {"""ctrl""": """https://huggingface.co/ctrl/resolve/main/config.json"""}
class __lowercase ( __snake_case ):
UpperCamelCase = '''ctrl'''
UpperCamelCase = ['''past_key_values''']
UpperCamelCase = {
'''max_position_embeddings''': '''n_positions''',
'''hidden_size''': '''n_embd''',
'''num_attention_heads''': '''n_head''',
'''num_hidden_layers''': '''n_layer''',
}
def __init__( self : str , __lowerCamelCase : Optional[int]=2_4_6_5_3_4 , __lowerCamelCase : Union[str, Any]=2_5_6 , __lowerCamelCase : int=1_2_8_0 , __lowerCamelCase : Optional[Any]=8_1_9_2 , __lowerCamelCase : List[str]=4_8 , __lowerCamelCase : Dict=1_6 , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : Union[str, Any]=0.1 , __lowerCamelCase : Union[str, Any]=1e-6 , __lowerCamelCase : str=0.02 , __lowerCamelCase : Union[str, Any]=True , **__lowerCamelCase : List[str] , ) -> Optional[Any]:
"""simple docstring"""
UpperCAmelCase = vocab_size
UpperCAmelCase = n_positions
UpperCAmelCase = n_embd
UpperCAmelCase = n_layer
UpperCAmelCase = n_head
UpperCAmelCase = dff
UpperCAmelCase = resid_pdrop
UpperCAmelCase = embd_pdrop
UpperCAmelCase = layer_norm_epsilon
UpperCAmelCase = initializer_range
UpperCAmelCase = use_cache
super().__init__(**__lowerCamelCase )
| 627 | 1 |
from __future__ import annotations
import unittest
from transformers import AutoTokenizer, PegasusConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel
@require_tf
class _lowerCAmelCase:
"""simple docstring"""
a : int =PegasusConfig
a : List[str] ={}
a : Optional[int] ='''gelu'''
def __init__( self , _lowerCamelCase , _lowerCamelCase=1_3 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase=9_9 , _lowerCamelCase=3_2 , _lowerCamelCase=2 , _lowerCamelCase=4 , _lowerCamelCase=3_7 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=4_0 , _lowerCamelCase=2 , _lowerCamelCase=1 , _lowerCamelCase=0 , ):
UpperCamelCase_: List[Any] = parent
UpperCamelCase_: Dict = batch_size
UpperCamelCase_: List[str] = seq_length
UpperCamelCase_: List[str] = is_training
UpperCamelCase_: Any = use_labels
UpperCamelCase_: Optional[Any] = vocab_size
UpperCamelCase_: Tuple = hidden_size
UpperCamelCase_: List[Any] = num_hidden_layers
UpperCamelCase_: Any = num_attention_heads
UpperCamelCase_: Optional[Any] = intermediate_size
UpperCamelCase_: Optional[int] = hidden_dropout_prob
UpperCamelCase_: int = attention_probs_dropout_prob
UpperCamelCase_: Union[str, Any] = max_position_embeddings
UpperCamelCase_: Dict = eos_token_id
UpperCamelCase_: Union[str, Any] = pad_token_id
UpperCamelCase_: List[Any] = bos_token_id
def _a ( self ):
UpperCamelCase_: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size )
UpperCamelCase_: int = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 )
UpperCamelCase_: List[str] = tf.concat([input_ids, eos_tensor] , axis=1 )
UpperCamelCase_: Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
UpperCamelCase_: Tuple = self.config_cls(
vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , )
UpperCamelCase_: Optional[Any] = prepare_pegasus_inputs_dict(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
return config, inputs_dict
def _a ( self , _lowerCamelCase , _lowerCamelCase ):
UpperCamelCase_: Optional[Any] = TFPegasusModel(config=_lowerCamelCase ).get_decoder()
UpperCamelCase_: Optional[int] = inputs_dict['input_ids']
UpperCamelCase_: Optional[int] = input_ids[:1, :]
UpperCamelCase_: int = inputs_dict['attention_mask'][:1, :]
UpperCamelCase_: Optional[int] = inputs_dict['head_mask']
UpperCamelCase_: Optional[int] = 1
# first forward pass
UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , head_mask=_lowerCamelCase , use_cache=_lowerCamelCase )
UpperCamelCase_ ,UpperCamelCase_: int = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
UpperCamelCase_: int = ids_tensor((self.batch_size, 3) , config.vocab_size )
UpperCamelCase_: List[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta )
# append to next input_ids and
UpperCamelCase_: Union[str, Any] = tf.concat([input_ids, next_tokens] , axis=-1 )
UpperCamelCase_: int = tf.concat([attention_mask, next_attn_mask] , axis=-1 )
UpperCamelCase_: Any = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0]
UpperCamelCase_: int = model(_lowerCamelCase , attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase )[0]
self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] )
# select random slice
UpperCamelCase_: Optional[int] = int(ids_tensor((1,) , output_from_past.shape[-1] ) )
UpperCamelCase_: Any = output_from_no_past[:, -3:, random_slice_idx]
UpperCamelCase_: Union[str, Any] = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(_lowerCamelCase , _lowerCamelCase , rtol=1e-3 )
def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , ) -> str:
if attention_mask is None:
UpperCamelCase_: Optional[Any] = tf.cast(tf.math.not_equal(UpperCAmelCase__ , config.pad_token_id ) , tf.inta )
if decoder_attention_mask is None:
UpperCamelCase_: int = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ),
] , axis=-1 , )
if head_mask is None:
UpperCamelCase_: str = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
UpperCamelCase_: Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
UpperCamelCase_: int = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
@require_tf
class _lowerCAmelCase( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ):
"""simple docstring"""
a : Tuple =(TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
a : int =(TFPegasusForConditionalGeneration,) if is_tf_available() else ()
a : Tuple =(
{
'''conversational''': TFPegasusForConditionalGeneration,
'''feature-extraction''': TFPegasusModel,
'''summarization''': TFPegasusForConditionalGeneration,
'''text2text-generation''': TFPegasusForConditionalGeneration,
'''translation''': TFPegasusForConditionalGeneration,
}
if is_tf_available()
else {}
)
a : List[str] =True
a : List[str] =False
a : Tuple =False
def _a ( self ):
UpperCamelCase_: Dict = TFPegasusModelTester(self )
UpperCamelCase_: Any = ConfigTester(self , config_class=_lowerCamelCase )
def _a ( self ):
self.config_tester.run_common_tests()
def _a ( self ):
UpperCamelCase_: Any = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*_lowerCamelCase )
@require_sentencepiece
@require_tokenizers
@require_tf
class _lowerCAmelCase( unittest.TestCase ):
"""simple docstring"""
a : Dict =[
''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''',
''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''',
]
a : int =[
'''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to'''
''' reduce the risk of wildfires.''',
'''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''',
] # differs slightly from pytorch, likely due to numerical differences in linear layers
a : Union[str, Any] ='''google/pegasus-xsum'''
@cached_property
def _a ( self ):
return AutoTokenizer.from_pretrained(self.model_name )
@cached_property
def _a ( self ):
UpperCamelCase_: Optional[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name )
return model
def _a ( self , **_lowerCamelCase ):
UpperCamelCase_: Dict = self.translate_src_text(**_lowerCamelCase )
assert self.expected_text == generated_words
def _a ( self , **_lowerCamelCase ):
UpperCamelCase_: Union[str, Any] = self.tokenizer(self.src_text , **_lowerCamelCase , padding=_lowerCamelCase , return_tensors='tf' )
UpperCamelCase_: Any = self.model.generate(
model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=_lowerCamelCase , )
UpperCamelCase_: str = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=_lowerCamelCase )
return generated_words
@slow
def _a ( self ):
self._assert_generated_batch_equal_expected()
| 57 |
import unittest
from pathlib import Path
from shutil import copyfile
from transformers import SPIECE_UNDERLINE, is_sentencepiece_available
from transformers.models.speech_to_text import SpeechaTextTokenizer
from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
A : Optional[int] = get_tests_dir("fixtures/test_sentencepiece.model")
if is_sentencepiece_available():
import sentencepiece as sp
A : Dict = 5
A : Optional[int] = 10
@require_sentencepiece
@require_tokenizers
class lowerCamelCase (SCREAMING_SNAKE_CASE__ , unittest.TestCase ):
"""simple docstring"""
lowerCamelCase__ = SpeechaTextTokenizer
lowerCamelCase__ = False
lowerCamelCase__ = True
def __A ( self : Optional[Any] ) -> str:
super().setUp()
SCREAMING_SNAKE_CASE_ = sp.SentencePieceProcessor()
spm_model.Load(__magic_name__ )
SCREAMING_SNAKE_CASE_ = ["<s>", "<pad>", "</s>", "<unk>"]
vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(__magic_name__ ) )]
SCREAMING_SNAKE_CASE_ = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) )
SCREAMING_SNAKE_CASE_ = Path(self.tmpdirname )
save_json(__magic_name__ , save_dir / VOCAB_FILES_NAMES["vocab_file"] )
if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
copyfile(__magic_name__ , save_dir / VOCAB_FILES_NAMES["spm_file"] )
SCREAMING_SNAKE_CASE_ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname )
tokenizer.save_pretrained(self.tmpdirname )
def __A ( self : Any ) -> Tuple:
SCREAMING_SNAKE_CASE_ = "<pad>"
SCREAMING_SNAKE_CASE_ = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ )
def __A ( self : Any ) -> List[Any]:
SCREAMING_SNAKE_CASE_ = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<s>" )
self.assertEqual(vocab_keys[1] , "<pad>" )
self.assertEqual(vocab_keys[-1] , "j" )
self.assertEqual(len(__magic_name__ ) , 1_001 )
def __A ( self : List[Any] ) -> Dict:
self.assertEqual(self.get_tokenizer().vocab_size , 1_001 )
def __A ( self : Union[str, Any] ) -> Optional[int]:
SCREAMING_SNAKE_CASE_ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname )
SCREAMING_SNAKE_CASE_ = tokenizer.tokenize("This is a test" )
self.assertListEqual(__magic_name__ , ["▁This", "▁is", "▁a", "▁t", "est"] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(__magic_name__ ) , [289, 50, 14, 174, 386] , )
SCREAMING_SNAKE_CASE_ = tokenizer.tokenize("I was born in 92000, and this is falsé." )
self.assertListEqual(
__magic_name__ , [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", "é", "."] , )
SCREAMING_SNAKE_CASE_ = tokenizer.convert_tokens_to_ids(__magic_name__ )
self.assertListEqual(__magic_name__ , [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8] )
SCREAMING_SNAKE_CASE_ = tokenizer.convert_ids_to_tokens(__magic_name__ )
self.assertListEqual(
__magic_name__ , [SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", "."] , )
@slow
def __A ( self : List[str] ) -> List[Any]:
# fmt: off
SCREAMING_SNAKE_CASE_ = {"input_ids": [[3_791, 797, 31, 11, 64, 797, 31, 2_429, 433, 12, 1_176, 12, 20, 786, 915, 142, 2_413, 240, 37, 3_238, 797, 31, 11, 35, 93, 915, 142, 2_413, 240, 37, 5_540, 567, 1_276, 93, 37, 610, 40, 62, 455, 657, 1_042, 123, 780, 177, 37, 309, 241, 1_298, 514, 20, 292, 2_737, 114, 2_469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3_388, 511, 459, 4, 3_555, 40, 321, 302, 705, 4, 3_388, 511, 583, 326, 5, 5, 5, 62, 3_310, 560, 177, 2_680, 217, 1_508, 32, 31, 853, 418, 64, 583, 511, 1_605, 62, 35, 93, 560, 177, 2_680, 217, 1_508, 1_521, 64, 583, 511, 519, 62, 20, 1_515, 764, 20, 149, 261, 5_625, 7_972, 20, 5_540, 567, 1_276, 93, 3_925, 1_675, 11, 15, 802, 7_972, 576, 217, 1_508, 11, 35, 93, 1_253, 2_441, 15, 289, 652, 31, 416, 321, 3_842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2_681, 1_153, 3_434, 20, 5_540, 37, 567, 126, 1_253, 2_441, 3_376, 449, 210, 431, 1_563, 177, 767, 5_540, 11, 1_203, 472, 11, 2_953, 685, 285, 364, 706, 1_153, 20, 6_799, 20, 2_869, 20, 4_464, 126, 40, 2_429, 20, 1_040, 866, 2_664, 418, 20, 318, 20, 1_726, 186, 20, 265, 522, 35, 93, 2_191, 4_634, 20, 1_040, 12, 6_799, 15, 228, 2_356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2_575, 2_666, 684, 1_582, 1_176, 12, 627, 149, 619, 20, 4_902, 563, 11, 20, 149, 261, 3_420, 2_356, 174, 142, 4_714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=__magic_name__ , model_name="facebook/s2t-small-mustc-en-de-st" , revision="a14f04cf0776c02f62a8cb800cf7909e15ea23ad" , )
@require_sentencepiece
class lowerCamelCase (unittest.TestCase ):
"""simple docstring"""
lowerCamelCase__ = '''valhalla/s2t_mustc_multilinguial_medium'''
lowerCamelCase__ = '''C\'est trop cool'''
lowerCamelCase__ = '''Esto es genial'''
@classmethod
def __A ( cls : List[Any] ) -> List[str]:
SCREAMING_SNAKE_CASE_ = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name )
return cls
def __A ( self : str ) -> int:
self.assertEqual(self.tokenizer.lang_code_to_id["pt"] , 4 )
self.assertEqual(self.tokenizer.lang_code_to_id["ru"] , 6 )
self.assertEqual(self.tokenizer.lang_code_to_id["it"] , 9 )
self.assertEqual(self.tokenizer.lang_code_to_id["de"] , 11 )
def __A ( self : List[Any] ) -> Union[str, Any]:
self.assertEqual(self.tokenizer.vocab_size , 10_000 )
def __A ( self : Any ) -> int:
self.assertIn(__magic_name__ , self.tokenizer.all_special_ids )
SCREAMING_SNAKE_CASE_ = [ES_CODE, 4, 1_601, 47, 7_647, 2]
SCREAMING_SNAKE_CASE_ = self.tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ )
SCREAMING_SNAKE_CASE_ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__magic_name__ )
self.assertEqual(__magic_name__ , __magic_name__ )
self.assertNotIn(self.tokenizer.eos_token , __magic_name__ )
def __A ( self : Dict ) -> Tuple:
SCREAMING_SNAKE_CASE_ = "fr"
SCREAMING_SNAKE_CASE_ = self.tokenizer(self.french_text ).input_ids
self.assertEqual(encoded[0] , __magic_name__ )
self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id )
def __A ( self : Any ) -> List[Any]:
SCREAMING_SNAKE_CASE_ = "fr"
self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE] )
SCREAMING_SNAKE_CASE_ = "es"
self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE] )
| 140 | 0 |
def lowerCamelCase_ ( UpperCamelCase__ : list ):
'''simple docstring'''
for i in range(len(UpperCamelCase__ ) - 1, 0, -1 ):
UpperCamelCase__ = False
for j in range(UpperCamelCase__, 0, -1 ):
if unsorted[j] < unsorted[j - 1]:
UpperCamelCase__ , UpperCamelCase__ = unsorted[j - 1], unsorted[j]
UpperCamelCase__ = True
for j in range(UpperCamelCase__ ):
if unsorted[j] > unsorted[j + 1]:
UpperCamelCase__ , UpperCamelCase__ = unsorted[j + 1], unsorted[j]
UpperCamelCase__ = True
if not swapped:
break
return unsorted
if __name__ == "__main__":
import doctest
doctest.testmod()
lowercase = input("""Enter numbers separated by a comma:\n""").strip()
lowercase = [int(item) for item in user_input.split(""",""")]
print(f'{cocktail_shaker_sort(unsorted) = }')
| 705 |
def lowerCamelCase_ ( ):
'''simple docstring'''
UpperCamelCase__ = []
UpperCamelCase__ = 1
while len(UpperCamelCase__ ) < 1e6:
constant.append(str(UpperCamelCase__ ) )
i += 1
UpperCamelCase__ = ''''''.join(UpperCamelCase__ )
return (
int(constant[0] )
* int(constant[9] )
* int(constant[99] )
* int(constant[999] )
* int(constant[9999] )
* int(constant[9_9999] )
* int(constant[99_9999] )
)
if __name__ == "__main__":
print(solution())
| 591 | 0 |
'''simple docstring'''
from ....configuration_utils import PretrainedConfig
from ....utils import logging
a_ : Optional[int] = logging.get_logger(__name__)
a_ : Tuple = {
"""Visual-Attention-Network/van-base""": (
"""https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json"""
),
}
class __UpperCamelCase ( lowerCamelCase__ ):
lowercase : int ='van'
def __init__( self, lowerCAmelCase=224, lowerCAmelCase=3, lowerCAmelCase=[7, 3, 3, 3], lowerCAmelCase=[4, 2, 2, 2], lowerCAmelCase=[64, 128, 320, 512], lowerCAmelCase=[3, 3, 12, 3], lowerCAmelCase=[8, 8, 4, 4], lowerCAmelCase="gelu", lowerCAmelCase=0.0_2, lowerCAmelCase=1e-6, lowerCAmelCase=1e-2, lowerCAmelCase=0.0, lowerCAmelCase=0.0, **lowerCAmelCase, ):
"""simple docstring"""
super().__init__(**lowerCAmelCase )
lowerCamelCase_ =image_size
lowerCamelCase_ =num_channels
lowerCamelCase_ =patch_sizes
lowerCamelCase_ =strides
lowerCamelCase_ =hidden_sizes
lowerCamelCase_ =depths
lowerCamelCase_ =mlp_ratios
lowerCamelCase_ =hidden_act
lowerCamelCase_ =initializer_range
lowerCamelCase_ =layer_norm_eps
lowerCamelCase_ =layer_scale_init_value
lowerCamelCase_ =drop_path_rate
lowerCamelCase_ =dropout_rate
| 676 |
'''simple docstring'''
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class __UpperCamelCase ( lowerCamelCase__ ):
lowercase : Optional[int] =['image_processor', 'tokenizer']
lowercase : str ='CLIPImageProcessor'
lowercase : Optional[Any] =('XLMRobertaTokenizer', 'XLMRobertaTokenizerFast')
def __init__( self, lowerCAmelCase=None, lowerCAmelCase=None, **lowerCAmelCase ):
"""simple docstring"""
lowerCamelCase_ =None
if "feature_extractor" in kwargs:
warnings.warn(
'''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
''' instead.''', lowerCAmelCase, )
lowerCamelCase_ =kwargs.pop('''feature_extractor''' )
lowerCamelCase_ =image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('''You need to specify an `image_processor`.''' )
if tokenizer is None:
raise ValueError('''You need to specify a `tokenizer`.''' )
super().__init__(lowerCAmelCase, lowerCAmelCase )
def __call__( self, lowerCAmelCase=None, lowerCAmelCase=None, lowerCAmelCase=None, **lowerCAmelCase ):
"""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_ =self.tokenizer(lowerCAmelCase, return_tensors=lowerCAmelCase, **lowerCAmelCase )
if images is not None:
lowerCamelCase_ =self.image_processor(lowerCAmelCase, return_tensors=lowerCAmelCase, **lowerCAmelCase )
if text is not None and images is not None:
lowerCamelCase_ =image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**lowerCAmelCase ), tensor_type=lowerCAmelCase )
def lowercase__ ( self, *lowerCAmelCase, **lowerCAmelCase ):
"""simple docstring"""
return self.tokenizer.batch_decode(*lowerCAmelCase, **lowerCAmelCase )
def lowercase__ ( self, *lowerCAmelCase, **lowerCAmelCase ):
"""simple docstring"""
return self.tokenizer.decode(*lowerCAmelCase, **lowerCAmelCase )
@property
def lowercase__ ( self ):
"""simple docstring"""
lowerCamelCase_ =self.tokenizer.model_input_names
lowerCamelCase_ =self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
| 676 | 1 |
import inspect
import unittest
from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
from transformers.models.mobilevitva.modeling_mobilevitva import (
MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
make_divisible,
)
if is_vision_available():
from PIL import Image
from transformers import MobileViTImageProcessor
class lowercase ( _SCREAMING_SNAKE_CASE ):
def __UpperCamelCase ( self ) -> List[str]:
"""simple docstring"""
UpperCamelCase = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(A_ , 'width_multiplier' ) )
class lowercase :
def __init__( self , A_ , A_=13 , A_=64 , A_=2 , A_=3 , A_="swish" , A_=3 , A_=32 , A_=0.1 , A_=0.02 , A_=True , A_=True , A_=10 , A_=None , A_=0.25 , A_=0.0 , A_=0.0 , ) -> Dict:
"""simple docstring"""
UpperCamelCase = parent
UpperCamelCase = batch_size
UpperCamelCase = image_size
UpperCamelCase = patch_size
UpperCamelCase = num_channels
UpperCamelCase = make_divisible(512 * width_multiplier , divisor=8 )
UpperCamelCase = hidden_act
UpperCamelCase = conv_kernel_size
UpperCamelCase = output_stride
UpperCamelCase = classifier_dropout_prob
UpperCamelCase = use_labels
UpperCamelCase = is_training
UpperCamelCase = num_labels
UpperCamelCase = initializer_range
UpperCamelCase = scope
UpperCamelCase = width_multiplier
UpperCamelCase = ffn_dropout
UpperCamelCase = attn_dropout
def __UpperCamelCase ( self ) -> int:
"""simple docstring"""
UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCamelCase = None
UpperCamelCase = None
if self.use_labels:
UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels )
UpperCamelCase = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
UpperCamelCase = self.get_config()
return config, pixel_values, labels, pixel_labels
def __UpperCamelCase ( self ) -> Optional[int]:
"""simple docstring"""
return MobileViTVaConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , )
def __UpperCamelCase ( self , A_ , A_ , A_ , A_ ) -> List[Any]:
"""simple docstring"""
UpperCamelCase = MobileViTVaModel(config=A_ )
model.to(A_ )
model.eval()
UpperCamelCase = model(A_ )
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 __UpperCamelCase ( self , A_ , A_ , A_ , A_ ) -> str:
"""simple docstring"""
UpperCamelCase = self.num_labels
UpperCamelCase = MobileViTVaForImageClassification(A_ )
model.to(A_ )
model.eval()
UpperCamelCase = model(A_ , labels=A_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __UpperCamelCase ( self , A_ , A_ , A_ , A_ ) -> Tuple:
"""simple docstring"""
UpperCamelCase = self.num_labels
UpperCamelCase = MobileViTVaForSemanticSegmentation(A_ )
model.to(A_ )
model.eval()
UpperCamelCase = model(A_ )
self.parent.assertEqual(
result.logits.shape , (
self.batch_size,
self.num_labels,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
UpperCamelCase = model(A_ , labels=A_ )
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 __UpperCamelCase ( self ) -> int:
"""simple docstring"""
UpperCamelCase = self.prepare_config_and_inputs()
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs
UpperCamelCase = {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
class lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ):
__lowercase : int = (
(MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
if is_torch_available()
else ()
)
__lowercase : Dict = (
{
"feature-extraction": MobileViTVaModel,
"image-classification": MobileViTVaForImageClassification,
"image-segmentation": MobileViTVaForSemanticSegmentation,
}
if is_torch_available()
else {}
)
__lowercase : str = False
__lowercase : int = False
__lowercase : Optional[int] = False
__lowercase : Optional[Any] = False
def __UpperCamelCase ( self ) -> Dict:
"""simple docstring"""
UpperCamelCase = MobileViTVaModelTester(self )
UpperCamelCase = MobileViTVaConfigTester(self , config_class=A_ , has_text_modality=A_ )
def __UpperCamelCase ( self ) -> List[str]:
"""simple docstring"""
self.config_tester.run_common_tests()
@unittest.skip(reason='MobileViTV2 does not use inputs_embeds' )
def __UpperCamelCase ( self ) -> Dict:
"""simple docstring"""
pass
@unittest.skip(reason='MobileViTV2 does not support input and output embeddings' )
def __UpperCamelCase ( self ) -> Optional[Any]:
"""simple docstring"""
pass
@unittest.skip(reason='MobileViTV2 does not output attentions' )
def __UpperCamelCase ( self ) -> Optional[Any]:
"""simple docstring"""
pass
@require_torch_multi_gpu
@unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.' )
def __UpperCamelCase ( self ) -> int:
"""simple docstring"""
pass
@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
def __UpperCamelCase ( self ) -> List[str]:
"""simple docstring"""
pass
def __UpperCamelCase ( self ) -> List[Any]:
"""simple docstring"""
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase = model_class(A_ )
UpperCamelCase = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCamelCase = [*signature.parameters.keys()]
UpperCamelCase = ['pixel_values']
self.assertListEqual(arg_names[:1] , A_ )
def __UpperCamelCase ( self ) -> Any:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*A_ )
def __UpperCamelCase ( self ) -> str:
"""simple docstring"""
def check_hidden_states_output(A_ , A_ , A_ ):
UpperCamelCase = model_class(A_ )
model.to(A_ )
model.eval()
with torch.no_grad():
UpperCamelCase = model(**self._prepare_for_class(A_ , A_ ) )
UpperCamelCase = outputs.hidden_states
UpperCamelCase = 5
self.assertEqual(len(A_ ) , A_ )
# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
# with the width and height being successively divided by 2.
UpperCamelCase = 2
for i in range(len(A_ ) ):
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 )
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase = True
check_hidden_states_output(A_ , A_ , A_ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
UpperCamelCase = True
check_hidden_states_output(A_ , A_ , A_ )
def __UpperCamelCase ( self ) -> Dict:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*A_ )
def __UpperCamelCase ( self ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*A_ )
@slow
def __UpperCamelCase ( self ) -> Dict:
"""simple docstring"""
for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCamelCase = MobileViTVaModel.from_pretrained(A_ )
self.assertIsNotNone(A_ )
def A ( ) -> int:
'''simple docstring'''
UpperCamelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_torch
@require_vision
class lowercase ( unittest.TestCase ):
@cached_property
def __UpperCamelCase ( self ) -> Any:
"""simple docstring"""
return (
MobileViTImageProcessor.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256' )
if is_vision_available()
else None
)
@slow
def __UpperCamelCase ( self ) -> str:
"""simple docstring"""
UpperCamelCase = MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256' ).to(
A_ )
UpperCamelCase = self.default_image_processor
UpperCamelCase = prepare_img()
UpperCamelCase = image_processor(images=A_ , return_tensors='pt' ).to(A_ )
# forward pass
with torch.no_grad():
UpperCamelCase = model(**A_ )
# verify the logits
UpperCamelCase = torch.Size((1, 1_000) )
self.assertEqual(outputs.logits.shape , A_ )
UpperCamelCase = torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01] ).to(A_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , A_ , atol=1e-4 ) )
@slow
def __UpperCamelCase ( self ) -> List[Any]:
"""simple docstring"""
UpperCamelCase = MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' )
UpperCamelCase = model.to(A_ )
UpperCamelCase = MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' )
UpperCamelCase = prepare_img()
UpperCamelCase = image_processor(images=A_ , return_tensors='pt' ).to(A_ )
# forward pass
with torch.no_grad():
UpperCamelCase = model(**A_ )
UpperCamelCase = outputs.logits
# verify the logits
UpperCamelCase = torch.Size((1, 21, 32, 32) )
self.assertEqual(logits.shape , A_ )
UpperCamelCase = torch.tensor(
[
[[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]],
[[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]],
[[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]],
] , device=A_ , )
self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , A_ , atol=1e-4 ) )
@slow
def __UpperCamelCase ( self ) -> List[Any]:
"""simple docstring"""
UpperCamelCase = MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' )
UpperCamelCase = model.to(A_ )
UpperCamelCase = MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' )
UpperCamelCase = prepare_img()
UpperCamelCase = image_processor(images=A_ , return_tensors='pt' ).to(A_ )
# forward pass
with torch.no_grad():
UpperCamelCase = model(**A_ )
UpperCamelCase = outputs.logits.detach().cpu()
UpperCamelCase = image_processor.post_process_semantic_segmentation(outputs=A_ , target_sizes=[(50, 60)] )
UpperCamelCase = torch.Size((50, 60) )
self.assertEqual(segmentation[0].shape , A_ )
UpperCamelCase = image_processor.post_process_semantic_segmentation(outputs=A_ )
UpperCamelCase = torch.Size((32, 32) )
self.assertEqual(segmentation[0].shape , A_ )
| 707 |
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
# @@protoc_insertion_point(imports)
_UpperCAmelCase : Tuple = _symbol_database.Default()
_UpperCAmelCase : List[Any] = _descriptor_pool.Default().AddSerializedFile(
b"\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03"
)
_UpperCAmelCase : int = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "sentencepiece_model_pb2", _globals)
if _descriptor._USE_C_DESCRIPTORS is False:
_UpperCAmelCase : int = None
_UpperCAmelCase : List[str] = b"H\003"
# (generated by protobuf compiler, but `_TRAINERSPEC` is not defined)
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001"
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001"
_UpperCAmelCase : Optional[Any] = 45
_UpperCAmelCase : Any = 1_581
_UpperCAmelCase : Tuple = 1_517
_UpperCAmelCase : List[str] = 1_570
_UpperCAmelCase : int = 1_584
_UpperCAmelCase : List[Any] = 1_793
_UpperCAmelCase : Optional[int] = 1_795
_UpperCAmelCase : Any = 1_916
_UpperCAmelCase : Tuple = 1_864
_UpperCAmelCase : List[Any] = 1_905
_UpperCAmelCase : Union[str, Any] = 1_919
_UpperCAmelCase : str = 2_429
_UpperCAmelCase : Any = 2_208
_UpperCAmelCase : Dict = 2_418
_UpperCAmelCase : Optional[Any] = 2_323
_UpperCAmelCase : Tuple = 2_407
# @@protoc_insertion_point(module_scope)
| 3 | 0 |
"""simple docstring"""
import math
import os
import unittest
from transformers import MegatronBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
MODEL_FOR_PRETRAINING_MAPPING,
MegatronBertForCausalLM,
MegatronBertForMaskedLM,
MegatronBertForMultipleChoice,
MegatronBertForNextSentencePrediction,
MegatronBertForPreTraining,
MegatronBertForQuestionAnswering,
MegatronBertForSequenceClassification,
MegatronBertForTokenClassification,
MegatronBertModel,
)
class lowerCamelCase :
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ):
UpperCamelCase : Optional[int] = parent
UpperCamelCase : int = batch_size
UpperCamelCase : List[Any] = seq_length
UpperCamelCase : Optional[int] = is_training
UpperCamelCase : List[str] = use_input_mask
UpperCamelCase : int = use_token_type_ids
UpperCamelCase : List[Any] = use_labels
UpperCamelCase : Tuple = vocab_size
UpperCamelCase : Union[str, Any] = hidden_size
UpperCamelCase : str = embedding_size
UpperCamelCase : List[Any] = num_hidden_layers
UpperCamelCase : Tuple = num_attention_heads
UpperCamelCase : List[Any] = intermediate_size
UpperCamelCase : Optional[int] = hidden_act
UpperCamelCase : Optional[int] = hidden_dropout_prob
UpperCamelCase : Dict = attention_probs_dropout_prob
UpperCamelCase : List[str] = max_position_embeddings
UpperCamelCase : List[str] = type_vocab_size
UpperCamelCase : Optional[Any] = type_sequence_label_size
UpperCamelCase : Dict = initializer_range
UpperCamelCase : Optional[Any] = num_labels
UpperCamelCase : Optional[Any] = num_choices
UpperCamelCase : Union[str, Any] = scope
def a_ ( self ):
UpperCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
UpperCamelCase : Tuple = None
if self.use_input_mask:
UpperCamelCase : str = random_attention_mask([self.batch_size, self.seq_length] )
UpperCamelCase : List[str] = None
if self.use_token_type_ids:
UpperCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
UpperCamelCase : List[str] = None
UpperCamelCase : Any = None
UpperCamelCase : str = None
if self.use_labels:
UpperCamelCase : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
UpperCamelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices )
UpperCamelCase : Dict = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def a_ ( self ):
return MegatronBertConfig(
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 , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , )
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : Tuple = MegatronBertModel(config=UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.eval()
UpperCamelCase : Tuple = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ )
UpperCamelCase : List[str] = model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ )
UpperCamelCase : str = model(UpperCAmelCase_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) )
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : Any = MegatronBertForMaskedLM(config=UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.eval()
UpperCamelCase : str = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : int = MegatronBertForCausalLM(config=UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.eval()
UpperCamelCase : str = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : List[Any] = MegatronBertForNextSentencePrediction(config=UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.eval()
UpperCamelCase : Optional[int] = model(
UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) )
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : Optional[Any] = MegatronBertForPreTraining(config=UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.eval()
UpperCamelCase : Optional[int] = model(
UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , next_sentence_label=UpperCAmelCase_ , )
self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) )
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : Dict = MegatronBertForQuestionAnswering(config=UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.eval()
UpperCamelCase : Tuple = model(
UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=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 a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : List[Any] = self.num_labels
UpperCamelCase : List[str] = MegatronBertForSequenceClassification(UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.eval()
UpperCamelCase : Optional[Any] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : List[Any] = self.num_labels
UpperCamelCase : Tuple = MegatronBertForTokenClassification(config=UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.eval()
UpperCamelCase : Optional[int] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : Dict = self.num_choices
UpperCamelCase : int = MegatronBertForMultipleChoice(config=UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.eval()
UpperCamelCase : Any = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
UpperCamelCase : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
UpperCamelCase : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
UpperCamelCase : List[str] = model(
UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def a_ ( self ):
UpperCamelCase : Union[str, Any] = self.prepare_config_and_inputs()
(
UpperCamelCase
) : str = config_and_inputs
UpperCamelCase : Optional[int] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class lowerCamelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ):
lowercase : Union[str, Any] = (
(
MegatronBertModel,
MegatronBertForMaskedLM,
MegatronBertForCausalLM,
MegatronBertForMultipleChoice,
MegatronBertForNextSentencePrediction,
MegatronBertForPreTraining,
MegatronBertForQuestionAnswering,
MegatronBertForSequenceClassification,
MegatronBertForTokenClassification,
)
if is_torch_available()
else ()
)
lowercase : Union[str, Any] = (
{
'feature-extraction': MegatronBertModel,
'fill-mask': MegatronBertForMaskedLM,
'question-answering': MegatronBertForQuestionAnswering,
'text-classification': MegatronBertForSequenceClassification,
'text-generation': MegatronBertForCausalLM,
'token-classification': MegatronBertForTokenClassification,
'zero-shot': MegatronBertForSequenceClassification,
}
if is_torch_available()
else {}
)
lowercase : Union[str, Any] = True
# test_resize_embeddings = False
lowercase : Optional[int] = False
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ):
UpperCamelCase : Optional[int] = super()._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ )
if return_labels:
if model_class in get_values(UpperCAmelCase_ ):
UpperCamelCase : List[Any] = torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase_ )
UpperCamelCase : int = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase_ )
return inputs_dict
def a_ ( self ):
UpperCamelCase : Dict = MegatronBertModelTester(self )
UpperCamelCase : int = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 )
def a_ ( self ):
self.config_tester.run_common_tests()
def a_ ( self ):
UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_model(*UpperCAmelCase_ )
def a_ ( self ):
UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_masked_lm(*UpperCAmelCase_ )
def a_ ( self ):
UpperCamelCase : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*UpperCAmelCase_ )
def a_ ( self ):
UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*UpperCAmelCase_ )
def a_ ( self ):
UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_pretraining(*UpperCAmelCase_ )
def a_ ( self ):
UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_question_answering(*UpperCAmelCase_ )
def a_ ( self ):
UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*UpperCAmelCase_ )
def a_ ( self ):
UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_megatron_bert_for_token_classification(*UpperCAmelCase_ )
def A_ ( snake_case_ : Union[str, Any] ):
'''simple docstring'''
return torch.tensor(
__a ,dtype=torch.long ,device=__a ,)
__A : int = 1e-4
@require_torch
@require_sentencepiece
@require_tokenizers
class lowerCamelCase ( unittest.TestCase ):
@slow
@unittest.skip("""Model is not available.""" )
def a_ ( self ):
UpperCamelCase : Optional[Any] = "nvidia/megatron-bert-uncased-345m"
if "MYDIR" in os.environ:
UpperCamelCase : Optional[int] = os.path.join(os.environ["""MYDIR"""] , UpperCAmelCase_ )
UpperCamelCase : Dict = MegatronBertModel.from_pretrained(UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.half()
UpperCamelCase : str = _long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]] )
with torch.no_grad():
UpperCamelCase : Dict = model(UpperCAmelCase_ )[0]
UpperCamelCase : Dict = torch.Size((1, 9, 1024) )
self.assertEqual(output.shape , UpperCAmelCase_ )
UpperCamelCase : Any = [-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728]
for ii in range(3 ):
for jj in range(3 ):
UpperCamelCase : Optional[Any] = output[0, ii, jj]
UpperCamelCase : Optional[Any] = expected[3 * ii + jj]
UpperCamelCase : Tuple = "ii={} jj={} a={} b={}".format(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
self.assertTrue(math.isclose(UpperCAmelCase_ , UpperCAmelCase_ , rel_tol=UpperCAmelCase_ , abs_tol=UpperCAmelCase_ ) , msg=UpperCAmelCase_ )
| 499 |
import logging
import os
from typing import Dict, List, Optional, Union
import torch
import torch.nn as nn
from accelerate.utils.imports import (
is_abit_bnb_available,
is_abit_bnb_available,
is_bnb_available,
)
from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
find_tied_parameters,
get_balanced_memory,
infer_auto_device_map,
load_checkpoint_in_model,
offload_weight,
set_module_tensor_to_device,
)
if is_bnb_available():
import bitsandbytes as bnb
from copy import deepcopy
__A = logging.getLogger(__name__)
def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str:
"""simple docstring"""
lowerCamelCase__: int =bnb_quantization_config.load_in_abit
lowerCamelCase__: Any =bnb_quantization_config.load_in_abit
if load_in_abit and not is_abit_bnb_available():
raise ImportError(
"You have a version of `bitsandbytes` that is not compatible with 8bit quantization,"
" make sure you have the latest version of `bitsandbytes` installed." )
if load_in_abit and not is_abit_bnb_available():
raise ValueError(
"You have a version of `bitsandbytes` that is not compatible with 4bit quantization,"
"make sure you have the latest version of `bitsandbytes` installed." )
lowerCamelCase__: List[Any] =[]
# custom device map
if isinstance(__a , __a ) and len(device_map.keys() ) > 1:
lowerCamelCase__: Optional[int] =[key for key, value in device_map.items() if value in ["disk", "cpu"]]
# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
if bnb_quantization_config.skip_modules is None:
lowerCamelCase__: Any =get_keys_to_not_convert(__a )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(__a )
lowerCamelCase__: List[str] =bnb_quantization_config.skip_modules
# We add the modules we want to keep in full precision
if bnb_quantization_config.keep_in_fpaa_modules is None:
lowerCamelCase__: List[Any] =[]
lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(__a )
# compatibility with peft
lowerCamelCase__: List[str] =load_in_abit
lowerCamelCase__: int =load_in_abit
lowerCamelCase__: Tuple =get_parameter_device(__a )
if model_device.type != "meta":
# quantization of an already loaded model
logger.warning(
"It is not recommended to quantize a loaded model. "
"The model should be instantiated under the `init_empty_weights` context manager." )
lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a )
# convert param to the right dtype
lowerCamelCase__: Dict =bnb_quantization_config.torch_dtype
for name, param in model.state_dict().items():
if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ):
param.to(torch.floataa )
if param.dtype != torch.floataa:
lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" )
lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(__a ):
param.to(__a )
if model_device.type == "cuda":
# move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
model.cuda(torch.cuda.current_device() )
torch.cuda.empty_cache()
elif torch.cuda.is_available():
model.to(torch.cuda.current_device() )
else:
raise RuntimeError("No GPU found. A GPU is needed for quantization." )
logger.info(
F"""The model device type is {model_device.type}. However, cuda is needed for quantization."""
"We move the model to cuda." )
return model
elif weights_location is None:
raise RuntimeError(
F"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ )
else:
with init_empty_weights():
lowerCamelCase__: str =replace_with_bnb_layers(
__a , __a , modules_to_not_convert=__a )
lowerCamelCase__: Optional[Any] =get_quantized_model_device_map(
__a , __a , __a , max_memory=__a , no_split_module_classes=__a , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
lowerCamelCase__: Any =True
lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] )
load_checkpoint_in_model(
__a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(__a , device_map=__a , offload_dir=__a )
def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str:
"""simple docstring"""
if device_map is None:
if torch.cuda.is_available():
lowerCamelCase__: str ={"": torch.cuda.current_device()}
else:
raise RuntimeError("No GPU found. A GPU is needed for quantization." )
logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." )
if isinstance(__a , __a ):
if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
raise ValueError(
"If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or "
"'sequential'." )
lowerCamelCase__: Optional[int] ={}
special_dtypes.update(
{
name: bnb_quantization_config.torch_dtype
for name, _ in model.named_parameters()
if any(m in name for m in bnb_quantization_config.skip_modules )
} )
special_dtypes.update(
{
name: torch.floataa
for name, _ in model.named_parameters()
if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules )
} )
lowerCamelCase__: Optional[Any] ={}
lowerCamelCase__: str =special_dtypes
lowerCamelCase__: List[str] =no_split_module_classes
lowerCamelCase__: Dict =bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
lowerCamelCase__: Optional[Any] =get_balanced_memory(
__a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , )
lowerCamelCase__: Union[str, Any] =max_memory
lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a )
if isinstance(__a , __a ):
# check if don't have any quantized module on the cpu
lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
lowerCamelCase__: List[Any] ={
key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
}
for device in ["cpu", "disk"]:
if device in device_map_without_some_modules.values():
if bnb_quantization_config.load_in_abit:
raise ValueError(
"\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " )
else:
logger.info(
"Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" )
del device_map_without_some_modules
return device_map
def lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]:
"""simple docstring"""
if modules_to_not_convert is None:
lowerCamelCase__: List[Any] =[]
lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers(
__a , __a , __a , __a )
if not has_been_replaced:
logger.warning(
"You are loading your model in 8bit or 4bit but no linear modules were found in your model."
" this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers."
" Please double check your model architecture, or submit an issue on github if you think this is"
" a bug." )
return model
def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: Optional[int] =False
for name, module in model.named_children():
if current_key_name is None:
lowerCamelCase__: Optional[Any] =[]
current_key_name.append(__a )
if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
lowerCamelCase__: List[str] =".".join(__a )
lowerCamelCase__: Optional[Any] =True
for key in modules_to_not_convert:
if (
(key in current_key_name_str) and (key + "." in current_key_name_str)
) or key == current_key_name_str:
lowerCamelCase__: int =False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
lowerCamelCase__: Dict =bnb.nn.Linearabit(
module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , )
else:
raise ValueError("load_in_8bit and load_in_4bit can't be both False" )
lowerCamelCase__: Dict =module.weight.data
if module.bias is not None:
lowerCamelCase__: List[Any] =module.bias.data
bnb_module.requires_grad_(__a )
setattr(__a , __a , __a )
lowerCamelCase__: int =True
if len(list(module.children() ) ) > 0:
lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers(
__a , __a , __a , __a )
lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def lowerCAmelCase_ ( __a ) -> List[Any]:
"""simple docstring"""
with init_empty_weights():
lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
lowerCamelCase__: str =find_tied_parameters(__a )
# For compatibility with Accelerate < 0.18
if isinstance(__a , __a ):
lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
lowerCamelCase__: str =sum(__a , [] )
lowerCamelCase__: str =len(__a ) > 0
# Check if it is a base model
lowerCamelCase__: Optional[Any] =False
if hasattr(__a , "base_model_prefix" ):
lowerCamelCase__: Union[str, Any] =not hasattr(__a , model.base_model_prefix )
# Ignore this for base models (BertModel, GPT2Model, etc.)
if (not has_tied_params) and is_base_model:
return []
# otherwise they have an attached head
lowerCamelCase__: Optional[int] =list(model.named_children() )
lowerCamelCase__: Optional[int] =[list_modules[-1][0]]
# add last module together with tied weights
lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a )
lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a )
# remove ".weight" from the keys
lowerCamelCase__: List[Any] =[".weight", ".bias"]
lowerCamelCase__: Tuple =[]
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
lowerCamelCase__: Optional[Any] =name.replace(__a , "" )
filtered_module_names.append(__a )
return filtered_module_names
def lowerCAmelCase_ ( __a ) -> Tuple:
"""simple docstring"""
for m in model.modules():
if isinstance(__a , bnb.nn.Linearabit ):
return True
return False
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
return next(parameter.parameters() ).device
def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any:
"""simple docstring"""
if fpaa_statistics is None:
set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a )
lowerCamelCase__: Dict =param_name
lowerCamelCase__: Tuple =model
if "." in tensor_name:
lowerCamelCase__: Any =tensor_name.split("." )
for split in splits[:-1]:
lowerCamelCase__: Any =getattr(__a , __a )
if new_module is None:
raise ValueError(F"""{module} has no attribute {split}.""" )
lowerCamelCase__: str =new_module
lowerCamelCase__: int =splits[-1]
# offload weights
lowerCamelCase__: str =False
offload_weight(module._parameters[tensor_name] , __a , __a , index=__a )
if hasattr(module._parameters[tensor_name] , "SCB" ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , )
else:
offload_weight(__a , __a , __a , index=__a )
offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a )
set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
| 59 | 0 |
from __future__ import annotations
import sys
from collections import deque
from typing import Generic, TypeVar
_lowercase = TypeVar('T')
class lowerCamelCase__ ( Generic[T] ):
__lowerCamelCase = 42 # Cache store of keys
__lowerCamelCase = 42 # References of the keys in cache
__lowerCamelCase = 10 # Maximum capacity of cache
def __init__( self : Optional[int] , __a : int ):
'''simple docstring'''
lowerCamelCase__: Optional[int] = deque()
lowerCamelCase__: List[Any] = set()
if not n:
lowerCamelCase__: List[Any] = sys.maxsize
elif n < 0:
raise ValueError("""n should be an integer greater than 0.""" )
else:
lowerCamelCase__: int = n
def lowerCamelCase_ ( self : List[Any] , __a : T ):
'''simple docstring'''
if x not in self.key_reference:
if len(self.dq_store ) == LRUCache._MAX_CAPACITY:
lowerCamelCase__: Optional[int] = self.dq_store.pop()
self.key_reference.remove(__a )
else:
self.dq_store.remove(__a )
self.dq_store.appendleft(__a )
self.key_reference.add(__a )
def lowerCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
for k in self.dq_store:
print(__a )
def __repr__( self : str ):
'''simple docstring'''
return f"""LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}"""
if __name__ == "__main__":
import doctest
doctest.testmod()
_lowercase = LRUCache(4)
lru_cache.refer('A')
lru_cache.refer(2)
lru_cache.refer(3)
lru_cache.refer('A')
lru_cache.refer(4)
lru_cache.refer(5)
lru_cache.display()
print(lru_cache)
assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
| 717 |
from dataclasses import dataclass, field
from typing import Tuple
from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments
if is_torch_available():
import torch
if is_torch_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
_lowercase = logging.get_logger(__name__)
@dataclass
class lowerCamelCase__ ( A__ ):
__lowerCamelCase = [
"""no_inference""",
"""no_cuda""",
"""no_tpu""",
"""no_speed""",
"""no_memory""",
"""no_env_print""",
"""no_multi_process""",
]
def __init__( self : Optional[Any] , **__a : Optional[Any] ):
'''simple docstring'''
for deprecated_arg in self.deprecated_args:
if deprecated_arg in kwargs:
lowerCamelCase__: List[Any] = deprecated_arg[3:]
setattr(self , __a , not kwargs.pop(__a ) )
logger.warning(
f"""{deprecated_arg} is depreciated. Please use --no_{positive_arg} or"""
f""" {positive_arg}={kwargs[positive_arg]}""" )
lowerCamelCase__: int = kwargs.pop("""torchscript""" , self.torchscript )
lowerCamelCase__: str = kwargs.pop("""torch_xla_tpu_print_metrics""" , self.torch_xla_tpu_print_metrics )
lowerCamelCase__: List[str] = kwargs.pop("""fp16_opt_level""" , self.fpaa_opt_level )
super().__init__(**__a )
__lowerCamelCase = field(default=A__ , metadata={"""help""": """Trace the models using torchscript"""} )
__lowerCamelCase = field(default=A__ , metadata={"""help""": """Print Xla/PyTorch tpu metrics"""} )
__lowerCamelCase = field(
default="""O1""" , metadata={
"""help""": (
"""For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. """
"""See details at https://nvidia.github.io/apex/amp.html"""
)
} , )
@cached_property
def lowerCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
requires_backends(self , ["""torch"""] )
logger.info("""PyTorch: setting up devices""" )
if not self.cuda:
lowerCamelCase__: Dict = torch.device("""cpu""" )
lowerCamelCase__: Optional[int] = 0
elif is_torch_tpu_available():
lowerCamelCase__: str = xm.xla_device()
lowerCamelCase__: Dict = 0
else:
lowerCamelCase__: int = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" )
lowerCamelCase__: Tuple = torch.cuda.device_count()
return device, n_gpu
@property
def lowerCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
return is_torch_tpu_available() and self.tpu
@property
def lowerCamelCase_ ( self : Any ):
'''simple docstring'''
requires_backends(self , ["""torch"""] )
# TODO(PVP): currently only single GPU is supported
return torch.cuda.current_device()
@property
def lowerCamelCase_ ( self : Any ):
'''simple docstring'''
requires_backends(self , ["""torch"""] )
return self._setup_devices[0]
@property
def lowerCamelCase_ ( self : List[Any] ):
'''simple docstring'''
requires_backends(self , ["""torch"""] )
return self._setup_devices[1]
@property
def lowerCamelCase_ ( self : Any ):
'''simple docstring'''
return self.n_gpu > 0
| 242 | 0 |
"""simple docstring"""
import warnings
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class lowercase__ ( A ):
'''simple docstring'''
_UpperCAmelCase = ['''image_processor''', '''tokenizer''']
_UpperCAmelCase = '''LayoutLMv3ImageProcessor'''
_UpperCAmelCase = ('''LayoutLMv3Tokenizer''', '''LayoutLMv3TokenizerFast''')
def __init__( self , snake_case=None , snake_case=None , **snake_case ) -> List[Any]:
_UpperCAmelCase = None
if "feature_extractor" in kwargs:
warnings.warn(
'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
' instead.' , snake_case , )
_UpperCAmelCase = kwargs.pop('feature_extractor' )
_UpperCAmelCase = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('You need to specify an `image_processor`.' )
if tokenizer is None:
raise ValueError('You need to specify a `tokenizer`.' )
super().__init__(snake_case , snake_case )
def __call__( self , snake_case , snake_case = None , snake_case = None , snake_case = None , snake_case = None , snake_case = True , snake_case = False , snake_case = None , snake_case = None , snake_case = 0 , snake_case = None , snake_case = None , snake_case = None , snake_case = False , snake_case = False , snake_case = False , snake_case = False , snake_case = True , snake_case = None , **snake_case , ) -> BatchEncoding:
# verify input
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 = 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 = [text] # add batch dimension (as the image processor always adds a batch dimension)
_UpperCAmelCase = features['words']
_UpperCAmelCase = 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 = features.pop('pixel_values' )
if return_overflowing_tokens is True:
_UpperCAmelCase = self.get_overflowing_images(snake_case , encoded_inputs['overflow_to_sample_mapping'] )
_UpperCAmelCase = images
return encoded_inputs
def lowerCamelCase_ ( self , snake_case , snake_case ) -> str:
# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
_UpperCAmelCase = []
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 lowerCamelCase_ ( self , *snake_case , **snake_case ) -> Dict:
return self.tokenizer.batch_decode(*snake_case , **snake_case )
def lowerCamelCase_ ( self , *snake_case , **snake_case ) -> str:
return self.tokenizer.decode(*snake_case , **snake_case )
@property
def lowerCamelCase_ ( self ) -> Any:
return ["input_ids", "bbox", "attention_mask", "pixel_values"]
@property
def lowerCamelCase_ ( self ) -> Optional[Any]:
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 lowerCamelCase_ ( self ) -> List[Any]:
warnings.warn(
'`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , snake_case , )
return self.image_processor
| 573 |
"""simple docstring"""
import tempfile
import numpy as np
import torch
from transformers import AutoTokenizer, TaEncoderModel
from diffusers import DDPMScheduler, UNetaDConditionModel
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.pipelines.deepfloyd_if import IFWatermarker
from diffusers.utils.testing_utils import torch_device
from ..test_pipelines_common import to_np
class lowercase__ :
'''simple docstring'''
def lowerCamelCase_ ( self ) -> Optional[int]:
torch.manual_seed(0 )
_UpperCAmelCase = TaEncoderModel.from_pretrained('hf-internal-testing/tiny-random-t5' )
torch.manual_seed(0 )
_UpperCAmelCase = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-t5' )
torch.manual_seed(0 )
_UpperCAmelCase = UNetaDConditionModel(
sample_size=32 , layers_per_block=1 , block_out_channels=[32, 64] , down_block_types=[
'ResnetDownsampleBlock2D',
'SimpleCrossAttnDownBlock2D',
] , mid_block_type='UNetMidBlock2DSimpleCrossAttn' , up_block_types=['SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'] , in_channels=3 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type='text' , addition_embed_type_num_heads=2 , cross_attention_norm='group_norm' , resnet_time_scale_shift='scale_shift' , act_fn='gelu' , )
unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests
torch.manual_seed(0 )
_UpperCAmelCase = DDPMScheduler(
num_train_timesteps=1000 , beta_schedule='squaredcos_cap_v2' , beta_start=0.0001 , beta_end=0.02 , thresholding=snake_case , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='epsilon' , variance_type='learned_range' , )
torch.manual_seed(0 )
_UpperCAmelCase = IFWatermarker()
return {
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"unet": unet,
"scheduler": scheduler,
"watermarker": watermarker,
"safety_checker": None,
"feature_extractor": None,
}
def lowerCamelCase_ ( self ) -> Union[str, Any]:
torch.manual_seed(0 )
_UpperCAmelCase = TaEncoderModel.from_pretrained('hf-internal-testing/tiny-random-t5' )
torch.manual_seed(0 )
_UpperCAmelCase = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-t5' )
torch.manual_seed(0 )
_UpperCAmelCase = UNetaDConditionModel(
sample_size=32 , layers_per_block=[1, 2] , block_out_channels=[32, 64] , down_block_types=[
'ResnetDownsampleBlock2D',
'SimpleCrossAttnDownBlock2D',
] , mid_block_type='UNetMidBlock2DSimpleCrossAttn' , up_block_types=['SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'] , in_channels=6 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type='text' , addition_embed_type_num_heads=2 , cross_attention_norm='group_norm' , resnet_time_scale_shift='scale_shift' , act_fn='gelu' , class_embed_type='timestep' , mid_block_scale_factor=1.414 , time_embedding_act_fn='gelu' , time_embedding_dim=32 , )
unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests
torch.manual_seed(0 )
_UpperCAmelCase = DDPMScheduler(
num_train_timesteps=1000 , beta_schedule='squaredcos_cap_v2' , beta_start=0.0001 , beta_end=0.02 , thresholding=snake_case , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='epsilon' , variance_type='learned_range' , )
torch.manual_seed(0 )
_UpperCAmelCase = DDPMScheduler(
num_train_timesteps=1000 , beta_schedule='squaredcos_cap_v2' , beta_start=0.0001 , beta_end=0.02 , )
torch.manual_seed(0 )
_UpperCAmelCase = IFWatermarker()
return {
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"unet": unet,
"scheduler": scheduler,
"image_noising_scheduler": image_noising_scheduler,
"watermarker": watermarker,
"safety_checker": None,
"feature_extractor": None,
}
def lowerCamelCase_ ( self ) -> Tuple:
_UpperCAmelCase = self.get_dummy_components()
_UpperCAmelCase = self.pipeline_class(**snake_case )
pipe.to(snake_case )
pipe.set_progress_bar_config(disable=snake_case )
_UpperCAmelCase = self.get_dummy_inputs(snake_case )
_UpperCAmelCase = inputs['prompt']
_UpperCAmelCase = inputs['generator']
_UpperCAmelCase = inputs['num_inference_steps']
_UpperCAmelCase = inputs['output_type']
if "image" in inputs:
_UpperCAmelCase = inputs['image']
else:
_UpperCAmelCase = None
if "mask_image" in inputs:
_UpperCAmelCase = inputs['mask_image']
else:
_UpperCAmelCase = None
if "original_image" in inputs:
_UpperCAmelCase = inputs['original_image']
else:
_UpperCAmelCase = None
_UpperCAmelCase , _UpperCAmelCase = pipe.encode_prompt(snake_case )
# inputs with prompt converted to embeddings
_UpperCAmelCase = {
'prompt_embeds': prompt_embeds,
'negative_prompt_embeds': negative_prompt_embeds,
'generator': generator,
'num_inference_steps': num_inference_steps,
'output_type': output_type,
}
if image is not None:
_UpperCAmelCase = image
if mask_image is not None:
_UpperCAmelCase = mask_image
if original_image is not None:
_UpperCAmelCase = original_image
# set all optional components to None
for optional_component in pipe._optional_components:
setattr(snake_case , snake_case , snake_case )
_UpperCAmelCase = pipe(**snake_case )[0]
with tempfile.TemporaryDirectory() as tmpdir:
pipe.save_pretrained(snake_case )
_UpperCAmelCase = self.pipeline_class.from_pretrained(snake_case )
pipe_loaded.to(snake_case )
pipe_loaded.set_progress_bar_config(disable=snake_case )
pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests
for optional_component in pipe._optional_components:
self.assertTrue(
getattr(snake_case , snake_case ) is None , f'`{optional_component}` did not stay set to None after loading.' , )
_UpperCAmelCase = self.get_dummy_inputs(snake_case )
_UpperCAmelCase = inputs['generator']
_UpperCAmelCase = inputs['num_inference_steps']
_UpperCAmelCase = inputs['output_type']
# inputs with prompt converted to embeddings
_UpperCAmelCase = {
'prompt_embeds': prompt_embeds,
'negative_prompt_embeds': negative_prompt_embeds,
'generator': generator,
'num_inference_steps': num_inference_steps,
'output_type': output_type,
}
if image is not None:
_UpperCAmelCase = image
if mask_image is not None:
_UpperCAmelCase = mask_image
if original_image is not None:
_UpperCAmelCase = original_image
_UpperCAmelCase = pipe_loaded(**snake_case )[0]
_UpperCAmelCase = np.abs(to_np(snake_case ) - to_np(snake_case ) ).max()
self.assertLess(snake_case , 1E-4 )
def lowerCamelCase_ ( self ) -> Dict:
_UpperCAmelCase = self.get_dummy_components()
_UpperCAmelCase = self.pipeline_class(**snake_case )
pipe.to(snake_case )
pipe.set_progress_bar_config(disable=snake_case )
_UpperCAmelCase = self.get_dummy_inputs(snake_case )
_UpperCAmelCase = pipe(**snake_case )[0]
with tempfile.TemporaryDirectory() as tmpdir:
pipe.save_pretrained(snake_case )
_UpperCAmelCase = self.pipeline_class.from_pretrained(snake_case )
pipe_loaded.to(snake_case )
pipe_loaded.set_progress_bar_config(disable=snake_case )
pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests
_UpperCAmelCase = self.get_dummy_inputs(snake_case )
_UpperCAmelCase = pipe_loaded(**snake_case )[0]
_UpperCAmelCase = np.abs(to_np(snake_case ) - to_np(snake_case ) ).max()
self.assertLess(snake_case , 1E-4 )
| 573 | 1 |
from math import sqrt
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and (
number >= 0
), "'number' must been an int and positive"
lowercase_ = True
# 0 and 1 are none primes.
if number <= 1:
lowercase_ = False
for divisor in range(2 , int(round(sqrt(UpperCAmelCase__ ) ) ) + 1 ):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
lowercase_ = False
break
# precondition
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ), "'status' must been from type bool"
return status
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and (n > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
lowercase_ = list(range(2 , n + 1 ) )
lowercase_ = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(UpperCAmelCase__ ) ):
for j in range(i + 1 , len(UpperCAmelCase__ ) ):
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
lowercase_ = 0
# filters actual prime numbers.
lowercase_ = [x for x in begin_list if x != 0]
# precondition
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ), "'ans' must been from type list"
return ans
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and (n > 2), "'N' must been an int and > 2"
lowercase_ = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2 , n + 1 ):
if is_prime(UpperCAmelCase__ ):
ans.append(UpperCAmelCase__ )
# precondition
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ), "'ans' must been from type list"
return ans
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and number >= 0, "'number' must been an int and >= 0"
lowercase_ = [] # this list will be returns of the function.
# potential prime number factors.
lowercase_ = 2
lowercase_ = number
if number == 0 or number == 1:
ans.append(UpperCAmelCase__ )
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(UpperCAmelCase__ ):
while quotient != 1:
if is_prime(UpperCAmelCase__ ) and (quotient % factor == 0):
ans.append(UpperCAmelCase__ )
quotient /= factor
else:
factor += 1
else:
ans.append(UpperCAmelCase__ )
# precondition
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ), "'ans' must been from type list"
return ans
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and (
number >= 0
), "'number' bust been an int and >= 0"
lowercase_ = 0
# prime factorization of 'number'
lowercase_ = prime_factorization(UpperCAmelCase__ )
lowercase_ = max(UpperCAmelCase__ )
# precondition
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ), "'ans' must been from type int"
return ans
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and (
number >= 0
), "'number' bust been an int and >= 0"
lowercase_ = 0
# prime factorization of 'number'
lowercase_ = prime_factorization(UpperCAmelCase__ )
lowercase_ = min(UpperCAmelCase__ )
# precondition
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ), "'ans' must been from type int"
return ans
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ), "'number' must been an int"
assert isinstance(number % 2 == 0 , UpperCAmelCase__ ), "compare bust been from type bool"
return number % 2 == 0
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ), "'number' must been an int"
assert isinstance(number % 2 != 0 , UpperCAmelCase__ ), "compare bust been from type bool"
return number % 2 != 0
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert (
isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and (number > 2) and is_even(UpperCAmelCase__ )
), "'number' must been an int, even and > 2"
lowercase_ = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
lowercase_ = get_prime_numbers(UpperCAmelCase__ )
lowercase_ = len(UpperCAmelCase__ )
# run variable for while-loops.
lowercase_ = 0
lowercase_ = None
# exit variable. for break up the loops
lowercase_ = True
while i < len_pn and loop:
lowercase_ = i + 1
while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number:
lowercase_ = False
ans.append(prime_numbers[i] )
ans.append(prime_numbers[j] )
j += 1
i += 1
# precondition
assert (
isinstance(UpperCAmelCase__ , UpperCAmelCase__ )
and (len(UpperCAmelCase__ ) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0] )
and is_prime(ans[1] )
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
def UpperCAmelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ ):
assert (
isinstance(UpperCAmelCase__ , UpperCAmelCase__ )
and isinstance(UpperCAmelCase__ , UpperCAmelCase__ )
and (numbera >= 0)
and (numbera >= 0)
), "'number1' and 'number2' must been positive integer."
lowercase_ = 0
while numbera != 0:
lowercase_ = numbera % numbera
lowercase_ = numbera
lowercase_ = rest
# precondition
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and (
numbera >= 0
), "'number' must been from type int and positive"
return numbera
def UpperCAmelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ ):
assert (
isinstance(UpperCAmelCase__ , UpperCAmelCase__ )
and isinstance(UpperCAmelCase__ , UpperCAmelCase__ )
and (numbera >= 1)
and (numbera >= 1)
), "'number1' and 'number2' must been positive integer."
lowercase_ = 1 # actual answer that will be return.
# for kgV (x,1)
if numbera > 1 and numbera > 1:
# builds the prime factorization of 'number1' and 'number2'
lowercase_ = prime_factorization(UpperCAmelCase__ )
lowercase_ = prime_factorization(UpperCAmelCase__ )
elif numbera == 1 or numbera == 1:
lowercase_ = []
lowercase_ = []
lowercase_ = max(UpperCAmelCase__ , UpperCAmelCase__ )
lowercase_ = 0
lowercase_ = 0
lowercase_ = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in prime_fac_a:
if n not in done:
if n in prime_fac_a:
lowercase_ = prime_fac_a.count(UpperCAmelCase__ )
lowercase_ = prime_fac_a.count(UpperCAmelCase__ )
for _ in range(max(UpperCAmelCase__ , UpperCAmelCase__ ) ):
ans *= n
else:
lowercase_ = prime_fac_a.count(UpperCAmelCase__ )
for _ in range(UpperCAmelCase__ ):
ans *= n
done.append(UpperCAmelCase__ )
# iterates through primeFac2
for n in prime_fac_a:
if n not in done:
lowercase_ = prime_fac_a.count(UpperCAmelCase__ )
for _ in range(UpperCAmelCase__ ):
ans *= n
done.append(UpperCAmelCase__ )
# precondition
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and (n >= 0), "'number' must been a positive int"
lowercase_ = 0
lowercase_ = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(UpperCAmelCase__ ):
ans += 1
# precondition
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and is_prime(
UpperCAmelCase__ ), "'ans' must been a prime number and from type int"
return ans
def UpperCAmelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ ):
assert (
is_prime(UpperCAmelCase__ ) and is_prime(UpperCAmelCase__ ) and (p_number_a < p_number_a)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
lowercase_ = p_number_a + 1 # jump to the next number
lowercase_ = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(UpperCAmelCase__ ):
number += 1
while number < p_number_a:
ans.append(UpperCAmelCase__ )
number += 1
# fetch the next prime number.
while not is_prime(UpperCAmelCase__ ):
number += 1
# precondition
assert (
isinstance(UpperCAmelCase__ , UpperCAmelCase__ )
and ans[0] != p_number_a
and ans[len(UpperCAmelCase__ ) - 1] != p_number_a
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and (n >= 1), "'n' must been int and >= 1"
lowercase_ = [] # will be returned.
for divisor in range(1 , n + 1 ):
if n % divisor == 0:
ans.append(UpperCAmelCase__ )
# precondition
assert ans[0] == 1 and ans[len(UpperCAmelCase__ ) - 1] == n, "Error in function getDivisiors(...)"
return ans
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and (
number > 1
), "'number' must been an int and >= 1"
lowercase_ = get_divisors(UpperCAmelCase__ )
# precondition
assert (
isinstance(UpperCAmelCase__ , UpperCAmelCase__ )
and (divisors[0] == 1)
and (divisors[len(UpperCAmelCase__ ) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1] ) == number
def UpperCAmelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ ):
assert (
isinstance(UpperCAmelCase__ , UpperCAmelCase__ )
and isinstance(UpperCAmelCase__ , UpperCAmelCase__ )
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
lowercase_ = gcd(abs(UpperCAmelCase__ ) , abs(UpperCAmelCase__ ) )
# precondition
assert (
isinstance(UpperCAmelCase__ , UpperCAmelCase__ )
and (numerator % gcd_of_fraction == 0)
and (denominator % gcd_of_fraction == 0)
), "Error in function gcd(...,...)"
return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and (n >= 0), "'n' must been a int and >= 0"
lowercase_ = 1 # this will be return.
for factor in range(1 , n + 1 ):
ans *= factor
return ans
def UpperCAmelCase_ ( UpperCAmelCase__ ):
assert isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and (n >= 0), "'n' must been an int and >= 0"
lowercase_ = 0
lowercase_ = 1
lowercase_ = 1 # this will be return
for _ in range(n - 1 ):
lowercase_ = ans
ans += fiba
lowercase_ = tmp
return ans
| 650 |
from __future__ import annotations
import sys
from collections import deque
from typing import Generic, TypeVar
a = TypeVar('T')
class UpperCamelCase__ ( Generic[T] ):
__SCREAMING_SNAKE_CASE : deque[T] # Cache store of keys
__SCREAMING_SNAKE_CASE : set[T] # References of the keys in cache
__SCREAMING_SNAKE_CASE : int = 10 # Maximum capacity of cache
def __init__( self : str , UpperCamelCase__ : int ):
'''simple docstring'''
lowercase_ = deque()
lowercase_ = set()
if not n:
lowercase_ = sys.maxsize
elif n < 0:
raise ValueError("""n should be an integer greater than 0.""" )
else:
lowercase_ = n
def UpperCAmelCase__ ( self : Optional[int] , UpperCamelCase__ : T ):
'''simple docstring'''
if x not in self.key_reference:
if len(self.dq_store ) == LRUCache._MAX_CAPACITY:
lowercase_ = self.dq_store.pop()
self.key_reference.remove(UpperCamelCase__ )
else:
self.dq_store.remove(UpperCamelCase__ )
self.dq_store.appendleft(UpperCamelCase__ )
self.key_reference.add(UpperCamelCase__ )
def UpperCAmelCase__ ( self : List[Any] ):
'''simple docstring'''
for k in self.dq_store:
print(UpperCamelCase__ )
def __repr__( self : Optional[Any] ):
'''simple docstring'''
return F'''LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}'''
if __name__ == "__main__":
import doctest
doctest.testmod()
a = LRUCache(4)
lru_cache.refer('A')
lru_cache.refer(2)
lru_cache.refer(3)
lru_cache.refer('A')
lru_cache.refer(4)
lru_cache.refer(5)
lru_cache.display()
print(lru_cache)
assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
| 650 | 1 |
from math import pi
def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase ) -> float:
'''simple docstring'''
return 2 * pi * radius * (angle / 360)
if __name__ == "__main__":
print(arc_length(90, 10))
| 343 |
import math
import sys
def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ) -> str:
'''simple docstring'''
lowerCAmelCase : str = ''
try:
with open(_UpperCAmelCase, 'rb' ) as binary_file:
lowerCAmelCase : Any = binary_file.read()
for dat in data:
lowerCAmelCase : int = f"{dat:08b}"
result += curr_byte
return result
except OSError:
print('File not accessible' )
sys.exit()
def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ) -> str:
'''simple docstring'''
lowerCAmelCase : Tuple = {'0': '0', '1': '1'}
lowerCAmelCase , lowerCAmelCase : Tuple = '', ''
lowerCAmelCase : Any = len(_UpperCAmelCase )
for i in range(len(_UpperCAmelCase ) ):
curr_string += data_bits[i]
if curr_string not in lexicon:
continue
lowerCAmelCase : List[Any] = lexicon[curr_string]
result += last_match_id
lowerCAmelCase : int = last_match_id + '0'
if math.loga(_UpperCAmelCase ).is_integer():
lowerCAmelCase : List[str] = {}
for curr_key in list(_UpperCAmelCase ):
lowerCAmelCase : List[Any] = lexicon.pop(_UpperCAmelCase )
lowerCAmelCase : Optional[int] = new_lex
lowerCAmelCase : Tuple = last_match_id + '1'
index += 1
lowerCAmelCase : List[Any] = ''
return result
def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase ) -> None:
'''simple docstring'''
lowerCAmelCase : Dict = 8
try:
with open(_UpperCAmelCase, 'wb' ) as opened_file:
lowerCAmelCase : List[Any] = [
to_write[i : i + byte_length]
for i in range(0, len(_UpperCAmelCase ), _UpperCAmelCase )
]
if len(result_byte_array[-1] ) % byte_length == 0:
result_byte_array.append('10000000' )
else:
result_byte_array[-1] += "1" + "0" * (
byte_length - len(result_byte_array[-1] ) - 1
)
for elem in result_byte_array[:-1]:
opened_file.write(int(_UpperCAmelCase, 2 ).to_bytes(1, byteorder='big' ) )
except OSError:
print('File not accessible' )
sys.exit()
def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ) -> str:
'''simple docstring'''
lowerCAmelCase : int = 0
for letter in data_bits:
if letter == "1":
break
counter += 1
lowerCAmelCase : int = data_bits[counter:]
lowerCAmelCase : Optional[int] = data_bits[counter + 1 :]
return data_bits
def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase ) -> None:
'''simple docstring'''
lowerCAmelCase : Tuple = read_file_binary(_UpperCAmelCase )
lowerCAmelCase : int = remove_prefix(_UpperCAmelCase )
lowerCAmelCase : List[str] = decompress_data(_UpperCAmelCase )
write_file_binary(_UpperCAmelCase, _UpperCAmelCase )
if __name__ == "__main__":
compress(sys.argv[1], sys.argv[2])
| 343 | 1 |
"""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
_UpperCAmelCase = logging.getLogger(__name__)
class a ( UpperCAmelCase__ ):
def __init__( self : Any , lowerCAmelCase : str , lowerCAmelCase : List[Any] , lowerCAmelCase : str , lowerCAmelCase : Tuple=None ) -> Optional[int]:
'''simple docstring'''
super().__init__(
__lowerCAmelCase , question_encoder_tokenizer=__lowerCAmelCase , generator_tokenizer=__lowerCAmelCase , index=__lowerCAmelCase , init_retrieval=__lowerCAmelCase , )
SCREAMING_SNAKE_CASE_: List[str] =None
def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : int ) -> Union[str, Any]:
'''simple docstring'''
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
SCREAMING_SNAKE_CASE_: List[str] =self._infer_socket_ifname()
# avoid clash with the NCCL port
SCREAMING_SNAKE_CASE_: Optional[int] =str(distributed_port + 1 )
SCREAMING_SNAKE_CASE_: Any =dist.new_group(ranks=__lowerCAmelCase , 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 lowerCamelCase__ ( self : List[Any] ) -> Union[str, Any]:
'''simple docstring'''
return dist.get_rank(group=self.process_group ) == 0
def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : List[Any] , lowerCAmelCase : Any , lowerCAmelCase : Tuple=torch.floataa ) -> Dict:
'''simple docstring'''
SCREAMING_SNAKE_CASE_: Dict =torch.empty(__lowerCAmelCase , dtype=__lowerCAmelCase )
dist.scatter(__lowerCAmelCase , src=0 , scatter_list=__lowerCAmelCase , group=self.process_group )
return target_tensor
def lowerCamelCase__ ( self : Dict ) -> List[str]:
'''simple docstring'''
SCREAMING_SNAKE_CASE_: int =psutil.net_if_addrs()
# a hacky way to deal with varying network interface names
SCREAMING_SNAKE_CASE_: str =next((addr for addr in addrs if addr.startswith("""e""" )) , __lowerCAmelCase )
return ifname
def lowerCamelCase__ ( self : str , lowerCAmelCase : np.ndarray , lowerCAmelCase : int ) -> Tuple[np.ndarray, List[dict]]:
'''simple docstring'''
if not dist.is_initialized():
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[Any] =self._main_retrieve(__lowerCAmelCase , __lowerCAmelCase )
return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__lowerCAmelCase )
# distributed training
SCREAMING_SNAKE_CASE_: Any =dist.get_world_size(group=self.process_group )
# gather logic
SCREAMING_SNAKE_CASE_: List[str] =None
if self._is_main():
SCREAMING_SNAKE_CASE_: Dict =[torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(__lowerCAmelCase )]
dist.gather(torch.tensor(__lowerCAmelCase ) , dst=0 , gather_list=__lowerCAmelCase , group=self.process_group )
# scatter logic
SCREAMING_SNAKE_CASE_: int =question_hidden_states.shape[0]
SCREAMING_SNAKE_CASE_: Dict =[]
SCREAMING_SNAKE_CASE_: Tuple =[]
if self._is_main():
assert len(__lowerCAmelCase ) == world_size
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =self._main_retrieve(torch.cat(__lowerCAmelCase ).numpy() , __lowerCAmelCase )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =torch.tensor(__lowerCAmelCase ), torch.tensor(__lowerCAmelCase )
SCREAMING_SNAKE_CASE_: Dict =self._chunk_tensor(__lowerCAmelCase , __lowerCAmelCase )
SCREAMING_SNAKE_CASE_: Tuple =self._chunk_tensor(__lowerCAmelCase , __lowerCAmelCase )
SCREAMING_SNAKE_CASE_: Optional[int] =self._scattered(__lowerCAmelCase , [n_queries, n_docs] , target_type=torch.intaa )
SCREAMING_SNAKE_CASE_: Dict =self._scattered(__lowerCAmelCase , [n_queries, n_docs, question_hidden_states.shape[1]] )
return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(__lowerCAmelCase )
| 710 |
"""simple docstring"""
def __magic_name__ ( lowercase , lowercase ):
return int((input_a, input_a).count(0 ) == 0 )
def __magic_name__ ( ):
assert and_gate(0 , 0 ) == 0
assert and_gate(0 , 1 ) == 0
assert and_gate(1 , 0 ) == 0
assert and_gate(1 , 1 ) == 1
if __name__ == "__main__":
test_and_gate()
print(and_gate(1, 0))
print(and_gate(0, 0))
print(and_gate(0, 1))
print(and_gate(1, 1))
| 36 | 0 |
'''simple docstring'''
from typing import Optional
from .. import Features, NamedSplit
from ..packaged_modules.text.text import Text
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
class a_ ( snake_case_ ):
'''simple docstring'''
def __init__( self , A , A = None , A = None , A = None , A = False , A = False , A = None , **A , ) -> Optional[int]:
super().__init__(
A , split=A , features=A , cache_dir=A , keep_in_memory=A , streaming=A , num_proc=A , **A , )
_SCREAMING_SNAKE_CASE = path_or_paths if isinstance(A , A ) else {self.split: path_or_paths}
_SCREAMING_SNAKE_CASE = Text(
cache_dir=A , data_files=A , features=A , **A , )
def snake_case_( self ) -> int:
# Build iterable dataset
if self.streaming:
_SCREAMING_SNAKE_CASE = self.builder.as_streaming_dataset(split=self.split )
# Build regular (map-style) dataset
else:
_SCREAMING_SNAKE_CASE = None
_SCREAMING_SNAKE_CASE = None
_SCREAMING_SNAKE_CASE = None
_SCREAMING_SNAKE_CASE = None
self.builder.download_and_prepare(
download_config=A , download_mode=A , verification_mode=A , base_path=A , num_proc=self.num_proc , )
_SCREAMING_SNAKE_CASE = self.builder.as_dataset(
split=self.split , verification_mode=A , in_memory=self.keep_in_memory )
return dataset
| 314 |
'''simple docstring'''
import argparse
import json
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
torch.set_grad_enabled(False)
def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : Dict=False ) ->List[Any]:
_SCREAMING_SNAKE_CASE = []
for i in range(config.num_hidden_layers ):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append((F'module.blocks.{i}.norm1.weight', F'vit.encoder.layer.{i}.layernorm_before.weight') )
rename_keys.append((F'module.blocks.{i}.norm1.bias', F'vit.encoder.layer.{i}.layernorm_before.bias') )
rename_keys.append(
(F'module.blocks.{i}.attn.proj.weight', F'vit.encoder.layer.{i}.attention.output.dense.weight') )
rename_keys.append((F'module.blocks.{i}.attn.proj.bias', F'vit.encoder.layer.{i}.attention.output.dense.bias') )
rename_keys.append((F'module.blocks.{i}.norm2.weight', F'vit.encoder.layer.{i}.layernorm_after.weight') )
rename_keys.append((F'module.blocks.{i}.norm2.bias', F'vit.encoder.layer.{i}.layernorm_after.bias') )
rename_keys.append((F'module.blocks.{i}.mlp.fc1.weight', F'vit.encoder.layer.{i}.intermediate.dense.weight') )
rename_keys.append((F'module.blocks.{i}.mlp.fc1.bias', F'vit.encoder.layer.{i}.intermediate.dense.bias') )
rename_keys.append((F'module.blocks.{i}.mlp.fc2.weight', F'vit.encoder.layer.{i}.output.dense.weight') )
rename_keys.append((F'module.blocks.{i}.mlp.fc2.bias', F'vit.encoder.layer.{i}.output.dense.bias') )
# projection layer + position embeddings
rename_keys.extend(
[
("""module.cls_token""", """vit.embeddings.cls_token"""),
("""module.patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""),
("""module.patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""),
("""module.pos_embed""", """vit.embeddings.position_embeddings"""),
] )
if base_model:
# layernorm + pooler
rename_keys.extend(
[
("""module.norm.weight""", """layernorm.weight"""),
("""module.norm.bias""", """layernorm.bias"""),
] )
# if just the base model, we should remove "vit" from all keys that start with "vit"
_SCREAMING_SNAKE_CASE = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys]
else:
# layernorm + classification head
rename_keys.extend(
[
("""norm.weight""", """vit.layernorm.weight"""),
("""norm.bias""", """vit.layernorm.bias"""),
("""head.weight""", """classifier.weight"""),
("""head.bias""", """classifier.bias"""),
] )
return rename_keys
def lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int]=False ) ->Optional[int]:
for i in range(config.num_hidden_layers ):
if base_model:
_SCREAMING_SNAKE_CASE = """"""
else:
_SCREAMING_SNAKE_CASE = """vit."""
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
_SCREAMING_SNAKE_CASE = state_dict.pop(F'module.blocks.{i}.attn.qkv.weight' )
_SCREAMING_SNAKE_CASE = state_dict.pop(F'module.blocks.{i}.attn.qkv.bias' )
# next, add query, keys and values (in that order) to the state dict
_SCREAMING_SNAKE_CASE = in_proj_weight[
: config.hidden_size, :
]
_SCREAMING_SNAKE_CASE = in_proj_bias[: config.hidden_size]
_SCREAMING_SNAKE_CASE = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
_SCREAMING_SNAKE_CASE = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
_SCREAMING_SNAKE_CASE = in_proj_weight[
-config.hidden_size :, :
]
_SCREAMING_SNAKE_CASE = in_proj_bias[-config.hidden_size :]
def lowerCamelCase ( __lowerCamelCase : Dict ) ->Dict:
_SCREAMING_SNAKE_CASE = ["""head.weight""", """head.bias"""]
for k in ignore_keys:
state_dict.pop(__lowerCamelCase , __lowerCamelCase )
def lowerCamelCase ( __lowerCamelCase : Union[str, Any] ) ->Union[str, Any]:
# projection head is used in the self-supervised pre-training in MSN,
# for downstream task it's not needed.
_SCREAMING_SNAKE_CASE = [
"""module.fc.fc1.weight""",
"""module.fc.fc1.bias""",
"""module.fc.bn1.weight""",
"""module.fc.bn1.bias""",
"""module.fc.bn1.running_mean""",
"""module.fc.bn1.running_var""",
"""module.fc.bn1.num_batches_tracked""",
"""module.fc.fc2.weight""",
"""module.fc.fc2.bias""",
"""module.fc.bn2.weight""",
"""module.fc.bn2.bias""",
"""module.fc.bn2.running_mean""",
"""module.fc.bn2.running_var""",
"""module.fc.bn2.num_batches_tracked""",
"""module.fc.fc3.weight""",
"""module.fc.fc3.bias""",
]
for k in ignore_keys:
state_dict.pop(__lowerCamelCase , __lowerCamelCase )
def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : List[str] , __lowerCamelCase : Optional[int] ) ->Optional[Any]:
_SCREAMING_SNAKE_CASE = dct.pop(__lowerCamelCase )
_SCREAMING_SNAKE_CASE = val
def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : Tuple ) ->List[str]:
_SCREAMING_SNAKE_CASE = ViTMSNConfig()
_SCREAMING_SNAKE_CASE = 1000
_SCREAMING_SNAKE_CASE = """datasets/huggingface/label-files"""
_SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json"""
_SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase ) , """r""" ) )
_SCREAMING_SNAKE_CASE = {int(__lowerCamelCase ): v for k, v in idalabel.items()}
_SCREAMING_SNAKE_CASE = idalabel
_SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()}
if "s16" in checkpoint_url:
_SCREAMING_SNAKE_CASE = 384
_SCREAMING_SNAKE_CASE = 1536
_SCREAMING_SNAKE_CASE = 6
elif "l16" in checkpoint_url:
_SCREAMING_SNAKE_CASE = 1024
_SCREAMING_SNAKE_CASE = 4096
_SCREAMING_SNAKE_CASE = 24
_SCREAMING_SNAKE_CASE = 16
_SCREAMING_SNAKE_CASE = 0.1
elif "b4" in checkpoint_url:
_SCREAMING_SNAKE_CASE = 4
elif "l7" in checkpoint_url:
_SCREAMING_SNAKE_CASE = 7
_SCREAMING_SNAKE_CASE = 1024
_SCREAMING_SNAKE_CASE = 4096
_SCREAMING_SNAKE_CASE = 24
_SCREAMING_SNAKE_CASE = 16
_SCREAMING_SNAKE_CASE = 0.1
_SCREAMING_SNAKE_CASE = ViTMSNModel(__lowerCamelCase )
_SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(__lowerCamelCase , map_location="""cpu""" )["""target_encoder"""]
_SCREAMING_SNAKE_CASE = ViTImageProcessor(size=config.image_size )
remove_projection_head(__lowerCamelCase )
_SCREAMING_SNAKE_CASE = create_rename_keys(__lowerCamelCase , base_model=__lowerCamelCase )
for src, dest in rename_keys:
rename_key(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
read_in_q_k_v(__lowerCamelCase , __lowerCamelCase , base_model=__lowerCamelCase )
model.load_state_dict(__lowerCamelCase )
model.eval()
_SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg"""
_SCREAMING_SNAKE_CASE = Image.open(requests.get(__lowerCamelCase , stream=__lowerCamelCase ).raw )
_SCREAMING_SNAKE_CASE = ViTImageProcessor(
size=config.image_size , image_mean=__lowerCamelCase , image_std=__lowerCamelCase )
_SCREAMING_SNAKE_CASE = image_processor(images=__lowerCamelCase , return_tensors="""pt""" )
# forward pass
torch.manual_seed(2 )
_SCREAMING_SNAKE_CASE = model(**__lowerCamelCase )
_SCREAMING_SNAKE_CASE = outputs.last_hidden_state
# The following Colab Notebook was used to generate these outputs:
# https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb
if "s16" in checkpoint_url:
_SCREAMING_SNAKE_CASE = torch.tensor([[-1.0915, -1.4876, -1.1809]] )
elif "b16" in checkpoint_url:
_SCREAMING_SNAKE_CASE = torch.tensor([[14.2889, -18.9045, 11.7281]] )
elif "l16" in checkpoint_url:
_SCREAMING_SNAKE_CASE = torch.tensor([[41.5028, -22.8681, 45.6475]] )
elif "b4" in checkpoint_url:
_SCREAMING_SNAKE_CASE = torch.tensor([[-4.3868, 5.2932, -0.4137]] )
else:
_SCREAMING_SNAKE_CASE = torch.tensor([[-0.1792, -0.6465, 2.4263]] )
# verify logits
assert torch.allclose(last_hidden_state[:, 0, :3] , __lowerCamelCase , atol=1e-4 )
print(F'Saving model to {pytorch_dump_folder_path}' )
model.save_pretrained(__lowerCamelCase )
print(F'Saving image processor to {pytorch_dump_folder_path}' )
image_processor.save_pretrained(__lowerCamelCase )
if __name__ == "__main__":
lowercase_ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--checkpoint_url""",
default="""https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar""",
type=str,
help="""URL of the checkpoint you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
)
lowercase_ = parser.parse_args()
convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
| 314 | 1 |
__SCREAMING_SNAKE_CASE : str = {
'''Pillow''': '''Pillow<10.0.0''',
'''accelerate''': '''accelerate>=0.20.3''',
'''av''': '''av==9.2.0''',
'''beautifulsoup4''': '''beautifulsoup4''',
'''black''': '''black~=23.1''',
'''codecarbon''': '''codecarbon==1.2.0''',
'''cookiecutter''': '''cookiecutter==1.7.3''',
'''dataclasses''': '''dataclasses''',
'''datasets''': '''datasets!=2.5.0''',
'''decord''': '''decord==0.6.0''',
'''deepspeed''': '''deepspeed>=0.9.3''',
'''diffusers''': '''diffusers''',
'''dill''': '''dill<0.3.5''',
'''evaluate''': '''evaluate>=0.2.0''',
'''fairscale''': '''fairscale>0.3''',
'''faiss-cpu''': '''faiss-cpu''',
'''fastapi''': '''fastapi''',
'''filelock''': '''filelock''',
'''flax''': '''flax>=0.4.1,<=0.7.0''',
'''ftfy''': '''ftfy''',
'''fugashi''': '''fugashi>=1.0''',
'''GitPython''': '''GitPython<3.1.19''',
'''hf-doc-builder''': '''hf-doc-builder>=0.3.0''',
'''huggingface-hub''': '''huggingface-hub>=0.14.1,<1.0''',
'''importlib_metadata''': '''importlib_metadata''',
'''ipadic''': '''ipadic>=1.0.0,<2.0''',
'''isort''': '''isort>=5.5.4''',
'''jax''': '''jax>=0.2.8,!=0.3.2,<=0.4.13''',
'''jaxlib''': '''jaxlib>=0.1.65,<=0.4.13''',
'''jieba''': '''jieba''',
'''kenlm''': '''kenlm''',
'''keras-nlp''': '''keras-nlp>=0.3.1''',
'''librosa''': '''librosa''',
'''nltk''': '''nltk''',
'''natten''': '''natten>=0.14.6''',
'''numpy''': '''numpy>=1.17''',
'''onnxconverter-common''': '''onnxconverter-common''',
'''onnxruntime-tools''': '''onnxruntime-tools>=1.4.2''',
'''onnxruntime''': '''onnxruntime>=1.4.0''',
'''opencv-python''': '''opencv-python''',
'''optuna''': '''optuna''',
'''optax''': '''optax>=0.0.8,<=0.1.4''',
'''packaging''': '''packaging>=20.0''',
'''parameterized''': '''parameterized''',
'''phonemizer''': '''phonemizer''',
'''protobuf''': '''protobuf''',
'''psutil''': '''psutil''',
'''pyyaml''': '''pyyaml>=5.1''',
'''pydantic''': '''pydantic<2''',
'''pytest''': '''pytest>=7.2.0''',
'''pytest-timeout''': '''pytest-timeout''',
'''pytest-xdist''': '''pytest-xdist''',
'''python''': '''python>=3.8.0''',
'''ray[tune]''': '''ray[tune]''',
'''regex''': '''regex!=2019.12.17''',
'''requests''': '''requests''',
'''rhoknp''': '''rhoknp>=1.1.0,<1.3.1''',
'''rjieba''': '''rjieba''',
'''rouge-score''': '''rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1''',
'''ruff''': '''ruff>=0.0.241,<=0.0.259''',
'''sacrebleu''': '''sacrebleu>=1.4.12,<2.0.0''',
'''sacremoses''': '''sacremoses''',
'''safetensors''': '''safetensors>=0.3.1''',
'''sagemaker''': '''sagemaker>=2.31.0''',
'''scikit-learn''': '''scikit-learn''',
'''sentencepiece''': '''sentencepiece>=0.1.91,!=0.1.92''',
'''sigopt''': '''sigopt''',
'''starlette''': '''starlette''',
'''sudachipy''': '''sudachipy>=0.6.6''',
'''sudachidict_core''': '''sudachidict_core>=20220729''',
'''tensorflow-cpu''': '''tensorflow-cpu>=2.6,<2.14''',
'''tensorflow''': '''tensorflow>=2.6,<2.14''',
'''tensorflow-text''': '''tensorflow-text<2.14''',
'''tf2onnx''': '''tf2onnx''',
'''timeout-decorator''': '''timeout-decorator''',
'''timm''': '''timm''',
'''tokenizers''': '''tokenizers>=0.11.1,!=0.11.3,<0.14''',
'''torch''': '''torch>=1.9,!=1.12.0''',
'''torchaudio''': '''torchaudio''',
'''torchvision''': '''torchvision''',
'''pyctcdecode''': '''pyctcdecode>=0.4.0''',
'''tqdm''': '''tqdm>=4.27''',
'''unidic''': '''unidic>=1.0.2''',
'''unidic_lite''': '''unidic_lite>=1.0.7''',
'''urllib3''': '''urllib3<2.0.0''',
'''uvicorn''': '''uvicorn''',
}
| 149 |
def snake_case_ ( lowercase__ : list[int] ):
'''simple docstring'''
_lowerCAmelCase =[]
if len(lowercase__ ) == 1:
return [nums.copy()]
for _ in range(len(lowercase__ ) ):
_lowerCAmelCase =nums.pop(0 )
_lowerCAmelCase =permute(lowercase__ )
for perm in permutations:
perm.append(lowercase__ )
result.extend(lowercase__ )
nums.append(lowercase__ )
return result
def snake_case_ ( lowercase__ : Optional[Any] ):
'''simple docstring'''
def backtrack(lowercase__ : List[Any] ):
if start == len(lowercase__ ) - 1:
output.append(nums[:] )
else:
for i in range(lowercase__ , len(lowercase__ ) ):
_lowerCAmelCase , _lowerCAmelCase =nums[i], nums[start]
backtrack(start + 1 )
_lowerCAmelCase , _lowerCAmelCase =nums[i], nums[start] # backtrack
_lowerCAmelCase =[]
backtrack(0 )
return output
if __name__ == "__main__":
import doctest
# use res to print the data in permute2 function
__SCREAMING_SNAKE_CASE : Any = permutea([1, 2, 3])
print(res)
doctest.testmod()
| 149 | 1 |
'''simple docstring'''
import argparse
import json
import os
import torch
from transformers.file_utils import has_file
from diffusers import UNetaDConditionModel, UNetaDModel
A_ = False
A_ = True
A_ = False
if __name__ == "__main__":
A_ = argparse.ArgumentParser()
parser.add_argument(
"--repo_path",
default=None,
type=str,
required=True,
help="The config json file corresponding to the architecture.",
)
parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")
A_ = parser.parse_args()
A_ = {
"image_size": "sample_size",
"num_res_blocks": "layers_per_block",
"block_channels": "block_out_channels",
"down_blocks": "down_block_types",
"up_blocks": "up_block_types",
"downscale_freq_shift": "freq_shift",
"resnet_num_groups": "norm_num_groups",
"resnet_act_fn": "act_fn",
"resnet_eps": "norm_eps",
"num_head_channels": "attention_head_dim",
}
A_ = {
"time_steps": "time_proj",
"mid": "mid_block",
"downsample_blocks": "down_blocks",
"upsample_blocks": "up_blocks",
}
A_ = "" if has_file(args.repo_path, "config.json") else "unet"
with open(os.path.join(args.repo_path, subfolder, "config.json"), "r", encoding="utf-8") as reader:
A_ = reader.read()
A_ = json.loads(text)
if do_only_config:
for key in config_parameters_to_change.keys():
config.pop(key, None)
if has_file(args.repo_path, "config.json"):
A_ = UNetaDModel(**config)
else:
A_ = UNetaDConditionModel if "ldm-text2im-large-256" in args.repo_path else UNetaDModel
A_ = class_name(**config)
if do_only_config:
model.save_config(os.path.join(args.repo_path, subfolder))
A_ = dict(model.config)
if do_only_renaming:
for key, value in config_parameters_to_change.items():
if key in config:
A_ = config[key]
del config[key]
A_ = [k.replace("UNetRes", "") for k in config["down_block_types"]]
A_ = [k.replace("UNetRes", "") for k in config["up_block_types"]]
if do_only_weights:
A_ = torch.load(os.path.join(args.repo_path, subfolder, "diffusion_pytorch_model.bin"))
A_ = {}
for param_key, param_value in state_dict.items():
if param_key.endswith(".op.bias") or param_key.endswith(".op.weight"):
continue
A_ = False
for key, new_key in key_parameters_to_change.items():
if not has_changed and param_key.split(".")[0] == key:
A_ = param_value
A_ = True
if not has_changed:
A_ = param_value
model.load_state_dict(new_state_dict)
model.save_pretrained(os.path.join(args.repo_path, subfolder))
| 42 |
from ..utils import DummyObject, requires_backends
class __UpperCamelCase ( metaclass=A__ ):
__A : str = ["""torch""", """scipy"""]
def __init__( self , *_UpperCamelCase , **_UpperCamelCase ):
requires_backends(self , ['''torch''', '''scipy'''] )
@classmethod
def UpperCamelCase( cls , *_UpperCamelCase , **_UpperCamelCase ):
requires_backends(cls , ['''torch''', '''scipy'''] )
@classmethod
def UpperCamelCase( cls , *_UpperCamelCase , **_UpperCamelCase ):
requires_backends(cls , ['''torch''', '''scipy'''] )
| 32 | 0 |
"""simple docstring"""
import numpy as np
from PIL import Image
def __lowerCamelCase ( SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE ) -> Tuple:
"""simple docstring"""
_UpperCAmelCase = np.array(__A )
if arr.shape[0] != arr.shape[1]:
raise ValueError('The input array is not a square matrix' )
_UpperCAmelCase = 0
_UpperCAmelCase = 0
_UpperCAmelCase = 0
_UpperCAmelCase = 0
# compute the shape of the output matrix
_UpperCAmelCase = (arr.shape[0] - size) // stride + 1
# initialize the output matrix with zeros of shape maxpool_shape
_UpperCAmelCase = np.zeros((maxpool_shape, maxpool_shape) )
while i < arr.shape[0]:
if i + size > arr.shape[0]:
# if the end of the matrix is reached, break
break
while j < arr.shape[1]:
# if the end of the matrix is reached, break
if j + size > arr.shape[1]:
break
# compute the maximum of the pooling matrix
_UpperCAmelCase = np.max(arr[i : i + size, j : j + size] )
# shift the pooling matrix by stride of column pixels
j += stride
mat_j += 1
# shift the pooling matrix by stride of row pixels
i += stride
mat_i += 1
# reset the column index to 0
_UpperCAmelCase = 0
_UpperCAmelCase = 0
return updated_arr
def __lowerCamelCase ( SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE ) -> str:
"""simple docstring"""
_UpperCAmelCase = np.array(__A )
if arr.shape[0] != arr.shape[1]:
raise ValueError('The input array is not a square matrix' )
_UpperCAmelCase = 0
_UpperCAmelCase = 0
_UpperCAmelCase = 0
_UpperCAmelCase = 0
# compute the shape of the output matrix
_UpperCAmelCase = (arr.shape[0] - size) // stride + 1
# initialize the output matrix with zeros of shape avgpool_shape
_UpperCAmelCase = np.zeros((avgpool_shape, avgpool_shape) )
while i < arr.shape[0]:
# if the end of the matrix is reached, break
if i + size > arr.shape[0]:
break
while j < arr.shape[1]:
# if the end of the matrix is reached, break
if j + size > arr.shape[1]:
break
# compute the average of the pooling matrix
_UpperCAmelCase = int(np.average(arr[i : i + size, j : j + size] ) )
# shift the pooling matrix by stride of column pixels
j += stride
mat_j += 1
# shift the pooling matrix by stride of row pixels
i += stride
mat_i += 1
# reset the column index to 0
_UpperCAmelCase = 0
_UpperCAmelCase = 0
return updated_arr
# Main Function
if __name__ == "__main__":
from doctest import testmod
testmod(name='''avgpooling''', verbose=True)
# Loading the image
lowerCAmelCase_ = Image.open('''path_to_image''')
# Converting the image to numpy array and maxpooling, displaying the result
# Ensure that the image is a square matrix
Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()
# Converting the image to numpy array and averagepooling, displaying the result
# Ensure that the image is a square matrix
Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
| 701 |
"""simple docstring"""
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
lowerCAmelCase_ = logging.get_logger(__name__)
lowerCAmelCase_ = {
'''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 ( snake_case ):
lowerCAmelCase__ = """deberta-v2"""
def __init__( self , a__=12_81_00 , a__=15_36 , a__=24 , a__=24 , a__=61_44 , a__="gelu" , a__=0.1 , a__=0.1 , a__=5_12 , a__=0 , a__=0.02 , a__=1E-7 , a__=False , a__=-1 , a__=0 , a__=True , a__=None , a__=0 , a__="gelu" , **a__ , ):
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 ( snake_case ):
@property
def __A ( self ):
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 __A ( self ):
return 12
def __A ( self , a__ , a__ = -1 , a__ = -1 , a__ = -1 , a__ = False , a__ = None , a__ = 3 , a__ = 40 , a__ = 40 , a__ = None , ):
_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
| 494 | 0 |
import copy
import re
class __lowercase :
"""simple docstring"""
_UpperCAmelCase = """hp"""
_UpperCAmelCase = {}
_UpperCAmelCase = None
@classmethod
def UpperCamelCase__ ( cls , lowerCAmelCase__ , lowerCAmelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str = prefix
SCREAMING_SNAKE_CASE_ : Dict = defaults
cls.build_naming_info()
@staticmethod
def UpperCamelCase__ ( lowerCAmelCase__ , lowerCAmelCase__ ):
"""simple docstring"""
if len(lowerCAmelCase__ ) == 0:
return ""
SCREAMING_SNAKE_CASE_ : Tuple = None
if any(char.isdigit() for char in word ):
raise Exception(F'''Parameters should not contain numbers: \'{word}\' contains a number''' )
if word in info["short_word"]:
return info["short_word"][word]
for prefix_len in range(1 , len(lowerCAmelCase__ ) + 1 ):
SCREAMING_SNAKE_CASE_ : Tuple = word[:prefix_len]
if prefix in info["reverse_short_word"]:
continue
else:
SCREAMING_SNAKE_CASE_ : Tuple = prefix
break
if short_word is None:
# Paranoid fallback
def int_to_alphabetic(lowerCAmelCase__ ):
SCREAMING_SNAKE_CASE_ : Tuple = ''
while integer != 0:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = chr(ord('A' ) + integer % 1_0 ) + s
integer //= 1_0
return s
SCREAMING_SNAKE_CASE_ : Dict = 0
while True:
SCREAMING_SNAKE_CASE_ : Optional[Any] = word + '#' + int_to_alphabetic(lowerCAmelCase__ )
if sword in info["reverse_short_word"]:
continue
else:
SCREAMING_SNAKE_CASE_ : Dict = sword
break
SCREAMING_SNAKE_CASE_ : List[str] = short_word
SCREAMING_SNAKE_CASE_ : Optional[int] = word
return short_word
@staticmethod
def UpperCamelCase__ ( lowerCAmelCase__ , lowerCAmelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : List[Any] = param_name.split('_' )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = [TrialShortNamer.shortname_for_word(lowerCAmelCase__ , lowerCAmelCase__ ) for word in words]
# We try to create a separatorless short name, but if there is a collision we have to fallback
# to a separated short name
SCREAMING_SNAKE_CASE_ : Any = ['', '_']
for separator in separators:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = separator.join(lowerCAmelCase__ )
if shortname not in info["reverse_short_param"]:
SCREAMING_SNAKE_CASE_ : Any = shortname
SCREAMING_SNAKE_CASE_ : Optional[int] = param_name
return shortname
return param_name
@staticmethod
def UpperCamelCase__ ( lowerCAmelCase__ , lowerCAmelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Union[str, Any] = TrialShortNamer.shortname_for_key(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : List[Any] = short_name
SCREAMING_SNAKE_CASE_ : List[str] = param_name
@classmethod
def UpperCamelCase__ ( cls ):
"""simple docstring"""
if cls.NAMING_INFO is not None:
return
SCREAMING_SNAKE_CASE_ : Any = {
'short_word': {},
'reverse_short_word': {},
'short_param': {},
'reverse_short_param': {},
}
SCREAMING_SNAKE_CASE_ : int = list(cls.DEFAULTS.keys() )
for k in field_keys:
cls.add_new_param_name(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : str = info
@classmethod
def UpperCamelCase__ ( cls , lowerCAmelCase__ ):
"""simple docstring"""
cls.build_naming_info()
assert cls.PREFIX is not None
SCREAMING_SNAKE_CASE_ : str = [copy.copy(cls.PREFIX )]
for k, v in params.items():
if k not in cls.DEFAULTS:
raise Exception(F'''You should provide a default value for the param name {k} with value {v}''' )
if v == cls.DEFAULTS[k]:
# The default value is not added to the name
continue
SCREAMING_SNAKE_CASE_ : int = cls.NAMING_INFO['short_param'][k]
if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ):
SCREAMING_SNAKE_CASE_ : Optional[Any] = 1 if v else 0
SCREAMING_SNAKE_CASE_ : int = '' if isinstance(lowerCAmelCase__ , (int, float) ) else '-'
SCREAMING_SNAKE_CASE_ : List[Any] = F'''{key}{sep}{v}'''
name.append(lowerCAmelCase__ )
return "_".join(lowerCAmelCase__ )
@classmethod
def UpperCamelCase__ ( cls , lowerCAmelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[int] = repr[len(cls.PREFIX ) + 1 :]
if repr == "":
SCREAMING_SNAKE_CASE_ : Optional[Any] = []
else:
SCREAMING_SNAKE_CASE_ : Optional[Any] = repr.split('_' )
SCREAMING_SNAKE_CASE_ : int = {}
for value in values:
if "-" in value:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = value.split('-' )
else:
SCREAMING_SNAKE_CASE_ : str = re.sub('[0-9.]' , '' , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : List[str] = float(re.sub('[^0-9.]' , '' , lowerCAmelCase__ ) )
SCREAMING_SNAKE_CASE_ : int = cls.NAMING_INFO['reverse_short_param'][p_k]
SCREAMING_SNAKE_CASE_ : Union[str, Any] = p_v
for k in cls.DEFAULTS:
if k not in parameters:
SCREAMING_SNAKE_CASE_ : Tuple = cls.DEFAULTS[k]
return parameters
| 101 |
from __future__ import annotations
import math
def _lowercase ( UpperCAmelCase_):
"""simple docstring"""
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(math.sqrt(UpperCAmelCase_) + 1) , 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def _lowercase ( UpperCAmelCase_):
"""simple docstring"""
snake_case__ : List[str] = str(UpperCAmelCase_)
snake_case__ : str = [n]
for i in range(1 , len(UpperCAmelCase_)):
list_nums.append(int(str_num[i:]))
list_nums.append(int(str_num[:-i]))
return list_nums
def _lowercase ( UpperCAmelCase_):
"""simple docstring"""
if len(str(UpperCAmelCase_)) > 3:
if not is_prime(int(str(UpperCAmelCase_)[-3:])) or not is_prime(int(str(UpperCAmelCase_)[:3])):
return False
return True
def _lowercase ( UpperCAmelCase_ = 11):
"""simple docstring"""
snake_case__ : list[int] = []
snake_case__ : Dict = 13
while len(UpperCAmelCase_) != count:
if validate(UpperCAmelCase_):
snake_case__ : Tuple = list_truncated_nums(UpperCAmelCase_)
if all(is_prime(UpperCAmelCase_) for i in list_nums):
list_truncated_primes.append(UpperCAmelCase_)
num += 2
return list_truncated_primes
def _lowercase ( ):
"""simple docstring"""
return sum(compute_truncated_primes(11))
if __name__ == "__main__":
print(F"""{sum(compute_truncated_primes(11)) = }""")
| 648 | 0 |
from typing import Dict, List, Optional, Union
import numpy as np
from transformers.utils import is_vision_available
from transformers.utils.generic import TensorType
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
is_valid_image,
to_numpy_array,
valid_images,
)
from ...utils import logging
if is_vision_available():
import PIL
lowerCamelCase =logging.get_logger(__name__)
def SCREAMING_SNAKE_CASE_ ( UpperCamelCase__ ):
if isinstance(UpperCamelCase__ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ):
return videos
elif isinstance(UpperCamelCase__ , (list, tuple) ) and is_valid_image(videos[0] ):
return [videos]
elif is_valid_image(UpperCamelCase__ ):
return [[videos]]
raise ValueError(f'''Could not make batched video from {videos}''' )
class _lowerCamelCase ( UpperCamelCase_ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = ['''pixel_values''']
def __init__( self , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = 1 / 2_5_5 , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ) -> None:
"""simple docstring"""
super().__init__(**__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Dict = size if size is not None else {'''shortest_edge''': 2_5_6}
UpperCamelCase__ : Optional[Any] = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
UpperCamelCase__ : int = get_size_dict(__SCREAMING_SNAKE_CASE , param_name='''crop_size''' )
UpperCamelCase__ : Optional[int] = do_resize
UpperCamelCase__ : str = size
UpperCamelCase__ : Dict = do_center_crop
UpperCamelCase__ : Tuple = crop_size
UpperCamelCase__ : List[Any] = resample
UpperCamelCase__ : List[Any] = do_rescale
UpperCamelCase__ : Dict = rescale_factor
UpperCamelCase__ : Union[str, Any] = offset
UpperCamelCase__ : Tuple = do_normalize
UpperCamelCase__ : Dict = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
UpperCamelCase__ : str = image_std if image_std is not None else IMAGENET_STANDARD_STD
def __SCREAMING_SNAKE_CASE ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ) -> np.ndarray:
"""simple docstring"""
UpperCamelCase__ : Union[str, Any] = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE )
if "shortest_edge" in size:
UpperCamelCase__ : Any = get_resize_output_image_size(__SCREAMING_SNAKE_CASE , size['''shortest_edge'''] , default_to_square=__SCREAMING_SNAKE_CASE )
elif "height" in size and "width" in size:
UpperCamelCase__ : str = (size['''height'''], size['''width'''])
else:
raise ValueError(F'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' )
return resize(__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE , resample=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
def __SCREAMING_SNAKE_CASE ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ) -> np.ndarray:
"""simple docstring"""
UpperCamelCase__ : List[str] = get_size_dict(__SCREAMING_SNAKE_CASE )
if "height" not in size or "width" not in size:
raise ValueError(F'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}''' )
return center_crop(__SCREAMING_SNAKE_CASE , size=(size['''height'''], size['''width''']) , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
def __SCREAMING_SNAKE_CASE ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ) -> Optional[int]:
"""simple docstring"""
UpperCamelCase__ : List[str] = image.astype(np.floataa )
if offset:
UpperCamelCase__ : Any = image - (scale / 2)
return rescale(__SCREAMING_SNAKE_CASE , scale=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
def __SCREAMING_SNAKE_CASE ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ) -> np.ndarray:
"""simple docstring"""
return normalize(__SCREAMING_SNAKE_CASE , mean=__SCREAMING_SNAKE_CASE , std=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
def __SCREAMING_SNAKE_CASE ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , ) -> np.ndarray:
"""simple docstring"""
if do_resize and size is None or resample is None:
raise ValueError('''Size and resample must be specified if do_resize is True.''' )
if do_center_crop and crop_size is None:
raise ValueError('''Crop size must be specified if do_center_crop is True.''' )
if do_rescale and rescale_factor is None:
raise ValueError('''Rescale factor must be specified if do_rescale is True.''' )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('''Image mean and std must be specified if do_normalize is True.''' )
if offset and not do_rescale:
raise ValueError('''For offset, do_rescale must also be set to True.''' )
# All transformations expect numpy arrays.
UpperCamelCase__ : Optional[int] = to_numpy_array(__SCREAMING_SNAKE_CASE )
if do_resize:
UpperCamelCase__ : Any = self.resize(image=__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE , resample=__SCREAMING_SNAKE_CASE )
if do_center_crop:
UpperCamelCase__ : Optional[Any] = self.center_crop(__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE )
if do_rescale:
UpperCamelCase__ : Union[str, Any] = self.rescale(image=__SCREAMING_SNAKE_CASE , scale=__SCREAMING_SNAKE_CASE , offset=__SCREAMING_SNAKE_CASE )
if do_normalize:
UpperCamelCase__ : List[Any] = self.normalize(image=__SCREAMING_SNAKE_CASE , mean=__SCREAMING_SNAKE_CASE , std=__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Any = to_channel_dimension_format(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
return image
def __SCREAMING_SNAKE_CASE ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **__SCREAMING_SNAKE_CASE , ) -> PIL.Image.Image:
"""simple docstring"""
UpperCamelCase__ : List[Any] = do_resize if do_resize is not None else self.do_resize
UpperCamelCase__ : Dict = resample if resample is not None else self.resample
UpperCamelCase__ : int = do_center_crop if do_center_crop is not None else self.do_center_crop
UpperCamelCase__ : str = do_rescale if do_rescale is not None else self.do_rescale
UpperCamelCase__ : int = rescale_factor if rescale_factor is not None else self.rescale_factor
UpperCamelCase__ : Optional[Any] = offset if offset is not None else self.offset
UpperCamelCase__ : Dict = do_normalize if do_normalize is not None else self.do_normalize
UpperCamelCase__ : int = image_mean if image_mean is not None else self.image_mean
UpperCamelCase__ : int = image_std if image_std is not None else self.image_std
UpperCamelCase__ : Optional[Any] = size if size is not None else self.size
UpperCamelCase__ : Union[str, Any] = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : List[str] = crop_size if crop_size is not None else self.crop_size
UpperCamelCase__ : int = get_size_dict(__SCREAMING_SNAKE_CASE , param_name='''crop_size''' )
if not valid_images(__SCREAMING_SNAKE_CASE ):
raise ValueError(
'''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
'''torch.Tensor, tf.Tensor or jax.ndarray.''' )
UpperCamelCase__ : str = make_batched(__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : List[Any] = [
[
self._preprocess_image(
image=__SCREAMING_SNAKE_CASE , do_resize=__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE , resample=__SCREAMING_SNAKE_CASE , do_center_crop=__SCREAMING_SNAKE_CASE , crop_size=__SCREAMING_SNAKE_CASE , do_rescale=__SCREAMING_SNAKE_CASE , rescale_factor=__SCREAMING_SNAKE_CASE , offset=__SCREAMING_SNAKE_CASE , do_normalize=__SCREAMING_SNAKE_CASE , image_mean=__SCREAMING_SNAKE_CASE , image_std=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , )
for img in video
]
for video in videos
]
UpperCamelCase__ : List[Any] = {'''pixel_values''': videos}
return BatchFeature(data=__SCREAMING_SNAKE_CASE , tensor_type=__SCREAMING_SNAKE_CASE )
| 462 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
lowerCamelCase ={
"configuration_blenderbot": [
"BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP",
"BlenderbotConfig",
"BlenderbotOnnxConfig",
],
"tokenization_blenderbot": ["BlenderbotTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase =["BlenderbotTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase =[
"BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST",
"BlenderbotForCausalLM",
"BlenderbotForConditionalGeneration",
"BlenderbotModel",
"BlenderbotPreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase =[
"TFBlenderbotForConditionalGeneration",
"TFBlenderbotModel",
"TFBlenderbotPreTrainedModel",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase =[
"FlaxBlenderbotForConditionalGeneration",
"FlaxBlenderbotModel",
"FlaxBlenderbotPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_blenderbot import (
BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP,
BlenderbotConfig,
BlenderbotOnnxConfig,
)
from .tokenization_blenderbot import BlenderbotTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_blenderbot_fast import BlenderbotTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_blenderbot import (
BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST,
BlenderbotForCausalLM,
BlenderbotForConditionalGeneration,
BlenderbotModel,
BlenderbotPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_blenderbot import (
TFBlenderbotForConditionalGeneration,
TFBlenderbotModel,
TFBlenderbotPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_blenderbot import (
FlaxBlenderbotForConditionalGeneration,
FlaxBlenderbotModel,
FlaxBlenderbotPreTrainedModel,
)
else:
import sys
lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 462 | 1 |
'''simple docstring'''
from math import isqrt
def lowercase__( __UpperCamelCase: int ):
"""simple docstring"""
return all(number % divisor != 0 for divisor in range(2 ,isqrt(__UpperCamelCase ) + 1 ) )
def lowercase__( __UpperCamelCase: int = 10**6 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = 0
SCREAMING_SNAKE_CASE : List[Any] = 1
SCREAMING_SNAKE_CASE : List[Any] = 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() = }""")
| 28 |
from math import ceil
def _lowerCamelCase( lowercase__ = 1_0_0_1 ) -> int:
'''simple docstring'''
__lowercase= 1
for i in range(1 , int(ceil(n / 2.0 ) ) ):
__lowercase= 2 * i + 1
__lowercase= 2 * i
__lowercase= total + 4 * odd**2 - 6 * even
return total
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
print(solution())
else:
try:
lowerCAmelCase = int(sys.argv[1])
print(solution(n))
except ValueError:
print('''Invalid entry - please enter a number''')
| 230 | 0 |
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
enable_full_determinism()
class _a ( unittest.TestCase ):
"""simple docstring"""
def SCREAMING_SNAKE_CASE ( self ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@property
def SCREAMING_SNAKE_CASE ( self ):
_UpperCAmelCase =1
_UpperCAmelCase =3
_UpperCAmelCase =(32, 32)
_UpperCAmelCase =floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_snake_case )
return image
@property
def SCREAMING_SNAKE_CASE ( self ):
torch.manual_seed(0 )
_UpperCAmelCase =UNetaDConditionModel(
block_out_channels=(32, 32, 64) , layers_per_block=2 , sample_size=32 , in_channels=7 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , attention_head_dim=8 , use_linear_projection=_snake_case , only_cross_attention=(True, True, False) , num_class_embeds=100 , )
return model
@property
def SCREAMING_SNAKE_CASE ( self ):
torch.manual_seed(0 )
_UpperCAmelCase =AutoencoderKL(
block_out_channels=[32, 32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , )
return model
@property
def SCREAMING_SNAKE_CASE ( self ):
torch.manual_seed(0 )
_UpperCAmelCase =CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="gelu" , projection_dim=512 , )
return CLIPTextModel(_snake_case )
def SCREAMING_SNAKE_CASE ( self ):
_UpperCAmelCase ="cpu" # ensure determinism for the device-dependent torch.Generator
_UpperCAmelCase =self.dummy_cond_unet_upscale
_UpperCAmelCase =DDPMScheduler()
_UpperCAmelCase =DDIMScheduler(prediction_type="v_prediction" )
_UpperCAmelCase =self.dummy_vae
_UpperCAmelCase =self.dummy_text_encoder
_UpperCAmelCase =CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
_UpperCAmelCase =self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0]
_UpperCAmelCase =Image.fromarray(np.uinta(_snake_case ) ).convert("RGB" ).resize((64, 64) )
# make sure here that pndm scheduler skips prk
_UpperCAmelCase =StableDiffusionUpscalePipeline(
unet=_snake_case , low_res_scheduler=_snake_case , scheduler=_snake_case , vae=_snake_case , text_encoder=_snake_case , tokenizer=_snake_case , max_noise_level=350 , )
_UpperCAmelCase =sd_pipe.to(_snake_case )
sd_pipe.set_progress_bar_config(disable=_snake_case )
_UpperCAmelCase ="A painting of a squirrel eating a burger"
_UpperCAmelCase =torch.Generator(device=_snake_case ).manual_seed(0 )
_UpperCAmelCase =sd_pipe(
[prompt] , image=_snake_case , generator=_snake_case , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type="np" , )
_UpperCAmelCase =output.images
_UpperCAmelCase =torch.Generator(device=_snake_case ).manual_seed(0 )
_UpperCAmelCase =sd_pipe(
[prompt] , image=_snake_case , generator=_snake_case , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type="np" , return_dict=_snake_case , )[0]
_UpperCAmelCase =image[0, -3:, -3:, -1]
_UpperCAmelCase =image_from_tuple[0, -3:, -3:, -1]
_UpperCAmelCase =low_res_image.size[0] * 4
assert image.shape == (1, expected_height_width, expected_height_width, 3)
_UpperCAmelCase =np.array([0.3_113, 0.3_910, 0.4_272, 0.4_859, 0.5_061, 0.4_652, 0.5_362, 0.5_715, 0.5_661] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2
def SCREAMING_SNAKE_CASE ( self ):
_UpperCAmelCase ="cpu" # ensure determinism for the device-dependent torch.Generator
_UpperCAmelCase =self.dummy_cond_unet_upscale
_UpperCAmelCase =DDPMScheduler()
_UpperCAmelCase =DDIMScheduler(prediction_type="v_prediction" )
_UpperCAmelCase =self.dummy_vae
_UpperCAmelCase =self.dummy_text_encoder
_UpperCAmelCase =CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
_UpperCAmelCase =self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0]
_UpperCAmelCase =Image.fromarray(np.uinta(_snake_case ) ).convert("RGB" ).resize((64, 64) )
# make sure here that pndm scheduler skips prk
_UpperCAmelCase =StableDiffusionUpscalePipeline(
unet=_snake_case , low_res_scheduler=_snake_case , scheduler=_snake_case , vae=_snake_case , text_encoder=_snake_case , tokenizer=_snake_case , max_noise_level=350 , )
_UpperCAmelCase =sd_pipe.to(_snake_case )
sd_pipe.set_progress_bar_config(disable=_snake_case )
_UpperCAmelCase ="A painting of a squirrel eating a burger"
_UpperCAmelCase =sd_pipe(
2 * [prompt] , image=2 * [low_res_image] , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type="np" , )
_UpperCAmelCase =output.images
assert image.shape[0] == 2
_UpperCAmelCase =torch.Generator(device=_snake_case ).manual_seed(0 )
_UpperCAmelCase =sd_pipe(
[prompt] , image=_snake_case , generator=_snake_case , num_images_per_prompt=2 , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type="np" , )
_UpperCAmelCase =output.images
assert image.shape[0] == 2
@unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" )
def SCREAMING_SNAKE_CASE ( self ):
_UpperCAmelCase =self.dummy_cond_unet_upscale
_UpperCAmelCase =DDPMScheduler()
_UpperCAmelCase =DDIMScheduler(prediction_type="v_prediction" )
_UpperCAmelCase =self.dummy_vae
_UpperCAmelCase =self.dummy_text_encoder
_UpperCAmelCase =CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
_UpperCAmelCase =self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0]
_UpperCAmelCase =Image.fromarray(np.uinta(_snake_case ) ).convert("RGB" ).resize((64, 64) )
# put models in fp16, except vae as it overflows in fp16
_UpperCAmelCase =unet.half()
_UpperCAmelCase =text_encoder.half()
# make sure here that pndm scheduler skips prk
_UpperCAmelCase =StableDiffusionUpscalePipeline(
unet=_snake_case , low_res_scheduler=_snake_case , scheduler=_snake_case , vae=_snake_case , text_encoder=_snake_case , tokenizer=_snake_case , max_noise_level=350 , )
_UpperCAmelCase =sd_pipe.to(_snake_case )
sd_pipe.set_progress_bar_config(disable=_snake_case )
_UpperCAmelCase ="A painting of a squirrel eating a burger"
_UpperCAmelCase =torch.manual_seed(0 )
_UpperCAmelCase =sd_pipe(
[prompt] , image=_snake_case , generator=_snake_case , num_inference_steps=2 , output_type="np" , ).images
_UpperCAmelCase =low_res_image.size[0] * 4
assert image.shape == (1, expected_height_width, expected_height_width, 3)
@slow
@require_torch_gpu
class _a ( unittest.TestCase ):
"""simple docstring"""
def SCREAMING_SNAKE_CASE ( self ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def SCREAMING_SNAKE_CASE ( self ):
_UpperCAmelCase =load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
"/sd2-upscale/low_res_cat.png" )
_UpperCAmelCase =load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
"/upsampled_cat.npy" )
_UpperCAmelCase ="stabilityai/stable-diffusion-x4-upscaler"
_UpperCAmelCase =StableDiffusionUpscalePipeline.from_pretrained(_snake_case )
pipe.to(_snake_case )
pipe.set_progress_bar_config(disable=_snake_case )
pipe.enable_attention_slicing()
_UpperCAmelCase ="a cat sitting on a park bench"
_UpperCAmelCase =torch.manual_seed(0 )
_UpperCAmelCase =pipe(
prompt=_snake_case , image=_snake_case , generator=_snake_case , output_type="np" , )
_UpperCAmelCase =output.images[0]
assert image.shape == (512, 512, 3)
assert np.abs(expected_image - image ).max() < 1E-3
def SCREAMING_SNAKE_CASE ( self ):
_UpperCAmelCase =load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
"/sd2-upscale/low_res_cat.png" )
_UpperCAmelCase =load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
"/upsampled_cat_fp16.npy" )
_UpperCAmelCase ="stabilityai/stable-diffusion-x4-upscaler"
_UpperCAmelCase =StableDiffusionUpscalePipeline.from_pretrained(
_snake_case , torch_dtype=torch.floataa , )
pipe.to(_snake_case )
pipe.set_progress_bar_config(disable=_snake_case )
pipe.enable_attention_slicing()
_UpperCAmelCase ="a cat sitting on a park bench"
_UpperCAmelCase =torch.manual_seed(0 )
_UpperCAmelCase =pipe(
prompt=_snake_case , image=_snake_case , generator=_snake_case , output_type="np" , )
_UpperCAmelCase =output.images[0]
assert image.shape == (512, 512, 3)
assert np.abs(expected_image - image ).max() < 5E-1
def SCREAMING_SNAKE_CASE ( self ):
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated()
torch.cuda.reset_peak_memory_stats()
_UpperCAmelCase =load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
"/sd2-upscale/low_res_cat.png" )
_UpperCAmelCase ="stabilityai/stable-diffusion-x4-upscaler"
_UpperCAmelCase =StableDiffusionUpscalePipeline.from_pretrained(
_snake_case , torch_dtype=torch.floataa , )
pipe.to(_snake_case )
pipe.set_progress_bar_config(disable=_snake_case )
pipe.enable_attention_slicing(1 )
pipe.enable_sequential_cpu_offload()
_UpperCAmelCase ="a cat sitting on a park bench"
_UpperCAmelCase =torch.manual_seed(0 )
_UpperCAmelCase =pipe(
prompt=_snake_case , image=_snake_case , generator=_snake_case , num_inference_steps=5 , output_type="np" , )
_UpperCAmelCase =torch.cuda.max_memory_allocated()
# make sure that less than 2.9 GB is allocated
assert mem_bytes < 2.9 * 10**9
| 592 |
from __future__ import annotations
def lowerCamelCase__ ( _lowerCamelCase , _lowerCamelCase ) ->bool:
_UpperCAmelCase =get_failure_array(_lowerCamelCase )
# 2) Step through text searching for pattern
_UpperCAmelCase , _UpperCAmelCase =0, 0 # index into text, pattern
while i < len(_lowerCamelCase ):
if pattern[j] == text[i]:
if j == (len(_lowerCamelCase ) - 1):
return True
j += 1
# if this is a prefix in our pattern
# just go back far enough to continue
elif j > 0:
_UpperCAmelCase =failure[j - 1]
continue
i += 1
return False
def lowerCamelCase__ ( _lowerCamelCase ) ->list[int]:
_UpperCAmelCase =[0]
_UpperCAmelCase =0
_UpperCAmelCase =1
while j < len(_lowerCamelCase ):
if pattern[i] == pattern[j]:
i += 1
elif i > 0:
_UpperCAmelCase =failure[i - 1]
continue
j += 1
failure.append(_lowerCamelCase )
return failure
if __name__ == "__main__":
# Test 1)
snake_case__ : Dict = 'abc1abc12'
snake_case__ : Tuple = 'alskfjaldsabc1abc1abc12k23adsfabcabc'
snake_case__ : int = 'alskfjaldsk23adsfabcabc'
assert kmp(pattern, texta) and not kmp(pattern, texta)
# Test 2)
snake_case__ : Tuple = 'ABABX'
snake_case__ : Any = 'ABABZABABYABABX'
assert kmp(pattern, text)
# Test 3)
snake_case__ : Optional[int] = 'AAAB'
snake_case__ : Optional[Any] = 'ABAAAAAB'
assert kmp(pattern, text)
# Test 4)
snake_case__ : int = 'abcdabcy'
snake_case__ : int = 'abcxabcdabxabcdabcdabcy'
assert kmp(pattern, text)
# Test 5)
snake_case__ : str = 'aabaabaaa'
assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
| 592 | 1 |
"""simple docstring"""
class _UpperCAmelCase:
def __init__( self , __a , __a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = name
_UpperCamelCase = val
def __str__( self) -> Optional[int]:
'''simple docstring'''
return F'''{self.__class__.__name__}({self.name}, {self.val})'''
def __lt__( self , __a) -> Union[str, Any]:
'''simple docstring'''
return self.val < other.val
class _UpperCAmelCase:
def __init__( self , __a) -> str:
'''simple docstring'''
_UpperCamelCase = {}
_UpperCamelCase = {}
_UpperCamelCase = self.build_heap(__a)
def __getitem__( self , __a) -> Union[str, Any]:
'''simple docstring'''
return self.get_value(__a)
def UpperCAmelCase ( self , __a) -> Union[str, Any]:
'''simple docstring'''
return (idx - 1) // 2
def UpperCAmelCase ( self , __a) -> Any:
'''simple docstring'''
return idx * 2 + 1
def UpperCAmelCase ( self , __a) -> int:
'''simple docstring'''
return idx * 2 + 2
def UpperCAmelCase ( self , __a) -> Tuple:
'''simple docstring'''
return self.heap_dict[key]
def UpperCAmelCase ( self , __a) -> Tuple:
'''simple docstring'''
_UpperCamelCase = len(__a) - 1
_UpperCamelCase = self.get_parent_idx(__a)
for idx, i in enumerate(__a):
_UpperCamelCase = idx
_UpperCamelCase = i.val
for i in range(__a , -1 , -1):
self.sift_down(__a , __a)
return array
def UpperCAmelCase ( self , __a , __a) -> int:
'''simple docstring'''
while True:
_UpperCamelCase = self.get_left_child_idx(__a) # noqa: E741
_UpperCamelCase = self.get_right_child_idx(__a)
_UpperCamelCase = idx
if l < len(__a) and array[l] < array[idx]:
_UpperCamelCase = l
if r < len(__a) and array[r] < array[smallest]:
_UpperCamelCase = r
if smallest != idx:
_UpperCamelCase , _UpperCamelCase = array[smallest], array[idx]
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) ,
) = (
self.idx_of_element[array[smallest]],
self.idx_of_element[array[idx]],
)
_UpperCamelCase = smallest
else:
break
def UpperCAmelCase ( self , __a) -> Tuple:
'''simple docstring'''
_UpperCamelCase = self.get_parent_idx(__a)
while p >= 0 and self.heap[p] > self.heap[idx]:
_UpperCamelCase , _UpperCamelCase = self.heap[idx], self.heap[p]
_UpperCamelCase , _UpperCamelCase = (
self.idx_of_element[self.heap[idx]],
self.idx_of_element[self.heap[p]],
)
_UpperCamelCase = p
_UpperCamelCase = self.get_parent_idx(__a)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
return self.heap[0]
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.heap[-1], self.heap[0]
_UpperCamelCase , _UpperCamelCase = (
self.idx_of_element[self.heap[-1]],
self.idx_of_element[self.heap[0]],
)
_UpperCamelCase = self.heap.pop()
del self.idx_of_element[x]
self.sift_down(0 , self.heap)
return x
def UpperCAmelCase ( self , __a) -> Tuple:
'''simple docstring'''
self.heap.append(__a)
_UpperCamelCase = len(self.heap) - 1
_UpperCamelCase = node.val
self.sift_up(len(self.heap) - 1)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
return len(self.heap) == 0
def UpperCAmelCase ( self , __a , __a) -> List[Any]:
'''simple docstring'''
assert (
self.heap[self.idx_of_element[node]].val > new_value
), "newValue must be less that current value"
_UpperCamelCase = new_value
_UpperCamelCase = new_value
self.sift_up(self.idx_of_element[node])
_a = Node("""R""", -1)
_a = Node("""B""", 6)
_a = Node("""A""", 3)
_a = Node("""X""", 1)
_a = Node("""E""", 4)
# Use one of these two ways to generate Min-Heap
# Generating Min-Heap from array
_a = MinHeap([r, b, a, x, e])
# Generating Min-Heap by Insert method
# myMinHeap.insert(a)
# myMinHeap.insert(b)
# myMinHeap.insert(x)
# myMinHeap.insert(r)
# myMinHeap.insert(e)
# Before
print("""Min Heap - before decrease key""")
for i in my_min_heap.heap:
print(i)
print("""Min Heap - After decrease key of node [B -> -17]""")
my_min_heap.decrease_key(b, -17)
# After
for i in my_min_heap.heap:
print(i)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 19 |
def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :list[int] , SCREAMING_SNAKE_CASE :int ) -> int:
def count_of_possible_combinations(SCREAMING_SNAKE_CASE :int ) -> int:
if target < 0:
return 0
if target == 0:
return 1
return sum(count_of_possible_combinations(target - item ) for item in array )
return count_of_possible_combinations(SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :list[int] , SCREAMING_SNAKE_CASE :int ) -> int:
def count_of_possible_combinations_with_dp_array(
SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :list[int] ) -> int:
if target < 0:
return 0
if target == 0:
return 1
if dp_array[target] != -1:
return dp_array[target]
__lowerCAmelCase : int = sum(
count_of_possible_combinations_with_dp_array(target - item , SCREAMING_SNAKE_CASE )
for item in array )
__lowerCAmelCase : Optional[Any] = answer
return answer
__lowerCAmelCase : Optional[int] = [-1] * (target + 1)
return count_of_possible_combinations_with_dp_array(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :list[int] , SCREAMING_SNAKE_CASE :int ) -> int:
__lowerCAmelCase : Tuple = [0] * (target + 1)
__lowerCAmelCase : List[str] = 1
for i in range(1 , target + 1 ):
for j in range(SCREAMING_SNAKE_CASE ):
if i - array[j] >= 0:
dp_array[i] += dp_array[i - array[j]]
return dp_array[target]
if __name__ == "__main__":
import doctest
doctest.testmod()
_UpperCAmelCase = 3
_UpperCAmelCase = 5
_UpperCAmelCase = [1, 2, 5]
print(combination_sum_iv(n, array, target))
| 504 | 0 |
'''simple docstring'''
# Lint as: python3
import dataclasses
import re
from dataclasses import dataclass
from functools import total_ordering
from typing import Optional, Union
_lowerCAmelCase : List[str] = re.compile(R"^(?P<major>\d+)" R"\.(?P<minor>\d+)" R"\.(?P<patch>\d+)$")
@total_ordering
@dataclass
class snake_case :
"""simple docstring"""
_lowerCAmelCase = 42
_lowerCAmelCase = None
_lowerCAmelCase = None
_lowerCAmelCase = None
_lowerCAmelCase = None
def lowercase__ ( self ) -> List[str]:
"""simple docstring"""
snake_case__ ,snake_case__ ,snake_case__ : List[Any] = _str_to_version_tuple(self.version_str )
def __repr__( self ) -> Union[str, Any]:
"""simple docstring"""
return f'''{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}'''
@property
def lowercase__ ( self ) -> Tuple:
"""simple docstring"""
return self.major, self.minor, self.patch
def lowercase__ ( self , lowerCamelCase ) -> Optional[Any]:
"""simple docstring"""
if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
return Version(__SCREAMING_SNAKE_CASE )
elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
return other
raise TypeError(f'''{other} (type {type(__SCREAMING_SNAKE_CASE )}) cannot be compared to version.''' )
def __eq__( self , lowerCamelCase ) -> List[Any]:
"""simple docstring"""
try:
snake_case__ : List[str] = self._validate_operand(__SCREAMING_SNAKE_CASE )
except (TypeError, ValueError):
return False
else:
return self.tuple == other.tuple
def __lt__( self , lowerCamelCase ) -> List[str]:
"""simple docstring"""
snake_case__ : Dict = self._validate_operand(__SCREAMING_SNAKE_CASE )
return self.tuple < other.tuple
def __hash__( self ) -> Dict:
"""simple docstring"""
return hash(_version_tuple_to_str(self.tuple ) )
@classmethod
def lowercase__ ( cls , lowerCamelCase ) -> Optional[int]:
"""simple docstring"""
snake_case__ : List[str] = {f.name for f in dataclasses.fields(cls )}
return cls(**{k: v for k, v in dic.items() if k in field_names} )
def lowercase__ ( self ) -> Dict:
"""simple docstring"""
return self.version_str
def _A ( snake_case__ : Dict ):
snake_case__ : Optional[int] = _VERSION_REG.match(_UpperCAmelCase )
if not res:
raise ValueError(f'''Invalid version \'{version_str}\'. Format should be x.y.z with {{x,y,z}} being digits.''' )
return tuple(int(_UpperCAmelCase ) for v in [res.group('''major''' ), res.group('''minor''' ), res.group('''patch''' )] )
def _A ( snake_case__ : str ):
return ".".join(str(_UpperCAmelCase ) for v in version_tuple )
| 716 |
'''simple docstring'''
import argparse
import intel_extension_for_pytorch as ipex
import torch
from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline
_lowerCAmelCase : str = argparse.ArgumentParser("Stable Diffusion script with intel optimization", add_help=False)
parser.add_argument("--dpm", action="store_true", help="Enable DPMSolver or not")
parser.add_argument("--steps", default=None, type=int, help="Num inference steps")
_lowerCAmelCase : Optional[int] = parser.parse_args()
_lowerCAmelCase : Union[str, Any] = "cpu"
_lowerCAmelCase : List[str] = "a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings"
_lowerCAmelCase : Union[str, Any] = "path-to-your-trained-model"
_lowerCAmelCase : Tuple = StableDiffusionPipeline.from_pretrained(model_id)
if args.dpm:
_lowerCAmelCase : List[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
_lowerCAmelCase : Optional[Any] = pipe.to(device)
# to channels last
_lowerCAmelCase : Optional[int] = pipe.unet.to(memory_format=torch.channels_last)
_lowerCAmelCase : str = pipe.vae.to(memory_format=torch.channels_last)
_lowerCAmelCase : List[Any] = pipe.text_encoder.to(memory_format=torch.channels_last)
if pipe.requires_safety_checker:
_lowerCAmelCase : List[Any] = pipe.safety_checker.to(memory_format=torch.channels_last)
# optimize with ipex
_lowerCAmelCase : Optional[int] = torch.randn(2, 4, 6_4, 6_4)
_lowerCAmelCase : List[str] = torch.rand(1) * 9_9_9
_lowerCAmelCase : Optional[int] = torch.randn(2, 7_7, 7_6_8)
_lowerCAmelCase : List[Any] = (sample, timestep, encoder_hidden_status)
try:
_lowerCAmelCase : Union[str, Any] = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example)
except Exception:
_lowerCAmelCase : Union[str, Any] = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True)
_lowerCAmelCase : List[Any] = ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True)
_lowerCAmelCase : List[Any] = ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True)
if pipe.requires_safety_checker:
_lowerCAmelCase : List[str] = ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True)
# compute
_lowerCAmelCase : Tuple = 6_6_6
_lowerCAmelCase : str = torch.Generator(device).manual_seed(seed)
_lowerCAmelCase : Dict = {"generator": generator}
if args.steps is not None:
_lowerCAmelCase : Tuple = args.steps
with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa):
_lowerCAmelCase : Any = pipe(prompt, **generate_kwargs).images[0]
# save image
image.save("generated.png")
| 694 | 0 |
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from packaging import version
from .. import __version__
from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
from .doc import (
add_code_sample_docstrings,
add_end_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
copy_func,
replace_return_docstrings,
)
from .generic import (
ContextManagers,
ExplicitEnum,
ModelOutput,
PaddingStrategy,
TensorType,
add_model_info_to_auto_map,
cached_property,
can_return_loss,
expand_dims,
find_labels,
flatten_dict,
infer_framework,
is_jax_tensor,
is_numpy_array,
is_tensor,
is_tf_symbolic_tensor,
is_tf_tensor,
is_torch_device,
is_torch_dtype,
is_torch_tensor,
reshape,
squeeze,
strtobool,
tensor_size,
to_numpy,
to_py_obj,
transpose,
working_or_temp_dir,
)
from .hub import (
CLOUDFRONT_DISTRIB_PREFIX,
DISABLE_TELEMETRY,
HF_MODULES_CACHE,
HUGGINGFACE_CO_PREFIX,
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
PYTORCH_PRETRAINED_BERT_CACHE,
PYTORCH_TRANSFORMERS_CACHE,
S3_BUCKET_PREFIX,
TRANSFORMERS_CACHE,
TRANSFORMERS_DYNAMIC_MODULE_NAME,
EntryNotFoundError,
PushToHubMixin,
RepositoryNotFoundError,
RevisionNotFoundError,
cached_file,
default_cache_path,
define_sagemaker_information,
download_url,
extract_commit_hash,
get_cached_models,
get_file_from_repo,
get_full_repo_name,
has_file,
http_user_agent,
is_offline_mode,
is_remote_url,
move_cache,
send_example_telemetry,
try_to_load_from_cache,
)
from .import_utils import (
ENV_VARS_TRUE_AND_AUTO_VALUES,
ENV_VARS_TRUE_VALUES,
TORCH_FX_REQUIRED_VERSION,
USE_JAX,
USE_TF,
USE_TORCH,
DummyObject,
OptionalDependencyNotAvailable,
_LazyModule,
ccl_version,
direct_transformers_import,
get_torch_version,
is_accelerate_available,
is_apex_available,
is_bitsandbytes_available,
is_bsa_available,
is_coloredlogs_available,
is_cython_available,
is_datasets_available,
is_decord_available,
is_detectrona_available,
is_faiss_available,
is_flax_available,
is_ftfy_available,
is_in_notebook,
is_ipex_available,
is_jieba_available,
is_jumanpp_available,
is_kenlm_available,
is_keras_nlp_available,
is_librosa_available,
is_natten_available,
is_ninja_available,
is_onnx_available,
is_openai_available,
is_optimum_available,
is_pandas_available,
is_peft_available,
is_phonemizer_available,
is_protobuf_available,
is_psutil_available,
is_pyanvml_available,
is_pyctcdecode_available,
is_pytesseract_available,
is_pytest_available,
is_pytorch_quantization_available,
is_rjieba_available,
is_sacremoses_available,
is_safetensors_available,
is_sagemaker_dp_enabled,
is_sagemaker_mp_enabled,
is_scipy_available,
is_sentencepiece_available,
is_seqio_available,
is_sklearn_available,
is_soundfile_availble,
is_spacy_available,
is_speech_available,
is_sudachi_available,
is_tensorflow_probability_available,
is_tensorflow_text_available,
is_tfaonnx_available,
is_tf_available,
is_timm_available,
is_tokenizers_available,
is_torch_available,
is_torch_bfaa_available,
is_torch_bfaa_cpu_available,
is_torch_bfaa_gpu_available,
is_torch_compile_available,
is_torch_cuda_available,
is_torch_fx_available,
is_torch_fx_proxy,
is_torch_mps_available,
is_torch_neuroncore_available,
is_torch_tensorrt_fx_available,
is_torch_tfaa_available,
is_torch_tpu_available,
is_torchaudio_available,
is_torchdistx_available,
is_torchdynamo_available,
is_torchvision_available,
is_training_run_on_sagemaker,
is_vision_available,
requires_backends,
torch_only_method,
)
snake_case__ : int = '''pytorch_model.bin'''
snake_case__ : List[str] = '''pytorch_model.bin.index.json'''
snake_case__ : int = '''adapter_config.json'''
snake_case__ : List[Any] = '''adapter_model.bin'''
snake_case__ : Union[str, Any] = '''adapter_model.safetensors'''
snake_case__ : Tuple = '''tf_model.h5'''
snake_case__ : str = '''tf_model.h5.index.json'''
snake_case__ : Any = '''model.ckpt'''
snake_case__ : str = '''flax_model.msgpack'''
snake_case__ : str = '''flax_model.msgpack.index.json'''
snake_case__ : Tuple = '''model.safetensors'''
snake_case__ : List[Any] = '''model.safetensors.index.json'''
snake_case__ : Optional[Any] = '''config.json'''
snake_case__ : Union[str, Any] = '''preprocessor_config.json'''
snake_case__ : Union[str, Any] = FEATURE_EXTRACTOR_NAME
snake_case__ : Dict = '''generation_config.json'''
snake_case__ : Tuple = '''modelcard.json'''
snake_case__ : List[Any] = '''▁'''
snake_case__ : Union[str, Any] = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility
snake_case__ : Union[str, Any] = [
[[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too.
snake_case__ : Optional[Any] = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
snake_case__ : Dict = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]
def lowercase ( _lowerCAmelCase ):
if version.parse(_lowercase ) < version.parse(_lowercase ):
if "dev" in min_version:
UpperCAmelCase__ = (
"This example requires a source install from HuggingFace Transformers (see "
"`https://huggingface.co/docs/transformers/installation#install-from-source`),"
)
else:
UpperCAmelCase__ = F'''This example requires a minimum version of {min_version},'''
error_message += F''' but the version found is {__version__}.\n'''
raise ImportError(
error_message
+ """Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other """
"""versions of HuggingFace Transformers.""" )
| 392 |
class _a :
'''simple docstring'''
def __init__( self , __UpperCAmelCase ):
__A : Optional[Any] = n
__A : Optional[int] = [None] * self.n
__A : Optional[int] = 0 # index of the first element
__A : Any = 0
__A : Any = 0
def __len__( self ):
return self.size
def __UpperCAmelCase( self ):
return self.size == 0
def __UpperCAmelCase( self ):
return False if self.is_empty() else self.array[self.front]
def __UpperCAmelCase( self , __UpperCAmelCase ):
if self.size >= self.n:
raise Exception("QUEUE IS FULL" )
__A : Tuple = data
__A : List[Any] = (self.rear + 1) % self.n
self.size += 1
return self
def __UpperCAmelCase( self ):
if self.size == 0:
raise Exception("UNDERFLOW" )
__A : List[Any] = self.array[self.front]
__A : str = None
__A : Optional[Any] = (self.front + 1) % self.n
self.size -= 1
return temp
| 520 | 0 |
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
_lowerCamelCase = random.Random()
def lowerCamelCase ( UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any]=1.0 , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : str=None )-> List[str]:
"""simple docstring"""
if rng is None:
a =global_rng
a =[]
for batch_idx in range(shape[0] ):
values.append([] )
for _ in range(shape[1] ):
values[-1].append(rng.random() * scale )
return values
@require_torch
@require_torchaudio
class UpperCAmelCase__ ( unittest.TestCase ):
'''simple docstring'''
def __init__( self , _lowerCAmelCase , _lowerCAmelCase=7 , _lowerCAmelCase=400 , _lowerCAmelCase=2_000 , _lowerCAmelCase=10 , _lowerCAmelCase=160 , _lowerCAmelCase=8 , _lowerCAmelCase=0.0 , _lowerCAmelCase=4_000 , _lowerCAmelCase=False , _lowerCAmelCase=True , ):
a =parent
a =batch_size
a =min_seq_length
a =max_seq_length
a =(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
a =padding_value
a =sampling_rate
a =return_attention_mask
a =do_normalize
a =feature_size
a =chunk_length
a =hop_length
def lowerCAmelCase__ ( 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 lowerCAmelCase__ ( self , _lowerCAmelCase=False , _lowerCAmelCase=False ):
def _flatten(_lowerCAmelCase ):
return list(itertools.chain(*__a ) )
if equal_length:
a =[floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )]
else:
# make sure that inputs increase in size
a =[
floats_list((x, self.feature_size) )
for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff )
]
if numpify:
a =[np.asarray(__a ) for x in speech_inputs]
return speech_inputs
@require_torch
@require_torchaudio
class UpperCAmelCase__ ( __lowercase , unittest.TestCase ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE : List[str] = WhisperFeatureExtractor if is_speech_available() else None
def lowerCAmelCase__ ( self ):
a =WhisperFeatureExtractionTester(self )
def lowerCAmelCase__ ( self ):
a =self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
a =feat_extract_first.save_pretrained(__a )[0]
check_json_file_has_correct_format(__a )
a =self.feature_extraction_class.from_pretrained(__a )
a =feat_extract_first.to_dict()
a =feat_extract_second.to_dict()
a =feat_extract_first.mel_filters
a =feat_extract_second.mel_filters
self.assertTrue(np.allclose(__a , __a ) )
self.assertEqual(__a , __a )
def lowerCAmelCase__ ( self ):
a =self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
a =os.path.join(__a , """feat_extract.json""" )
feat_extract_first.to_json_file(__a )
a =self.feature_extraction_class.from_json_file(__a )
a =feat_extract_first.to_dict()
a =feat_extract_second.to_dict()
a =feat_extract_first.mel_filters
a =feat_extract_second.mel_filters
self.assertTrue(np.allclose(__a , __a ) )
self.assertEqual(__a , __a )
def lowerCAmelCase__ ( self ):
# Tests that all call wrap to encode_plus and batch_encode_plus
a =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
# create three inputs of length 800, 1000, and 1200
a =[floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )]
a =[np.asarray(__a ) for speech_input in speech_inputs]
# Test feature size
a =feature_extractor(__a , 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
a =feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features
a =feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features
self.assertTrue(np.allclose(__a , __a , atol=1E-3 ) )
# Test batched
a =feature_extractor(__a , return_tensors="""np""" ).input_features
a =feature_extractor(__a , return_tensors="""np""" ).input_features
for enc_seq_a, enc_seq_a in zip(__a , __a ):
self.assertTrue(np.allclose(__a , __a , atol=1E-3 ) )
# Test 2-D numpy arrays are batched.
a =[floats_list((1, x) )[0] for x in (800, 800, 800)]
a =np.asarray(__a )
a =feature_extractor(__a , return_tensors="""np""" ).input_features
a =feature_extractor(__a , return_tensors="""np""" ).input_features
for enc_seq_a, enc_seq_a in zip(__a , __a ):
self.assertTrue(np.allclose(__a , __a , atol=1E-3 ) )
# Test truncation required
a =[floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )]
a =[np.asarray(__a ) for speech_input in speech_inputs]
a =[x[: feature_extractor.n_samples] for x in speech_inputs]
a =[np.asarray(__a ) for speech_input in speech_inputs_truncated]
a =feature_extractor(__a , return_tensors="""np""" ).input_features
a =feature_extractor(__a , return_tensors="""np""" ).input_features
for enc_seq_a, enc_seq_a in zip(__a , __a ):
self.assertTrue(np.allclose(__a , __a , atol=1E-3 ) )
def lowerCAmelCase__ ( self ):
import torch
a =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
a =np.random.rand(100 , 32 ).astype(np.floataa )
a =np_speech_inputs.tolist()
for inputs in [py_speech_inputs, np_speech_inputs]:
a =feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" )
self.assertTrue(np_processed.input_features.dtype == np.floataa )
a =feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" )
self.assertTrue(pt_processed.input_features.dtype == torch.floataa )
def lowerCAmelCase__ ( self , _lowerCAmelCase ):
a =load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" )
# automatic decoding with librispeech
a =ds.sort("""id""" ).select(range(__a ) )[:num_samples]["""audio"""]
return [x["array"] for x in speech_samples]
def lowerCAmelCase__ ( self ):
# fmt: off
a =torch.tensor(
[
0.11_93, -0.09_46, -0.10_98, -0.01_96, 0.02_25, -0.06_90, -0.17_36, 0.09_51,
0.09_71, -0.08_17, -0.07_02, 0.01_62, 0.02_60, 0.00_17, -0.01_92, -0.16_78,
0.07_09, -0.18_67, -0.06_55, -0.02_74, -0.02_34, -0.18_84, -0.05_16, -0.05_54,
-0.02_74, -0.14_25, -0.14_23, 0.08_37, 0.03_77, -0.08_54
] )
# fmt: on
a =self._load_datasamples(1 )
a =WhisperFeatureExtractor()
a =feature_extractor(__a , return_tensors="""pt""" ).input_features
self.assertEqual(input_features.shape , (1, 80, 3_000) )
self.assertTrue(torch.allclose(input_features[0, 0, :30] , __a , atol=1E-4 ) )
def lowerCAmelCase__ ( self ):
a =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
a =self._load_datasamples(1 )[0]
a =((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue
a =feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__a )[0]
self.assertTrue(np.all(np.mean(__a ) < 1E-3 ) )
self.assertTrue(np.all(np.abs(np.var(__a ) - 1 ) < 1E-3 ) )
| 720 |
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {'''vocab_file''': '''sentencepiece.bpe.model'''}
_lowerCamelCase = {
'''vocab_file''': {
'''moussaKam/mbarthez''': '''https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model''',
'''moussaKam/barthez''': '''https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model''',
'''moussaKam/barthez-orangesum-title''': (
'''https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model'''
),
},
}
_lowerCamelCase = {
'''moussaKam/mbarthez''': 1024,
'''moussaKam/barthez''': 1024,
'''moussaKam/barthez-orangesum-title''': 1024,
}
_lowerCamelCase = '''▁'''
class UpperCAmelCase__ ( UpperCAmelCase__ ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE : str = VOCAB_FILES_NAMES
_SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP
_SCREAMING_SNAKE_CASE : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_SCREAMING_SNAKE_CASE : Tuple = ["input_ids", "attention_mask"]
def __init__( self , _lowerCAmelCase , _lowerCAmelCase="<s>" , _lowerCAmelCase="</s>" , _lowerCAmelCase="</s>" , _lowerCAmelCase="<s>" , _lowerCAmelCase="<unk>" , _lowerCAmelCase="<pad>" , _lowerCAmelCase="<mask>" , _lowerCAmelCase = None , **_lowerCAmelCase , ):
# Mask token behave like a normal word, i.e. include the space before it
a =AddedToken(_lowerCAmelCase , lstrip=_lowerCAmelCase , rstrip=_lowerCAmelCase ) if isinstance(_lowerCAmelCase , _lowerCAmelCase ) else mask_token
a ={} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=_lowerCAmelCase , eos_token=_lowerCAmelCase , unk_token=_lowerCAmelCase , sep_token=_lowerCAmelCase , cls_token=_lowerCAmelCase , pad_token=_lowerCAmelCase , mask_token=_lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCAmelCase , )
a =vocab_file
a =spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(_lowerCAmelCase ) )
a ={"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3}
a =len(self.sp_model ) - 1
a ={v: k for k, v in self.fairseq_tokens_to_ids.items()}
def lowerCAmelCase__ ( self , _lowerCAmelCase , _lowerCAmelCase = None ):
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
a =[self.cls_token_id]
a =[self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def lowerCAmelCase__ ( self , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = False ):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_lowerCAmelCase , token_ids_a=_lowerCAmelCase , already_has_special_tokens=_lowerCAmelCase )
if token_ids_a is None:
return [1] + ([0] * len(_lowerCAmelCase )) + [1]
return [1] + ([0] * len(_lowerCAmelCase )) + [1, 1] + ([0] * len(_lowerCAmelCase )) + [1]
def lowerCAmelCase__ ( self , _lowerCAmelCase , _lowerCAmelCase = None ):
a =[self.sep_token_id]
a =[self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
@property
def lowerCAmelCase__ ( self ):
return len(self.sp_model )
def lowerCAmelCase__ ( self ):
a ={self.convert_ids_to_tokens(_lowerCAmelCase ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def lowerCAmelCase__ ( self , _lowerCAmelCase ):
return self.sp_model.encode(_lowerCAmelCase , out_type=_lowerCAmelCase )
def lowerCAmelCase__ ( self , _lowerCAmelCase ):
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
a =self.sp_model.PieceToId(_lowerCAmelCase )
return spm_id if spm_id else self.unk_token_id
def lowerCAmelCase__ ( self , _lowerCAmelCase ):
if index in self.fairseq_ids_to_tokens:
return self.fairseq_ids_to_tokens[index]
return self.sp_model.IdToPiece(_lowerCAmelCase )
def lowerCAmelCase__ ( self , _lowerCAmelCase ):
a =[]
a =""""""
a =False
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
if not prev_is_special:
out_string += " "
out_string += self.sp_model.decode(_lowerCAmelCase ) + token
a =True
a =[]
else:
current_sub_tokens.append(_lowerCAmelCase )
a =False
out_string += self.sp_model.decode(_lowerCAmelCase )
return out_string.strip()
def __getstate__( self ):
a =self.__dict__.copy()
a =None
return state
def __setstate__( self , _lowerCAmelCase ):
a =d
# for backward compatibility
if not hasattr(self , """sp_model_kwargs""" ):
a ={}
a =spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def lowerCAmelCase__ ( self , _lowerCAmelCase , _lowerCAmelCase = None ):
if not os.path.isdir(_lowerCAmelCase ):
logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' )
return
a =os.path.join(
_lowerCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCAmelCase ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , _lowerCAmelCase )
elif not os.path.isfile(self.vocab_file ):
with open(_lowerCAmelCase , """wb""" ) as fi:
a =self.sp_model.serialized_model_proto()
fi.write(_lowerCAmelCase )
return (out_vocab_file,)
| 321 | 0 |
"""simple docstring"""
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_funnel import FunnelTokenizer
A = logging.get_logger(__name__)
A = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'}
A = [
'small',
'small-base',
'medium',
'medium-base',
'intermediate',
'intermediate-base',
'large',
'large-base',
'xlarge',
'xlarge-base',
]
A = {
'vocab_file': {
'funnel-transformer/small': 'https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt',
'funnel-transformer/small-base': 'https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt',
'funnel-transformer/medium': 'https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt',
'funnel-transformer/medium-base': (
'https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt'
),
'funnel-transformer/intermediate': (
'https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt'
),
'funnel-transformer/intermediate-base': (
'https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt'
),
'funnel-transformer/large': 'https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt',
'funnel-transformer/large-base': 'https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt',
'funnel-transformer/xlarge': 'https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt',
'funnel-transformer/xlarge-base': (
'https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt'
),
},
'tokenizer_file': {
'funnel-transformer/small': 'https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json',
'funnel-transformer/small-base': (
'https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json'
),
'funnel-transformer/medium': 'https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json',
'funnel-transformer/medium-base': (
'https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json'
),
'funnel-transformer/intermediate': (
'https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json'
),
'funnel-transformer/intermediate-base': (
'https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json'
),
'funnel-transformer/large': 'https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json',
'funnel-transformer/large-base': (
'https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json'
),
'funnel-transformer/xlarge': 'https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json',
'funnel-transformer/xlarge-base': (
'https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json'
),
},
}
A = {F'''funnel-transformer/{name}''': 5_1_2 for name in _model_names}
A = {F'''funnel-transformer/{name}''': {'do_lower_case': True} for name in _model_names}
class _a ( SCREAMING_SNAKE_CASE__):
__magic_name__ = VOCAB_FILES_NAMES
__magic_name__ = PRETRAINED_VOCAB_FILES_MAP
__magic_name__ = PRETRAINED_INIT_CONFIGURATION
__magic_name__ = FunnelTokenizer
__magic_name__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__magic_name__ = 2
def __init__( self : List[Any] , _lowercase : str=None , _lowercase : Any=None , _lowercase : int=True , _lowercase : Optional[int]="<unk>" , _lowercase : Any="<sep>" , _lowercase : Optional[int]="<pad>" , _lowercase : Optional[Any]="<cls>" , _lowercase : List[str]="<mask>" , _lowercase : Dict="<s>" , _lowercase : Any="</s>" , _lowercase : str=True , _lowercase : Dict=True , _lowercase : Optional[int]=None , _lowercase : Dict="##" , **_lowercase : Tuple , ) -> List[Any]:
super().__init__(
__SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , do_lower_case=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , clean_text=__SCREAMING_SNAKE_CASE , tokenize_chinese_chars=__SCREAMING_SNAKE_CASE , strip_accents=__SCREAMING_SNAKE_CASE , wordpieces_prefix=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , )
snake_case : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get("lowercase" , __SCREAMING_SNAKE_CASE ) != do_lower_case
or normalizer_state.get("strip_accents" , __SCREAMING_SNAKE_CASE ) != strip_accents
or normalizer_state.get("handle_chinese_chars" , __SCREAMING_SNAKE_CASE ) != tokenize_chinese_chars
):
snake_case : List[Any] = getattr(__SCREAMING_SNAKE_CASE , normalizer_state.pop("type" ) )
snake_case : int = do_lower_case
snake_case : int = strip_accents
snake_case : Optional[int] = tokenize_chinese_chars
snake_case : Optional[Any] = normalizer_class(**__SCREAMING_SNAKE_CASE )
snake_case : int = do_lower_case
def __lowercase ( self : str , _lowercase : List[Any] , _lowercase : Union[str, Any]=None ) -> Any:
snake_case : 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 : str , _lowercase : List[int] , _lowercase : Optional[List[int]] = None ) -> List[int]:
snake_case : Any = [self.sep_token_id]
snake_case : Optional[int] = [self.cls_token_id]
if token_ids_a is None:
return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0]
return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def __lowercase ( self : Any , _lowercase : str , _lowercase : Optional[str] = None ) -> Tuple[str]:
snake_case : Optional[Any] = self._tokenizer.model.save(__SCREAMING_SNAKE_CASE , name=__SCREAMING_SNAKE_CASE )
return tuple(__SCREAMING_SNAKE_CASE )
| 449 |
from itertools import permutations
def lowercase__ ( A_: tuple ) -> bool:
"""simple docstring"""
if num[3] % 2 != 0:
return False
if (num[2] + num[3] + num[4]) % 3 != 0:
return False
if num[5] % 5 != 0:
return False
__UpperCAmelCase =[7, 11, 13, 17]
for i, test in enumerate(A_ ):
if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0:
return False
return True
def lowercase__ ( A_: int = 10 ) -> int:
"""simple docstring"""
return sum(
int("""""".join(map(A_ , A_ ) ) )
for num in permutations(range(A_ ) )
if is_substring_divisible(A_ ) )
if __name__ == "__main__":
print(F"""{solution() = }""")
| 68 | 0 |
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
snake_case__ : Dict = logging.get_logger(__name__)
def __lowerCamelCase ( A__ : Optional[Any] , A__ : List[str] , A__ : Union[str, Any] , A__ : Optional[Any] ) -> Tuple[int, int]:
def constraint_to_multiple_of(A__ : int , A__ : Optional[Any] , A__ : List[str]=0 , A__ : Optional[int]=None ):
lowerCamelCase_ : str = round(val / multiple ) * multiple
if max_val is not None and x > max_val:
lowerCamelCase_ : int = math.floor(val / multiple ) * multiple
if x < min_val:
lowerCamelCase_ : Any = math.ceil(val / multiple ) * multiple
return x
lowerCamelCase_ : Optional[int] = (output_size, output_size) if isinstance(a__ , a__ ) else output_size
lowerCamelCase_, lowerCamelCase_ : Optional[Any] = get_image_size(a__ )
lowerCamelCase_, lowerCamelCase_ : Union[str, Any] = output_size
# determine new height and width
lowerCamelCase_ : List[str] = output_height / input_height
lowerCamelCase_ : List[str] = output_width / input_width
if keep_aspect_ratio:
# scale as little as possible
if abs(1 - scale_width ) < abs(1 - scale_height ):
# fit width
lowerCamelCase_ : int = scale_width
else:
# fit height
lowerCamelCase_ : Any = scale_height
lowerCamelCase_ : Optional[int] = constraint_to_multiple_of(scale_height * input_height , multiple=a__ )
lowerCamelCase_ : Optional[Any] = constraint_to_multiple_of(scale_width * input_width , multiple=a__ )
return (new_height, new_width)
class SCREAMING_SNAKE_CASE_ (a__ ):
'''simple docstring'''
_a = ["pixel_values"]
def __init__( self : int , __a : bool = True , __a : Dict[str, int] = None , __a : PILImageResampling = PILImageResampling.BILINEAR , __a : bool = False , __a : int = 1 , __a : bool = True , __a : Union[int, float] = 1 / 255 , __a : bool = True , __a : Optional[Union[float, List[float]]] = None , __a : Optional[Union[float, List[float]]] = None , **__a : Optional[Any] , ) ->None:
super().__init__(**lowercase_ )
lowerCamelCase_ : Optional[Any] = size if size is not None else {"""height""": 384, """width""": 384}
lowerCamelCase_ : Tuple = get_size_dict(lowercase_ )
lowerCamelCase_ : Any = do_resize
lowerCamelCase_ : Union[str, Any] = size
lowerCamelCase_ : List[str] = keep_aspect_ratio
lowerCamelCase_ : int = ensure_multiple_of
lowerCamelCase_ : Optional[int] = resample
lowerCamelCase_ : Optional[Any] = do_rescale
lowerCamelCase_ : Tuple = rescale_factor
lowerCamelCase_ : Tuple = do_normalize
lowerCamelCase_ : Any = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
lowerCamelCase_ : List[Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD
def _lowerCAmelCase ( self : str , __a : np.ndarray , __a : Dict[str, int] , __a : bool = False , __a : int = 1 , __a : PILImageResampling = PILImageResampling.BICUBIC , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Optional[int] , ) ->np.ndarray:
lowerCamelCase_ : List[Any] = get_size_dict(lowercase_ )
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()}''' )
lowerCamelCase_ : int = get_resize_output_image_size(
lowercase_ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=lowercase_ , multiple=lowercase_ , )
return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_ )
def _lowerCAmelCase ( self : int , __a : np.ndarray , __a : Union[int, float] , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Optional[Any] , ) ->Union[str, Any]:
return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_ )
def _lowerCAmelCase ( self : Optional[int] , __a : np.ndarray , __a : Union[float, List[float]] , __a : Union[float, List[float]] , __a : Optional[Union[str, ChannelDimension]] = None , **__a : List[Any] , ) ->np.ndarray:
return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_ )
def _lowerCAmelCase ( self : Optional[int] , __a : ImageInput , __a : bool = None , __a : int = None , __a : bool = None , __a : int = None , __a : PILImageResampling = None , __a : bool = None , __a : float = None , __a : bool = None , __a : Optional[Union[float, List[float]]] = None , __a : Optional[Union[float, List[float]]] = None , __a : Optional[Union[str, TensorType]] = None , __a : ChannelDimension = ChannelDimension.FIRST , **__a : Optional[Any] , ) ->PIL.Image.Image:
lowerCamelCase_ : Dict = do_resize if do_resize is not None else self.do_resize
lowerCamelCase_ : Optional[Any] = size if size is not None else self.size
lowerCamelCase_ : Any = get_size_dict(lowercase_ )
lowerCamelCase_ : Dict = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
lowerCamelCase_ : Union[str, Any] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
lowerCamelCase_ : Optional[Any] = resample if resample is not None else self.resample
lowerCamelCase_ : str = do_rescale if do_rescale is not None else self.do_rescale
lowerCamelCase_ : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor
lowerCamelCase_ : int = do_normalize if do_normalize is not None else self.do_normalize
lowerCamelCase_ : Any = image_mean if image_mean is not None else self.image_mean
lowerCamelCase_ : Optional[Any] = image_std if image_std is not None else self.image_std
lowerCamelCase_ : Optional[Any] = make_list_of_images(lowercase_ )
if not valid_images(lowercase_ ):
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.
lowerCamelCase_ : Dict = [to_numpy_array(lowercase_ ) for image in images]
if do_resize:
lowerCamelCase_ : Dict = [self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_ ) for image in images]
if do_rescale:
lowerCamelCase_ : Dict = [self.rescale(image=lowercase_ , scale=lowercase_ ) for image in images]
if do_normalize:
lowerCamelCase_ : Any = [self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_ ) for image in images]
lowerCamelCase_ : Union[str, Any] = [to_channel_dimension_format(lowercase_ , lowercase_ ) for image in images]
lowerCamelCase_ : List[str] = {"""pixel_values""": images}
return BatchFeature(data=lowercase_ , tensor_type=lowercase_ )
def _lowerCAmelCase ( self : str , __a : int , __a : List[Tuple] = None ) ->Optional[Any]:
lowerCamelCase_ : Dict = outputs.logits
# Resize logits and compute semantic segmentation maps
if target_sizes is not None:
if len(lowercase_ ) != len(lowercase_ ):
raise ValueError(
"""Make sure that you pass in as many target sizes as the batch dimension of the logits""" )
if is_torch_tensor(lowercase_ ):
lowerCamelCase_ : Union[str, Any] = target_sizes.numpy()
lowerCamelCase_ : Dict = []
for idx in range(len(lowercase_ ) ):
lowerCamelCase_ : Any = torch.nn.functional.interpolate(
logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=lowercase_ )
lowerCamelCase_ : List[Any] = resized_logits[0].argmax(dim=0 )
semantic_segmentation.append(lowercase_ )
else:
lowerCamelCase_ : Optional[int] = logits.argmax(dim=1 )
lowerCamelCase_ : Optional[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )]
return semantic_segmentation
| 716 |
import qiskit
def __lowerCamelCase ( A__ : int = 2 ) -> qiskit.result.counts.Counts:
lowerCamelCase_ : List[Any] = qubits
# Using Aer's simulator
lowerCamelCase_ : Tuple = qiskit.Aer.get_backend("""aer_simulator""" )
# Creating a Quantum Circuit acting on the q register
lowerCamelCase_ : int = qiskit.QuantumCircuit(A__ , A__ )
# Adding a H gate on qubit 0 (now q0 in superposition)
circuit.h(0 )
for i in range(1 , A__ ):
# Adding CX (CNOT) gate
circuit.cx(i - 1 , A__ )
# Mapping the quantum measurement to the classical bits
circuit.measure(list(range(A__ ) ) , list(range(A__ ) ) )
# Now measuring any one qubit would affect other qubits to collapse
# their super position and have same state as the measured one.
# Executing the circuit on the simulator
lowerCamelCase_ : Union[str, Any] = qiskit.execute(A__ , A__ , shots=1000 )
return job.result().get_counts(A__ )
if __name__ == "__main__":
print(F'Total count for various states are: {quantum_entanglement(3)}')
| 171 | 0 |
def A ( lowercase__ : int , lowercase__ : int ) -> int:
return int(input_a == input_a == 0 )
def A ( ) -> None:
print("""Truth Table of NOR Gate:""" )
print("""| Input 1 | Input 2 | Output |""" )
print(f"""| 0 | 0 | {nor_gate(0 , 0 )} |""" )
print(f"""| 0 | 1 | {nor_gate(0 , 1 )} |""" )
print(f"""| 1 | 0 | {nor_gate(1 , 0 )} |""" )
print(f"""| 1 | 1 | {nor_gate(1 , 1 )} |""" )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 45 |
import warnings
from ...utils import logging
from .image_processing_mobilevit import MobileViTImageProcessor
UpperCamelCase = logging.get_logger(__name__)
class lowerCAmelCase_ ( lowercase ):
"""simple docstring"""
def __init__( self :Union[str, Any] , *lowerCamelCase__ :Optional[int] , **lowerCamelCase__ :Dict ):
warnings.warn(
"""The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers."""
""" Please use MobileViTImageProcessor instead.""" , lowerCamelCase__ , )
super().__init__(*lowerCamelCase__ , **lowerCamelCase__ )
| 45 | 1 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor
from .base import PipelineTool
class _a ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
A = 'openai/whisper-base'
A = (
'This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the '
'transcribed text.'
)
A = 'transcriber'
A = WhisperProcessor
A = WhisperForConditionalGeneration
A = ['audio']
A = ['text']
def __a ( self ,__SCREAMING_SNAKE_CASE ):
return self.pre_processor(__SCREAMING_SNAKE_CASE ,return_tensors='pt' ).input_features
def __a ( self ,__SCREAMING_SNAKE_CASE ):
return self.model.generate(inputs=__SCREAMING_SNAKE_CASE )
def __a ( self ,__SCREAMING_SNAKE_CASE ):
return self.pre_processor.batch_decode(__SCREAMING_SNAKE_CASE ,skip_special_tokens=__SCREAMING_SNAKE_CASE )[0]
| 220 |
'''simple docstring'''
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from diffusers import (
DDIMScheduler,
KandinskyVaaImgaImgPipeline,
KandinskyVaaPriorPipeline,
UNetaDConditionModel,
VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
enable_full_determinism()
class _a ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
"""simple docstring"""
A = KandinskyVaaImgaImgPipeline
A = ['image_embeds', 'negative_image_embeds', 'image']
A = [
'image_embeds',
'negative_image_embeds',
'image',
]
A = [
'generator',
'height',
'width',
'strength',
'guidance_scale',
'num_inference_steps',
'return_dict',
'guidance_scale',
'num_images_per_prompt',
'output_type',
'return_dict',
]
A = False
@property
def __a ( self ):
return 32
@property
def __a ( self ):
return 32
@property
def __a ( self ):
return self.time_input_dim
@property
def __a ( self ):
return self.time_input_dim * 4
@property
def __a ( self ):
return 100
@property
def __a ( self ):
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE : Optional[Any] = {
'in_channels': 4,
# Out channels is double in channels because predicts mean and variance
'out_channels': 8,
'addition_embed_type': 'image',
'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'),
'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'),
'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn',
'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2),
'layers_per_block': 1,
'encoder_hid_dim': self.text_embedder_hidden_size,
'encoder_hid_dim_type': 'image_proj',
'cross_attention_dim': self.cross_attention_dim,
'attention_head_dim': 4,
'resnet_time_scale_shift': 'scale_shift',
'class_embed_type': None,
}
SCREAMING_SNAKE_CASE : Tuple = UNetaDConditionModel(**__SCREAMING_SNAKE_CASE )
return model
@property
def __a ( self ):
return {
"block_out_channels": [32, 64],
"down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
"in_channels": 3,
"latent_channels": 4,
"layers_per_block": 1,
"norm_num_groups": 8,
"norm_type": "spatial",
"num_vq_embeddings": 12,
"out_channels": 3,
"up_block_types": [
"AttnUpDecoderBlock2D",
"UpDecoderBlock2D",
],
"vq_embed_dim": 4,
}
@property
def __a ( self ):
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE : Tuple = VQModel(**self.dummy_movq_kwargs )
return model
def __a ( self ):
SCREAMING_SNAKE_CASE : List[Any] = self.dummy_unet
SCREAMING_SNAKE_CASE : List[str] = self.dummy_movq
SCREAMING_SNAKE_CASE : int = {
'num_train_timesteps': 1000,
'beta_schedule': 'linear',
'beta_start': 0.0_0085,
'beta_end': 0.012,
'clip_sample': False,
'set_alpha_to_one': False,
'steps_offset': 0,
'prediction_type': 'epsilon',
'thresholding': False,
}
SCREAMING_SNAKE_CASE : int = DDIMScheduler(**__SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE : str = {
'unet': unet,
'scheduler': scheduler,
'movq': movq,
}
return components
def __a ( self ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE=0 ):
SCREAMING_SNAKE_CASE : int = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE : str = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(seed + 1 ) ).to(
__SCREAMING_SNAKE_CASE )
# create init_image
SCREAMING_SNAKE_CASE : Any = floats_tensor((1, 3, 64, 64) ,rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE : Any = image.cpu().permute(0 ,2 ,3 ,1 )[0]
SCREAMING_SNAKE_CASE : Optional[int] = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert('RGB' ).resize((256, 256) )
if str(__SCREAMING_SNAKE_CASE ).startswith('mps' ):
SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(__SCREAMING_SNAKE_CASE )
else:
SCREAMING_SNAKE_CASE : int = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE : str = {
'image': init_image,
'image_embeds': image_embeds,
'negative_image_embeds': negative_image_embeds,
'generator': generator,
'height': 64,
'width': 64,
'num_inference_steps': 10,
'guidance_scale': 7.0,
'strength': 0.2,
'output_type': 'np',
}
return inputs
def __a ( self ):
SCREAMING_SNAKE_CASE : Optional[Any] = 'cpu'
SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_components()
SCREAMING_SNAKE_CASE : Tuple = self.pipeline_class(**__SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE : Any = pipe.to(__SCREAMING_SNAKE_CASE )
pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE : Any = pipe(**self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE : Union[str, Any] = output.images
SCREAMING_SNAKE_CASE : Tuple = pipe(
**self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) ,return_dict=__SCREAMING_SNAKE_CASE ,)[0]
SCREAMING_SNAKE_CASE : List[Any] = image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE : str = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
SCREAMING_SNAKE_CASE : Any = np.array(
[0.619_9778, 0.6398_4406, 0.4614_5785, 0.6294_4984, 0.562_2215, 0.4730_6132, 0.4744_1456, 0.460_7606, 0.4871_9263] )
assert (
np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
), f""" expected_slice {expected_slice}, but got {image_slice.flatten()}"""
assert (
np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
), f""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"""
@slow
@require_torch_gpu
class _a ( unittest.TestCase ):
"""simple docstring"""
def __a ( self ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __a ( self ):
SCREAMING_SNAKE_CASE : Any = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/kandinskyv22/kandinskyv22_img2img_frog.npy' )
SCREAMING_SNAKE_CASE : Any = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' )
SCREAMING_SNAKE_CASE : Optional[Any] = 'A red cartoon frog, 4k'
SCREAMING_SNAKE_CASE : str = KandinskyVaaPriorPipeline.from_pretrained(
'kandinsky-community/kandinsky-2-2-prior' ,torch_dtype=torch.floataa )
pipe_prior.to(__SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE : Optional[Any] = KandinskyVaaImgaImgPipeline.from_pretrained(
'kandinsky-community/kandinsky-2-2-decoder' ,torch_dtype=torch.floataa )
SCREAMING_SNAKE_CASE : str = pipeline.to(__SCREAMING_SNAKE_CASE )
pipeline.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device='cpu' ).manual_seed(0 )
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = pipe_prior(
__SCREAMING_SNAKE_CASE ,generator=__SCREAMING_SNAKE_CASE ,num_inference_steps=5 ,negative_prompt='' ,).to_tuple()
SCREAMING_SNAKE_CASE : Optional[Any] = pipeline(
image=__SCREAMING_SNAKE_CASE ,image_embeds=__SCREAMING_SNAKE_CASE ,negative_image_embeds=__SCREAMING_SNAKE_CASE ,generator=__SCREAMING_SNAKE_CASE ,num_inference_steps=100 ,height=768 ,width=768 ,strength=0.2 ,output_type='np' ,)
SCREAMING_SNAKE_CASE : List[Any] = output.images[0]
assert image.shape == (768, 768, 3)
assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE )
| 220 | 1 |
import math
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int:
if not isinstance(lowerCamelCase__ , lowerCamelCase__ ):
__lowerCamelCase : List[str] = F"Input value of [number={number}] must be an integer"
raise TypeError(lowerCamelCase__ )
if number < 1:
__lowerCamelCase : int = F"Input value of [number={number}] must be > 0"
raise ValueError(lowerCamelCase__ )
elif number == 1:
return 3
elif number == 2:
return 5
else:
__lowerCamelCase : Any = int(math.log(number // 3 , 2 ) ) + 2
__lowerCamelCase : List[Any] = [3, 5]
__lowerCamelCase : Union[str, Any] = 2
__lowerCamelCase : List[str] = 3
for block in range(1 , lowerCamelCase__ ):
for _ in range(lowerCamelCase__ ):
proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] )
proth_index += 1
increment *= 2
return proth_list[number - 1]
if __name__ == "__main__":
import doctest
doctest.testmod()
for number in range(11):
a =0
try:
a =proth(number)
except ValueError:
print(F"""ValueError: there is no {number}th Proth number""")
continue
print(F"""The {number}th Proth number: {value}""")
| 652 |
import gc
import random
import unittest
import numpy as np
import torch
from diffusers import (
DDIMScheduler,
KandinskyVaaControlnetPipeline,
KandinskyVaaPriorPipeline,
UNetaDConditionModel,
VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
enable_full_determinism()
class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_UpperCAmelCase : Optional[Any] = KandinskyVaaControlnetPipeline
_UpperCAmelCase : Optional[Any] = ['''image_embeds''', '''negative_image_embeds''', '''hint''']
_UpperCAmelCase : int = ['''image_embeds''', '''negative_image_embeds''', '''hint''']
_UpperCAmelCase : List[Any] = [
'''generator''',
'''height''',
'''width''',
'''latents''',
'''guidance_scale''',
'''num_inference_steps''',
'''return_dict''',
'''guidance_scale''',
'''num_images_per_prompt''',
'''output_type''',
'''return_dict''',
]
_UpperCAmelCase : Tuple = False
@property
def lowerCAmelCase ( self : Tuple):
return 3_2
@property
def lowerCAmelCase ( self : List[Any]):
return 3_2
@property
def lowerCAmelCase ( self : str):
return self.time_input_dim
@property
def lowerCAmelCase ( self : List[str]):
return self.time_input_dim * 4
@property
def lowerCAmelCase ( self : List[str]):
return 1_0_0
@property
def lowerCAmelCase ( self : Dict):
torch.manual_seed(0)
__lowerCamelCase : Optional[Any] = {
'in_channels': 8,
# Out channels is double in channels because predicts mean and variance
'out_channels': 8,
'addition_embed_type': 'image_hint',
'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'),
'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'),
'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn',
'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2),
'layers_per_block': 1,
'encoder_hid_dim': self.text_embedder_hidden_size,
'encoder_hid_dim_type': 'image_proj',
'cross_attention_dim': self.cross_attention_dim,
'attention_head_dim': 4,
'resnet_time_scale_shift': 'scale_shift',
'class_embed_type': None,
}
__lowerCamelCase : Union[str, Any] = UNetaDConditionModel(**SCREAMING_SNAKE_CASE__)
return model
@property
def lowerCAmelCase ( self : Union[str, Any]):
return {
"block_out_channels": [3_2, 3_2, 6_4, 6_4],
"down_block_types": [
"DownEncoderBlock2D",
"DownEncoderBlock2D",
"DownEncoderBlock2D",
"AttnDownEncoderBlock2D",
],
"in_channels": 3,
"latent_channels": 4,
"layers_per_block": 1,
"norm_num_groups": 8,
"norm_type": "spatial",
"num_vq_embeddings": 1_2,
"out_channels": 3,
"up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
"vq_embed_dim": 4,
}
@property
def lowerCAmelCase ( self : Optional[Any]):
torch.manual_seed(0)
__lowerCamelCase : int = VQModel(**self.dummy_movq_kwargs)
return model
def lowerCAmelCase ( self : Optional[Any]):
__lowerCamelCase : Tuple = self.dummy_unet
__lowerCamelCase : List[Any] = self.dummy_movq
__lowerCamelCase : str = DDIMScheduler(
num_train_timesteps=1_0_0_0 ,beta_schedule='linear' ,beta_start=0.00085 ,beta_end=0.012 ,clip_sample=SCREAMING_SNAKE_CASE__ ,set_alpha_to_one=SCREAMING_SNAKE_CASE__ ,steps_offset=1 ,prediction_type='epsilon' ,thresholding=SCREAMING_SNAKE_CASE__ ,)
__lowerCamelCase : Dict = {
'unet': unet,
'scheduler': scheduler,
'movq': movq,
}
return components
def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Optional[int]=0):
__lowerCamelCase : str = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(SCREAMING_SNAKE_CASE__)).to(SCREAMING_SNAKE_CASE__)
__lowerCamelCase : Optional[Any] = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(seed + 1)).to(
SCREAMING_SNAKE_CASE__)
# create hint
__lowerCamelCase : Optional[int] = floats_tensor((1, 3, 6_4, 6_4) ,rng=random.Random(SCREAMING_SNAKE_CASE__)).to(SCREAMING_SNAKE_CASE__)
if str(SCREAMING_SNAKE_CASE__).startswith('mps'):
__lowerCamelCase : int = torch.manual_seed(SCREAMING_SNAKE_CASE__)
else:
__lowerCamelCase : int = torch.Generator(device=SCREAMING_SNAKE_CASE__).manual_seed(SCREAMING_SNAKE_CASE__)
__lowerCamelCase : List[str] = {
'image_embeds': image_embeds,
'negative_image_embeds': negative_image_embeds,
'hint': hint,
'generator': generator,
'height': 6_4,
'width': 6_4,
'guidance_scale': 4.0,
'num_inference_steps': 2,
'output_type': 'np',
}
return inputs
def lowerCAmelCase ( self : Optional[Any]):
__lowerCamelCase : Dict = 'cpu'
__lowerCamelCase : Tuple = self.get_dummy_components()
__lowerCamelCase : Any = self.pipeline_class(**SCREAMING_SNAKE_CASE__)
__lowerCamelCase : List[str] = pipe.to(SCREAMING_SNAKE_CASE__)
pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)
__lowerCamelCase : Optional[Any] = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__))
__lowerCamelCase : int = output.images
__lowerCamelCase : Tuple = pipe(
**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__) ,return_dict=SCREAMING_SNAKE_CASE__ ,)[0]
__lowerCamelCase : Dict = image[0, -3:, -3:, -1]
__lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 6_4, 6_4, 3)
__lowerCamelCase : List[str] = np.array(
[0.6959826, 0.868279, 0.7558092, 0.68769467, 0.85805804, 0.65977496, 0.44885302, 0.5959111, 0.4251595])
assert (
np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
), F" expected_slice {expected_slice}, but got {image_slice.flatten()}"
assert (
np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1E-2
), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"
@slow
@require_torch_gpu
class A_ ( unittest.TestCase ):
def lowerCAmelCase ( self : int):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def lowerCAmelCase ( self : int):
__lowerCamelCase : List[Any] = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy')
__lowerCamelCase : Union[str, Any] = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/kandinskyv22/hint_image_cat.png')
__lowerCamelCase : Tuple = torch.from_numpy(np.array(SCREAMING_SNAKE_CASE__)).float() / 255.0
__lowerCamelCase : str = hint.permute(2 ,0 ,1).unsqueeze(0)
__lowerCamelCase : Tuple = KandinskyVaaPriorPipeline.from_pretrained(
'kandinsky-community/kandinsky-2-2-prior' ,torch_dtype=torch.floataa)
pipe_prior.to(SCREAMING_SNAKE_CASE__)
__lowerCamelCase : Any = KandinskyVaaControlnetPipeline.from_pretrained(
'kandinsky-community/kandinsky-2-2-controlnet-depth' ,torch_dtype=torch.floataa)
__lowerCamelCase : int = pipeline.to(SCREAMING_SNAKE_CASE__)
pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)
__lowerCamelCase : List[Any] = 'A robot, 4k photo'
__lowerCamelCase : List[str] = torch.Generator(device='cuda').manual_seed(0)
__lowerCamelCase , __lowerCamelCase : Optional[Any] = pipe_prior(
SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__ ,num_inference_steps=5 ,negative_prompt='' ,).to_tuple()
__lowerCamelCase : Optional[Any] = torch.Generator(device='cuda').manual_seed(0)
__lowerCamelCase : Any = pipeline(
image_embeds=SCREAMING_SNAKE_CASE__ ,negative_image_embeds=SCREAMING_SNAKE_CASE__ ,hint=SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__ ,num_inference_steps=1_0_0 ,output_type='np' ,)
__lowerCamelCase : List[Any] = output.images[0]
assert image.shape == (5_1_2, 5_1_2, 3)
assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)
| 652 | 1 |
'''simple docstring'''
def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> int:
return int((input_a, input_a).count(0 ) != 0 )
def a_ ( ) -> None:
assert nand_gate(0 ,0 ) == 1
assert nand_gate(0 ,1 ) == 1
assert nand_gate(1 ,0 ) == 1
assert nand_gate(1 ,1 ) == 0
if __name__ == "__main__":
print(nand_gate(0, 0))
print(nand_gate(0, 1))
print(nand_gate(1, 0))
print(nand_gate(1, 1))
| 124 |
'''simple docstring'''
import argparse
import torch
from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert
from transformers.utils import logging
logging.set_verbosity_info()
def a_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : Any ) -> Dict:
# Initialise PyTorch model
__snake_case : Tuple = BertConfig.from_json_file(_UpperCAmelCase )
print(f'''Building PyTorch model from configuration: {config}''' )
__snake_case : Optional[int] = BertForPreTraining(_UpperCAmelCase )
# Load weights from tf checkpoint
load_tf_weights_in_bert(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase )
# Save pytorch-model
print(f'''Save PyTorch model to {pytorch_dump_path}''' )
torch.save(model.state_dict() ,_UpperCAmelCase )
if __name__ == "__main__":
A__ : str = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.'''
)
parser.add_argument(
'''--bert_config_file''',
default=None,
type=str,
required=True,
help=(
'''The config json file corresponding to the pre-trained BERT model. \n'''
'''This specifies the model architecture.'''
),
)
parser.add_argument(
'''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
A__ : Tuple = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
| 124 | 1 |
"""simple docstring"""
import math
def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 0 , _SCREAMING_SNAKE_CASE = 0 ) ->list:
"""simple docstring"""
lowerCAmelCase__ :List[str] = end or len(_SCREAMING_SNAKE_CASE )
for i in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
lowerCAmelCase__ :List[Any] = i
lowerCAmelCase__ :Any = array[i]
while temp_index != start and temp_index_value < array[temp_index - 1]:
lowerCAmelCase__ :str = array[temp_index - 1]
temp_index -= 1
lowerCAmelCase__ :Tuple = temp_index_value
return array
def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->None: # Max Heap
"""simple docstring"""
lowerCAmelCase__ :Any = index
lowerCAmelCase__ :Optional[int] = 2 * index + 1 # Left Node
lowerCAmelCase__ :int = 2 * index + 2 # Right Node
if left_index < heap_size and array[largest] < array[left_index]:
lowerCAmelCase__ :Dict = left_index
if right_index < heap_size and array[largest] < array[right_index]:
lowerCAmelCase__ :str = right_index
if largest != index:
lowerCAmelCase__ , lowerCAmelCase__ :Dict = array[largest], array[index]
heapify(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def __A (_SCREAMING_SNAKE_CASE ) ->list:
"""simple docstring"""
lowerCAmelCase__ :Union[str, Any] = len(_SCREAMING_SNAKE_CASE )
for i in range(n // 2 , -1 , -1 ):
heapify(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
for i in range(n - 1 , 0 , -1 ):
lowerCAmelCase__ , lowerCAmelCase__ :int = array[0], array[i]
heapify(_SCREAMING_SNAKE_CASE , 0 , _SCREAMING_SNAKE_CASE )
return array
def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->int:
"""simple docstring"""
if (array[first_index] > array[middle_index]) != (
array[first_index] > array[last_index]
):
return array[first_index]
elif (array[middle_index] > array[first_index]) != (
array[middle_index] > array[last_index]
):
return array[middle_index]
else:
return array[last_index]
def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->int:
"""simple docstring"""
lowerCAmelCase__ :Optional[int] = low
lowerCAmelCase__ :int = high
while True:
while array[i] < pivot:
i += 1
j -= 1
while pivot < array[j]:
j -= 1
if i >= j:
return i
lowerCAmelCase__ , lowerCAmelCase__ :List[str] = array[j], array[i]
i += 1
def __A (_SCREAMING_SNAKE_CASE ) ->list:
"""simple docstring"""
if len(_SCREAMING_SNAKE_CASE ) == 0:
return array
lowerCAmelCase__ :Dict = 2 * math.ceil(math.loga(len(_SCREAMING_SNAKE_CASE ) ) )
lowerCAmelCase__ :Tuple = 16
return intro_sort(_SCREAMING_SNAKE_CASE , 0 , len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->list:
"""simple docstring"""
while end - start > size_threshold:
if max_depth == 0:
return heap_sort(_SCREAMING_SNAKE_CASE )
max_depth -= 1
lowerCAmelCase__ :Any = median_of_a(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , start + ((end - start) // 2) + 1 , end - 1 )
lowerCAmelCase__ :Tuple = partition(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
intro_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
lowerCAmelCase__ :str = p
return insertion_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
import doctest
doctest.testmod()
__A = input("""Enter numbers separated by a comma : """).strip()
__A = [float(item) for item in user_input.split(""",""")]
print(sort(unsorted))
| 93 |
'''simple docstring'''
import argparse
from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta
from transformers.utils import logging
logging.set_verbosity_info()
def lowercase (_A , _A , _A ):
"""simple docstring"""
_lowerCAmelCase : Optional[Any] = TaConfig.from_json_file(_A )
print(f'Building PyTorch model from configuration: {config}' )
_lowerCAmelCase : Union[str, Any] = TaForConditionalGeneration(_A )
# Load weights from tf checkpoint
load_tf_weights_in_ta(_A , _A , _A )
# Save pytorch-model
print(f'Save PyTorch model to {pytorch_dump_path}' )
model.save_pretrained(_A )
if __name__ == "__main__":
lowerCAmelCase : str = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
)
parser.add_argument(
"""--config_file""",
default=None,
type=str,
required=True,
help=(
"""The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture."""
),
)
parser.add_argument(
"""--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
)
lowerCAmelCase : int = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
| 444 | 0 |
import argparse
import os
import transformers
from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS
from .utils import logging
logging.set_verbosity_info()
lowerCAmelCase_ = logging.get_logger(__name__)
lowerCAmelCase_ = {name: getattr(transformers, name + """Fast""") for name in SLOW_TO_FAST_CONVERTERS}
def lowerCamelCase_ ( lowerCAmelCase: List[Any] , lowerCAmelCase: Optional[Any] , lowerCAmelCase: Dict , lowerCAmelCase: Union[str, Any] )-> Optional[int]:
if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES:
raise ValueError(F"""Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.""" )
if tokenizer_name is None:
_snake_case : Tuple = TOKENIZER_CLASSES
else:
_snake_case : Union[str, Any] = {tokenizer_name: getattr(lowerCAmelCase , tokenizer_name + 'Fast' )}
logger.info(F"""Loading tokenizer classes: {tokenizer_names}""" )
for tokenizer_name in tokenizer_names:
_snake_case : Dict = TOKENIZER_CLASSES[tokenizer_name]
_snake_case : Optional[Any] = True
if checkpoint_name is None:
_snake_case : Union[str, Any] = list(tokenizer_class.max_model_input_sizes.keys() )
else:
_snake_case : Optional[int] = [checkpoint_name]
logger.info(F"""For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}""" )
for checkpoint in checkpoint_names:
logger.info(F"""Loading {tokenizer_class.__class__.__name__} {checkpoint}""" )
# Load tokenizer
_snake_case : str = tokenizer_class.from_pretrained(lowerCAmelCase , force_download=lowerCAmelCase )
# Save fast tokenizer
logger.info(F"""Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}""" )
# For organization names we create sub-directories
if "/" in checkpoint:
_snake_case , _snake_case : Tuple = checkpoint.split('/' )
_snake_case : int = os.path.join(lowerCAmelCase , lowerCAmelCase )
elif add_prefix:
_snake_case : Dict = checkpoint
_snake_case : Optional[Any] = dump_path
else:
_snake_case : str = None
_snake_case : Union[str, Any] = dump_path
logger.info(F"""=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}""" )
if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]:
_snake_case : Optional[Any] = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint]
_snake_case : Optional[int] = file_path.split(lowerCAmelCase )[-1][0]
if next_char == "/":
_snake_case : Union[str, Any] = os.path.join(lowerCAmelCase , lowerCAmelCase )
_snake_case : str = None
logger.info(F"""=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}""" )
_snake_case : Optional[int] = tokenizer.save_pretrained(
lowerCAmelCase , legacy_format=lowerCAmelCase , filename_prefix=lowerCAmelCase )
logger.info(F"""=> File names {file_names}""" )
for file_name in file_names:
if not file_name.endswith('tokenizer.json' ):
os.remove(lowerCAmelCase )
logger.info(F"""=> removing {file_name}""" )
if __name__ == "__main__":
lowerCAmelCase_ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--dump_path""", default=None, type=str, required=True, help="""Path to output generated fast tokenizer files."""
)
parser.add_argument(
"""--tokenizer_name""",
default=None,
type=str,
help=(
F"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """
"""download and convert all the checkpoints from AWS."""
),
)
parser.add_argument(
"""--checkpoint_name""",
default=None,
type=str,
help="""Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.""",
)
parser.add_argument(
"""--force_download""",
action="""store_true""",
help="""Re-download checkpoints.""",
)
lowerCAmelCase_ = parser.parse_args()
convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
| 669 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _lowerCAmelCase ( UpperCAmelCase_ ):
'''simple docstring'''
a_ : Union[str, Any] =["""image_processor""", """tokenizer"""]
a_ : Optional[int] ="""CLIPImageProcessor"""
a_ : Optional[Any] =("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""")
def __init__( self : List[str] , UpperCamelCase : Optional[int]=None , UpperCamelCase : Optional[Any]=None , **UpperCamelCase : Dict ):
'''simple docstring'''
_snake_case : int = None
if "feature_extractor" in kwargs:
warnings.warn(
'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
' instead.' , UpperCamelCase , )
_snake_case : Optional[Any] = kwargs.pop('feature_extractor' )
_snake_case : Dict = 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__(UpperCamelCase , UpperCamelCase )
def __call__( self : Dict , UpperCamelCase : Optional[Any]=None , UpperCamelCase : Optional[Any]=None , UpperCamelCase : Optional[int]=None , **UpperCamelCase : Dict ):
'''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:
_snake_case : Optional[int] = self.tokenizer(UpperCamelCase , return_tensors=UpperCamelCase , **UpperCamelCase )
if images is not None:
_snake_case : Optional[int] = self.image_processor(UpperCamelCase , return_tensors=UpperCamelCase , **UpperCamelCase )
if text is not None and images is not None:
_snake_case : Optional[int] = image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**UpperCamelCase ) , tensor_type=UpperCamelCase )
def UpperCamelCase_ ( self : Union[str, Any] , *UpperCamelCase : Any , **UpperCamelCase : Union[str, Any] ):
'''simple docstring'''
return self.tokenizer.batch_decode(*UpperCamelCase , **UpperCamelCase )
def UpperCamelCase_ ( self : Union[str, Any] , *UpperCamelCase : Union[str, Any] , **UpperCamelCase : Optional[Any] ):
'''simple docstring'''
return self.tokenizer.decode(*UpperCamelCase , **UpperCamelCase )
@property
def UpperCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
_snake_case : Any = self.tokenizer.model_input_names
_snake_case : List[Any] = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
| 669 | 1 |
import gc
import unittest
import numpy as np
import torch
from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel
from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..pipeline_params import (
CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ):
'''simple docstring'''
UpperCAmelCase__ = DiTPipeline
UpperCAmelCase__ = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
UpperCAmelCase__ = PipelineTesterMixin.required_optional_params - {
'''latents''',
'''num_images_per_prompt''',
'''callback''',
'''callback_steps''',
}
UpperCAmelCase__ = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
UpperCAmelCase__ = False
def SCREAMING_SNAKE_CASE ( self : int) ->List[Any]:
'''simple docstring'''
torch.manual_seed(0)
A__ = TransformeraDModel(
sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=UpperCAmelCase__ , activation_fn='''gelu-approximate''' , num_embeds_ada_norm=1_000 , norm_type='''ada_norm_zero''' , norm_elementwise_affine=UpperCAmelCase__ , )
A__ = AutoencoderKL()
A__ = DDIMScheduler()
A__ = {'''transformer''': transformer.eval(), '''vae''': vae.eval(), '''scheduler''': scheduler}
return components
def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any]=0) ->str:
'''simple docstring'''
if str(UpperCAmelCase__).startswith('''mps'''):
A__ = torch.manual_seed(UpperCAmelCase__)
else:
A__ = torch.Generator(device=UpperCAmelCase__).manual_seed(UpperCAmelCase__)
A__ = {
'''class_labels''': [1],
'''generator''': generator,
'''num_inference_steps''': 2,
'''output_type''': '''numpy''',
}
return inputs
def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Optional[int]:
'''simple docstring'''
A__ = '''cpu'''
A__ = self.get_dummy_components()
A__ = self.pipeline_class(**UpperCAmelCase__)
pipe.to(UpperCAmelCase__)
pipe.set_progress_bar_config(disable=UpperCAmelCase__)
A__ = self.get_dummy_inputs(UpperCAmelCase__)
A__ = pipe(**UpperCAmelCase__).images
A__ = image[0, -3:, -3:, -1]
self.assertEqual(image.shape , (1, 16, 16, 3))
A__ = np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457])
A__ = np.abs(image_slice.flatten() - expected_slice).max()
self.assertLessEqual(UpperCAmelCase__ , 1e-3)
def SCREAMING_SNAKE_CASE ( self : Any) ->List[Any]:
'''simple docstring'''
self._test_inference_batch_single_identical(relax_max_difference=UpperCAmelCase__ , expected_max_diff=1e-3)
@unittest.skipIf(
torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , )
def SCREAMING_SNAKE_CASE ( self : Any) ->Union[str, Any]:
'''simple docstring'''
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3)
@require_torch_gpu
@slow
class UpperCamelCase_ ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->str:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[Any]:
'''simple docstring'''
A__ = torch.manual_seed(0)
A__ = DiTPipeline.from_pretrained('''facebook/DiT-XL-2-256''')
pipe.to('''cuda''')
A__ = ['''vase''', '''umbrella''', '''white shark''', '''white wolf''']
A__ = pipe.get_label_ids(UpperCAmelCase__)
A__ = pipe(UpperCAmelCase__ , generator=UpperCAmelCase__ , num_inference_steps=40 , output_type='''np''').images
for word, image in zip(UpperCAmelCase__ , UpperCAmelCase__):
A__ = load_numpy(
f"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy""")
assert np.abs((expected_image - image).max()) < 1e-2
def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]:
'''simple docstring'''
A__ = DiTPipeline.from_pretrained('''facebook/DiT-XL-2-512''')
A__ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe.to('''cuda''')
A__ = ['''vase''', '''umbrella''']
A__ = pipe.get_label_ids(UpperCAmelCase__)
A__ = torch.manual_seed(0)
A__ = pipe(UpperCAmelCase__ , generator=UpperCAmelCase__ , num_inference_steps=25 , output_type='''np''').images
for word, image in zip(UpperCAmelCase__ , UpperCAmelCase__):
A__ = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
f"""/dit/{word}_512.npy""")
assert np.abs((expected_image - image).max()) < 1e-1
| 87 |
import json
import os
import unittest
from transformers import MgpstrTokenizer
from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class A (__UpperCAmelCase ,unittest.TestCase ):
_SCREAMING_SNAKE_CASE = MgpstrTokenizer
_SCREAMING_SNAKE_CASE = False
_SCREAMING_SNAKE_CASE = {}
_SCREAMING_SNAKE_CASE = False
def __a ( self ) -> List[Any]:
'''simple docstring'''
super().setUp()
# fmt: off
_snake_case : int = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''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''']
# fmt: on
_snake_case : Optional[Any] = dict(zip(lowercase_ , range(len(lowercase_ ) ) ) )
_snake_case : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp:
fp.write(json.dumps(lowercase_ ) + '''\n''' )
def __a ( self , **lowercase_ ) -> Optional[Any]:
'''simple docstring'''
return MgpstrTokenizer.from_pretrained(self.tmpdirname , **lowercase_ )
def __a ( self , lowercase_ ) -> Optional[int]:
'''simple docstring'''
_snake_case : Optional[Any] = '''tester'''
_snake_case : List[str] = '''tester'''
return input_text, output_text
@unittest.skip('''MGP-STR always lower cases letters.''' )
def __a ( self ) -> Any:
'''simple docstring'''
pass
def __a ( self ) -> Optional[int]:
'''simple docstring'''
_snake_case : List[str] = self.get_tokenizers(do_lower_case=lowercase_ )
for tokenizer in tokenizers:
with self.subTest(F'''{tokenizer.__class__.__name__}''' ):
_snake_case : int = '''[SPECIAL_TOKEN]'''
tokenizer.add_special_tokens({'''cls_token''': special_token} )
_snake_case : Union[str, Any] = tokenizer.encode([special_token] , add_special_tokens=lowercase_ )
self.assertEqual(len(lowercase_ ) , 1 )
_snake_case : Union[str, Any] = tokenizer.decode(lowercase_ , skip_special_tokens=lowercase_ )
self.assertTrue(special_token not in decoded )
def __a ( self ) -> List[Any]:
'''simple docstring'''
_snake_case : Dict = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F'''{tokenizer.__class__.__name__}''' ):
_snake_case , _snake_case : int = self.get_input_output_texts(lowercase_ )
_snake_case : Optional[Any] = tokenizer.tokenize(lowercase_ )
_snake_case : Any = tokenizer.convert_tokens_to_ids(lowercase_ )
_snake_case : Tuple = tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ )
self.assertListEqual(lowercase_ , lowercase_ )
_snake_case : Tuple = tokenizer.convert_ids_to_tokens(lowercase_ )
self.assertNotEqual(len(lowercase_ ) , 0 )
_snake_case : str = tokenizer.decode(lowercase_ )
self.assertIsInstance(lowercase_ , lowercase_ )
self.assertEqual(text_a.replace(''' ''' , '''''' ) , lowercase_ )
@unittest.skip('''MGP-STR tokenizer only handles one sequence.''' )
def __a ( self ) -> Union[str, Any]:
'''simple docstring'''
pass
@unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer''' )
def __a ( self ) -> str:
'''simple docstring'''
pass
| 326 | 0 |
import os
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch
import numpy as np
from datasets import Dataset
from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer
class _SCREAMING_SNAKE_CASE ( _UpperCamelCase ):
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =tempfile.mkdtemp()
__UpperCAmelCase =5
# Realm tok
__UpperCAmelCase =[
'''[UNK]''',
'''[CLS]''',
'''[SEP]''',
'''[PAD]''',
'''[MASK]''',
'''test''',
'''question''',
'''this''',
'''is''',
'''the''',
'''first''',
'''second''',
'''third''',
'''fourth''',
'''fifth''',
'''record''',
'''want''',
'''##want''',
'''##ed''',
'''wa''',
'''un''',
'''runn''',
'''##ing''',
''',''',
'''low''',
'''lowest''',
]
__UpperCAmelCase =os.path.join(self.tmpdirname , '''realm_tokenizer''')
os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase)
__UpperCAmelCase =os.path.join(_UpperCAmelCase , VOCAB_FILES_NAMES['''vocab_file'''])
with open(self.vocab_file , '''w''' , encoding='''utf-8''') as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]))
__UpperCAmelCase =os.path.join(self.tmpdirname , '''realm_block_records''')
os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase)
def A__ (self):
'''simple docstring'''
return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer'''))
def A__ (self):
'''simple docstring'''
shutil.rmtree(self.tmpdirname)
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =RealmConfig(num_block_records=self.num_block_records)
return config
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =Dataset.from_dict(
{
'''id''': ['''0''', '''1'''],
'''question''': ['''foo''', '''bar'''],
'''answers''': [['''Foo''', '''Bar'''], ['''Bar''']],
})
return dataset
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =np.array(
[
B'''This is the first record''',
B'''This is the second record''',
B'''This is the third record''',
B'''This is the fourth record''',
B'''This is the fifth record''',
B'''This is a longer longer longer record''',
] , dtype=_UpperCAmelCase , )
return block_records
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =RealmRetriever(
block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , )
return retriever
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =self.get_config()
__UpperCAmelCase =self.get_dummy_retriever()
__UpperCAmelCase =retriever.tokenizer
__UpperCAmelCase =np.array([0, 3] , dtype='''long''')
__UpperCAmelCase =tokenizer(['''Test question''']).input_ids
__UpperCAmelCase =tokenizer(
['''the fourth'''] , add_special_tokens=_UpperCAmelCase , return_token_type_ids=_UpperCAmelCase , return_attention_mask=_UpperCAmelCase , ).input_ids
__UpperCAmelCase =config.reader_seq_len
__UpperCAmelCase =retriever(
_UpperCAmelCase , _UpperCAmelCase , answer_ids=_UpperCAmelCase , max_length=_UpperCAmelCase , return_tensors='''np''')
self.assertEqual(len(_UpperCAmelCase) , 2)
self.assertEqual(len(_UpperCAmelCase) , 2)
self.assertEqual(len(_UpperCAmelCase) , 2)
self.assertEqual(concat_inputs.input_ids.shape , (2, 1_0))
self.assertEqual(concat_inputs.attention_mask.shape , (2, 1_0))
self.assertEqual(concat_inputs.token_type_ids.shape , (2, 1_0))
self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 1_0))
self.assertEqual(
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0]) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , )
self.assertEqual(
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1]) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , )
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =self.get_config()
__UpperCAmelCase =self.get_dummy_retriever()
__UpperCAmelCase =retriever.tokenizer
__UpperCAmelCase =np.array([0, 3, 5] , dtype='''long''')
__UpperCAmelCase =tokenizer(['''Test question''']).input_ids
__UpperCAmelCase =tokenizer(
['''the fourth''', '''longer longer'''] , add_special_tokens=_UpperCAmelCase , return_token_type_ids=_UpperCAmelCase , return_attention_mask=_UpperCAmelCase , ).input_ids
__UpperCAmelCase =config.reader_seq_len
__UpperCAmelCase =retriever(
_UpperCAmelCase , _UpperCAmelCase , answer_ids=_UpperCAmelCase , max_length=_UpperCAmelCase , return_tensors='''np''')
self.assertEqual([False, True, True] , _UpperCAmelCase)
self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , _UpperCAmelCase)
self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , _UpperCAmelCase)
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =self.get_dummy_retriever()
retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records'''))
# Test local path
__UpperCAmelCase =retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records'''))
self.assertEqual(retriever.block_records[0] , B'''This is the first record''')
# Test mocked remote path
with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''') as mock_hf_hub_download:
__UpperCAmelCase =os.path.join(
os.path.join(self.tmpdirname , '''realm_block_records''') , _REALM_BLOCK_RECORDS_FILENAME)
__UpperCAmelCase =RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''')
self.assertEqual(retriever.block_records[0] , B'''This is the first record''')
| 713 |
from __future__ import annotations
import inspect
import unittest
from typing import List, Tuple
from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class _SCREAMING_SNAKE_CASE :
def __init__(self , UpperCAmelCase , UpperCAmelCase=3 , UpperCAmelCase=3_2 , UpperCAmelCase=3 , UpperCAmelCase=1_0 , UpperCAmelCase=[1_0, 2_0, 3_0, 4_0] , UpperCAmelCase=[1, 1, 2, 1] , UpperCAmelCase=True , UpperCAmelCase=True , UpperCAmelCase="relu" , UpperCAmelCase=3 , UpperCAmelCase=None , ):
'''simple docstring'''
__UpperCAmelCase =parent
__UpperCAmelCase =batch_size
__UpperCAmelCase =image_size
__UpperCAmelCase =num_channels
__UpperCAmelCase =embeddings_size
__UpperCAmelCase =hidden_sizes
__UpperCAmelCase =depths
__UpperCAmelCase =is_training
__UpperCAmelCase =use_labels
__UpperCAmelCase =hidden_act
__UpperCAmelCase =num_labels
__UpperCAmelCase =scope
__UpperCAmelCase =len(UpperCAmelCase)
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
__UpperCAmelCase =None
if self.use_labels:
__UpperCAmelCase =ids_tensor([self.batch_size] , self.num_labels)
__UpperCAmelCase =self.get_config()
return config, pixel_values, labels
def A__ (self):
'''simple docstring'''
return RegNetConfig(
num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , )
def A__ (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase):
'''simple docstring'''
__UpperCAmelCase =TFRegNetModel(config=UpperCAmelCase)
__UpperCAmelCase =model(UpperCAmelCase , training=UpperCAmelCase)
# expected last hidden states: B, C, H // 32, W // 32
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , )
def A__ (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase):
'''simple docstring'''
__UpperCAmelCase =self.num_labels
__UpperCAmelCase =TFRegNetForImageClassification(UpperCAmelCase)
__UpperCAmelCase =model(UpperCAmelCase , labels=UpperCAmelCase , training=UpperCAmelCase)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =self.prepare_config_and_inputs()
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =config_and_inputs
__UpperCAmelCase ={'''pixel_values''': pixel_values}
return config, inputs_dict
@require_tf
class _SCREAMING_SNAKE_CASE ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ):
a_ : Any = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
a_ : Union[str, Any] = (
{'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
if is_tf_available()
else {}
)
a_ : str = False
a_ : List[str] = False
a_ : int = False
a_ : List[str] = False
a_ : List[Any] = False
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =TFRegNetModelTester(self)
__UpperCAmelCase =ConfigTester(self , config_class=UpperCAmelCase , has_text_modality=UpperCAmelCase)
def A__ (self):
'''simple docstring'''
return
@unittest.skip(reason='''RegNet does not use inputs_embeds''')
def A__ (self):
'''simple docstring'''
pass
@unittest.skipIf(
not is_tf_available() or len(tf.config.list_physical_devices('''GPU''')) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , )
@slow
def A__ (self):
'''simple docstring'''
super().test_keras_fit()
@unittest.skip(reason='''RegNet does not support input and output embeddings''')
def A__ (self):
'''simple docstring'''
pass
def A__ (self):
'''simple docstring'''
__UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__UpperCAmelCase =model_class(UpperCAmelCase)
__UpperCAmelCase =inspect.signature(model.call)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__UpperCAmelCase =[*signature.parameters.keys()]
__UpperCAmelCase =['''pixel_values''']
self.assertListEqual(arg_names[:1] , UpperCAmelCase)
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCAmelCase)
def A__ (self):
'''simple docstring'''
def check_hidden_states_output(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase):
__UpperCAmelCase =model_class(UpperCAmelCase)
__UpperCAmelCase =model(**self._prepare_for_class(UpperCAmelCase , UpperCAmelCase) , training=UpperCAmelCase)
__UpperCAmelCase =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
__UpperCAmelCase =self.model_tester.num_stages
self.assertEqual(len(UpperCAmelCase) , expected_num_stages + 1)
# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
self.assertListEqual(
list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , )
__UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common()
__UpperCAmelCase =['''basic''', '''bottleneck''']
for model_class in self.all_model_classes:
for layer_type in layers_type:
__UpperCAmelCase =layer_type
__UpperCAmelCase =True
check_hidden_states_output(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__UpperCAmelCase =True
check_hidden_states_output(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase)
def A__ (self):
'''simple docstring'''
__UpperCAmelCase , __UpperCAmelCase =self.model_tester.prepare_config_and_inputs_for_common()
def check_equivalence(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase={}):
__UpperCAmelCase =model(UpperCAmelCase , return_dict=UpperCAmelCase , **UpperCAmelCase)
__UpperCAmelCase =model(UpperCAmelCase , return_dict=UpperCAmelCase , **UpperCAmelCase).to_tuple()
def recursive_check(UpperCAmelCase , UpperCAmelCase):
if isinstance(UpperCAmelCase , (List, Tuple)):
for tuple_iterable_value, dict_iterable_value in zip(UpperCAmelCase , UpperCAmelCase):
recursive_check(UpperCAmelCase , UpperCAmelCase)
elif tuple_object is None:
return
else:
self.assertTrue(
all(tf.equal(UpperCAmelCase , UpperCAmelCase)) , msg=(
'''Tuple and dict output are not equal. Difference:'''
f""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}"""
) , )
recursive_check(UpperCAmelCase , UpperCAmelCase)
for model_class in self.all_model_classes:
__UpperCAmelCase =model_class(UpperCAmelCase)
__UpperCAmelCase =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase)
__UpperCAmelCase =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase)
check_equivalence(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase)
__UpperCAmelCase =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase , return_labels=UpperCAmelCase)
__UpperCAmelCase =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase , return_labels=UpperCAmelCase)
check_equivalence(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase)
__UpperCAmelCase =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase)
__UpperCAmelCase =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase)
check_equivalence(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , {'''output_hidden_states''': True})
__UpperCAmelCase =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase , return_labels=UpperCAmelCase)
__UpperCAmelCase =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase , return_labels=UpperCAmelCase)
check_equivalence(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , {'''output_hidden_states''': True})
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase)
@slow
def A__ (self):
'''simple docstring'''
for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__UpperCAmelCase =TFRegNetModel.from_pretrained(UpperCAmelCase)
self.assertIsNotNone(UpperCAmelCase)
def SCREAMING_SNAKE_CASE ( ) -> Tuple:
__UpperCAmelCase =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_tf
@require_vision
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
@cached_property
def A__ (self):
'''simple docstring'''
return (
AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
if is_vision_available()
else None
)
@slow
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
__UpperCAmelCase =self.default_image_processor
__UpperCAmelCase =prepare_img()
__UpperCAmelCase =image_processor(images=UpperCAmelCase , return_tensors='''tf''')
# forward pass
__UpperCAmelCase =model(**UpperCAmelCase , training=UpperCAmelCase)
# verify the logits
__UpperCAmelCase =tf.TensorShape((1, 1_0_0_0))
self.assertEqual(outputs.logits.shape , UpperCAmelCase)
__UpperCAmelCase =tf.constant([-0.4180, -1.5051, -3.4836])
tf.debugging.assert_near(outputs.logits[0, :3] , UpperCAmelCase , atol=1e-4)
| 142 | 0 |
"""simple docstring"""
import tensorflow as tf
from ...tf_utils import shape_list
class _a ( tf.keras.layers.Layer):
"""simple docstring"""
def __init__( self : Union[str, Any] , __UpperCamelCase : Tuple , __UpperCamelCase : str , __UpperCamelCase : Any , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Any=1 , __UpperCamelCase : Optional[int]=False , **__UpperCamelCase : Any )->Any:
super().__init__(**__UpperCamelCase )
_UpperCAmelCase = vocab_size
_UpperCAmelCase = d_embed
_UpperCAmelCase = d_proj
_UpperCAmelCase = cutoffs + [vocab_size]
_UpperCAmelCase = [0] + self.cutoffs
_UpperCAmelCase = div_val
_UpperCAmelCase = self.cutoffs[0]
_UpperCAmelCase = len(self.cutoffs ) - 1
_UpperCAmelCase = self.shortlist_size + self.n_clusters
_UpperCAmelCase = keep_order
_UpperCAmelCase = []
_UpperCAmelCase = []
def lowercase__ ( self : Any , __UpperCamelCase : str )->int:
if self.n_clusters > 0:
_UpperCAmelCase = self.add_weight(
shape=(self.n_clusters, self.d_embed) , initializer='''zeros''' , trainable=__UpperCamelCase , name='''cluster_weight''' )
_UpperCAmelCase = self.add_weight(
shape=(self.n_clusters,) , initializer='''zeros''' , trainable=__UpperCamelCase , name='''cluster_bias''' )
if self.div_val == 1:
for i in range(len(self.cutoffs ) ):
if self.d_proj != self.d_embed:
_UpperCAmelCase = self.add_weight(
shape=(self.d_embed, self.d_proj) , initializer='''zeros''' , trainable=__UpperCamelCase , name=F'out_projs_._{i}' , )
self.out_projs.append(__UpperCamelCase )
else:
self.out_projs.append(__UpperCamelCase )
_UpperCAmelCase = self.add_weight(
shape=(self.vocab_size, self.d_embed) , initializer='''zeros''' , trainable=__UpperCamelCase , name=F'out_layers_._{i}_._weight' , )
_UpperCAmelCase = self.add_weight(
shape=(self.vocab_size,) , initializer='''zeros''' , trainable=__UpperCamelCase , name=F'out_layers_._{i}_._bias' , )
self.out_layers.append((weight, bias) )
else:
for i in range(len(self.cutoffs ) ):
_UpperCAmelCase , _UpperCAmelCase = self.cutoff_ends[i], self.cutoff_ends[i + 1]
_UpperCAmelCase = self.d_embed // (self.div_val**i)
_UpperCAmelCase = self.add_weight(
shape=(d_emb_i, self.d_proj) , initializer='''zeros''' , trainable=__UpperCamelCase , name=F'out_projs_._{i}' )
self.out_projs.append(__UpperCamelCase )
_UpperCAmelCase = self.add_weight(
shape=(r_idx - l_idx, d_emb_i) , initializer='''zeros''' , trainable=__UpperCamelCase , name=F'out_layers_._{i}_._weight' , )
_UpperCAmelCase = self.add_weight(
shape=(r_idx - l_idx,) , initializer='''zeros''' , trainable=__UpperCamelCase , name=F'out_layers_._{i}_._bias' , )
self.out_layers.append((weight, bias) )
super().build(__UpperCamelCase )
@staticmethod
def lowercase__ ( __UpperCamelCase : List[str] , __UpperCamelCase : List[str] , __UpperCamelCase : int , __UpperCamelCase : Tuple=None )->int:
_UpperCAmelCase = x
if proj is not None:
_UpperCAmelCase = tf.einsum('''ibd,ed->ibe''' , __UpperCamelCase , __UpperCamelCase )
return tf.einsum('''ibd,nd->ibn''' , __UpperCamelCase , __UpperCamelCase ) + b
@staticmethod
def lowercase__ ( __UpperCamelCase : Tuple , __UpperCamelCase : Dict )->Tuple:
_UpperCAmelCase = shape_list(__UpperCamelCase )
_UpperCAmelCase = tf.range(lp_size[0] , dtype=target.dtype )
_UpperCAmelCase = tf.stack([r, target] , 1 )
return tf.gather_nd(__UpperCamelCase , __UpperCamelCase )
def lowercase__ ( self : Dict , __UpperCamelCase : Optional[int] , __UpperCamelCase : List[str] , __UpperCamelCase : Union[str, Any]=True , __UpperCamelCase : int=False )->List[Any]:
_UpperCAmelCase = 0
if self.n_clusters == 0:
_UpperCAmelCase = self._logit(__UpperCamelCase , self.out_layers[0][0] , self.out_layers[0][1] , self.out_projs[0] )
if target is not None:
_UpperCAmelCase = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=__UpperCamelCase , logits=__UpperCamelCase )
_UpperCAmelCase = tf.nn.log_softmax(__UpperCamelCase , axis=-1 )
else:
_UpperCAmelCase = shape_list(__UpperCamelCase )
_UpperCAmelCase = []
_UpperCAmelCase = tf.zeros(hidden_sizes[:2] )
for i in range(len(self.cutoffs ) ):
_UpperCAmelCase , _UpperCAmelCase = self.cutoff_ends[i], self.cutoff_ends[i + 1]
if target is not None:
_UpperCAmelCase = (target >= l_idx) & (target < r_idx)
_UpperCAmelCase = tf.where(__UpperCamelCase )
_UpperCAmelCase = tf.boolean_mask(__UpperCamelCase , __UpperCamelCase ) - l_idx
if self.div_val == 1:
_UpperCAmelCase = self.out_layers[0][0][l_idx:r_idx]
_UpperCAmelCase = self.out_layers[0][1][l_idx:r_idx]
else:
_UpperCAmelCase = self.out_layers[i][0]
_UpperCAmelCase = self.out_layers[i][1]
if i == 0:
_UpperCAmelCase = tf.concat([cur_W, self.cluster_weight] , 0 )
_UpperCAmelCase = tf.concat([cur_b, self.cluster_bias] , 0 )
_UpperCAmelCase = self._logit(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , self.out_projs[0] )
_UpperCAmelCase = tf.nn.log_softmax(__UpperCamelCase )
out.append(head_logprob[..., : self.cutoffs[0]] )
if target is not None:
_UpperCAmelCase = tf.boolean_mask(__UpperCamelCase , __UpperCamelCase )
_UpperCAmelCase = self._gather_logprob(__UpperCamelCase , __UpperCamelCase )
else:
_UpperCAmelCase = self._logit(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , self.out_projs[i] )
_UpperCAmelCase = tf.nn.log_softmax(__UpperCamelCase )
_UpperCAmelCase = self.cutoffs[0] + i - 1 # No probability for the head cluster
_UpperCAmelCase = head_logprob[..., cluster_prob_idx, None] + tail_logprob
out.append(__UpperCamelCase )
if target is not None:
_UpperCAmelCase = tf.boolean_mask(__UpperCamelCase , __UpperCamelCase )
_UpperCAmelCase = tf.boolean_mask(__UpperCamelCase , __UpperCamelCase )
_UpperCAmelCase = self._gather_logprob(__UpperCamelCase , __UpperCamelCase )
cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]
if target is not None:
loss += tf.scatter_nd(__UpperCamelCase , -cur_logprob , shape_list(__UpperCamelCase ) )
_UpperCAmelCase = tf.concat(__UpperCamelCase , axis=-1 )
if target is not None:
if return_mean:
_UpperCAmelCase = tf.reduce_mean(__UpperCamelCase )
# Add the training-time loss value to the layer using `self.add_loss()`.
self.add_loss(__UpperCamelCase )
# Log the loss as a metric (we could log arbitrary metrics,
# including different metrics for training and inference.
self.add_metric(__UpperCamelCase , name=self.name , aggregation='''mean''' if return_mean else '''''' )
return out
| 602 |
"""simple docstring"""
__A : int = frozenset(
[
"prompt",
"height",
"width",
"guidance_scale",
"negative_prompt",
"prompt_embeds",
"negative_prompt_embeds",
"cross_attention_kwargs",
]
)
__A : Any = frozenset(["prompt", "negative_prompt"])
__A : Optional[Any] = frozenset([])
__A : List[Any] = frozenset(["image"])
__A : int = frozenset(
[
"image",
"height",
"width",
"guidance_scale",
]
)
__A : Any = frozenset(["image"])
__A : Optional[int] = frozenset(
[
"prompt",
"image",
"height",
"width",
"guidance_scale",
"negative_prompt",
"prompt_embeds",
"negative_prompt_embeds",
]
)
__A : Any = frozenset(["prompt", "image", "negative_prompt"])
__A : Dict = frozenset(
[
# Text guided image variation with an image mask
"prompt",
"image",
"mask_image",
"height",
"width",
"guidance_scale",
"negative_prompt",
"prompt_embeds",
"negative_prompt_embeds",
]
)
__A : str = frozenset(["prompt", "image", "mask_image", "negative_prompt"])
__A : List[Any] = frozenset(
[
# image variation with an image mask
"image",
"mask_image",
"height",
"width",
"guidance_scale",
]
)
__A : Union[str, Any] = frozenset(["image", "mask_image"])
__A : Tuple = frozenset(
[
"example_image",
"image",
"mask_image",
"height",
"width",
"guidance_scale",
]
)
__A : int = frozenset(["example_image", "image", "mask_image"])
__A : Union[str, Any] = frozenset(["class_labels"])
__A : Union[str, Any] = frozenset(["class_labels"])
__A : List[Any] = frozenset(["batch_size"])
__A : Optional[int] = frozenset([])
__A : Tuple = frozenset(["batch_size"])
__A : Union[str, Any] = frozenset([])
__A : List[str] = frozenset(
[
"prompt",
"audio_length_in_s",
"guidance_scale",
"negative_prompt",
"prompt_embeds",
"negative_prompt_embeds",
"cross_attention_kwargs",
]
)
__A : Tuple = frozenset(["prompt", "negative_prompt"])
__A : Dict = frozenset(["input_tokens"])
__A : List[str] = frozenset(["input_tokens"])
| 602 | 1 |
import argparse
from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta
from transformers.utils import logging
logging.set_verbosity_info()
def _lowerCamelCase ( A_ : Tuple , A_ : Union[str, Any] , A_ : Tuple ) -> List[Any]:
'''simple docstring'''
UpperCamelCase__ : List[str] =TaConfig.from_json_file(A_ )
print(f'''Building PyTorch model from configuration: {config}''' )
UpperCamelCase__ : List[str] =TaForConditionalGeneration(A_ )
# Load weights from tf checkpoint
load_tf_weights_in_ta(A_ , A_ , A_ )
# Save pytorch-model
print(f'''Save PyTorch model to {pytorch_dump_path}''' )
model.save_pretrained(A_ )
if __name__ == "__main__":
__UpperCAmelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
)
parser.add_argument(
"""--config_file""",
default=None,
type=str,
required=True,
help=(
"""The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture."""
),
)
parser.add_argument(
"""--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
)
__UpperCAmelCase = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
| 582 |
import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path
import torch_xla.distributed.xla_multiprocessing as xmp
def _lowerCamelCase ( ) -> int:
'''simple docstring'''
UpperCamelCase__ : str =ArgumentParser(
description=(
"PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes"
) )
# Optional arguments for the launch helper
parser.add_argument("--num_cores" , type=A_ , default=1 , help="Number of TPU cores to use (1 or 8)." )
# positional
parser.add_argument(
"training_script" , type=A_ , help=(
"The full path to the single TPU training "
"program/script to be launched in parallel, "
"followed by all the arguments for the "
"training script"
) , )
# rest from the training program
parser.add_argument("training_script_args" , nargs=A_ )
return parser.parse_args()
def _lowerCamelCase ( ) -> List[str]:
'''simple docstring'''
UpperCamelCase__ : Dict =parse_args()
# Import training_script as a module.
UpperCamelCase__ : Union[str, Any] =Path(args.training_script )
sys.path.append(str(script_fpath.parent.resolve() ) )
UpperCamelCase__ : Optional[Any] =script_fpath.stem
UpperCamelCase__ : Any =importlib.import_module(A_ )
# Patch sys.argv
UpperCamelCase__ : Optional[Any] =[args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )]
xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores )
if __name__ == "__main__":
main()
| 582 | 1 |
"""simple docstring"""
lowercase_ = 6_5_5_2_1
def lowercase ( lowerCAmelCase__ : str ) -> int:
__a = 1
__a = 0
for plain_chr in plain_text:
__a = (a + ord(lowerCAmelCase__ )) % MOD_ADLER
__a = (b + a) % MOD_ADLER
return (b << 16) | a
| 695 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowercase_ = logging.get_logger(__name__)
lowercase_ = {
"bigcode/gpt_bigcode-santacoder": "https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json",
}
class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
__UpperCAmelCase : List[str] = 'gpt_bigcode'
__UpperCAmelCase : Tuple = ['past_key_values']
__UpperCAmelCase : Dict = {
'hidden_size': 'n_embd',
'max_position_embeddings': 'n_positions',
'num_attention_heads': 'n_head',
'num_hidden_layers': 'n_layer',
}
def __init__( self , _a=50_257 , _a=1_024 , _a=768 , _a=12 , _a=12 , _a=None , _a="gelu_pytorch_tanh" , _a=0.1 , _a=0.1 , _a=0.1 , _a=1E-5 , _a=0.02 , _a=True , _a=True , _a=50_256 , _a=50_256 , _a=True , _a=True , _a=True , **_a , ):
__a = vocab_size
__a = n_positions
__a = n_embd
__a = n_layer
__a = n_head
__a = n_inner
__a = activation_function
__a = resid_pdrop
__a = embd_pdrop
__a = attn_pdrop
__a = layer_norm_epsilon
__a = initializer_range
__a = scale_attn_weights
__a = use_cache
__a = attention_softmax_in_fpaa
__a = scale_attention_softmax_in_fpaa
__a = multi_query
__a = bos_token_id
__a = eos_token_id
super().__init__(bos_token_id=_a , eos_token_id=_a , **_a )
| 695 | 1 |
import pickle
import numpy as np
from matplotlib import pyplot as plt
class UpperCAmelCase:
"""simple docstring"""
def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase=0.2 , lowerCamelCase=0.2 ) -> Any:
"""simple docstring"""
lowercase__ : Optional[int] = bp_numa
lowercase__ : int = bp_numa
lowercase__ : Optional[int] = bp_numa
lowercase__ : List[str] = conva_get[:2]
lowercase__ : str = conva_get[2]
lowercase__ : Tuple = size_pa
lowercase__ : Union[str, Any] = rate_w
lowercase__ : Optional[Any] = rate_t
lowercase__ : str = [
np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 )
for i in range(self.conva[1] )
]
lowercase__ : Dict = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 )
lowercase__ : List[Any] = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 )
lowercase__ : Union[str, Any] = -2 * np.random.rand(self.conva[1] ) + 1
lowercase__ : Union[str, Any] = -2 * np.random.rand(self.num_bpa ) + 1
lowercase__ : List[Any] = -2 * np.random.rand(self.num_bpa ) + 1
def __a ( self , lowerCamelCase ) -> Union[str, Any]:
"""simple docstring"""
lowercase__ : int = {
"""num_bp1""": self.num_bpa,
"""num_bp2""": self.num_bpa,
"""num_bp3""": self.num_bpa,
"""conv1""": self.conva,
"""step_conv1""": self.step_conva,
"""size_pooling1""": self.size_poolinga,
"""rate_weight""": self.rate_weight,
"""rate_thre""": self.rate_thre,
"""w_conv1""": self.w_conva,
"""wkj""": self.wkj,
"""vji""": self.vji,
"""thre_conv1""": self.thre_conva,
"""thre_bp2""": self.thre_bpa,
"""thre_bp3""": self.thre_bpa,
}
with open(lowercase_ , "wb" ) as f:
pickle.dump(lowercase_ , lowercase_ )
print(f"""Model saved: {save_path}""" )
@classmethod
def __a ( cls , lowerCamelCase ) -> Tuple:
"""simple docstring"""
with open(lowercase_ , "rb" ) as f:
lowercase__ : List[Any] = pickle.load(lowercase_ ) # noqa: S301
lowercase__ : Any = model_dic.get("conv1" )
conv_get.append(model_dic.get("step_conv1" ) )
lowercase__ : Tuple = model_dic.get("size_pooling1" )
lowercase__ : Tuple = model_dic.get("num_bp1" )
lowercase__ : Dict = model_dic.get("num_bp2" )
lowercase__ : Tuple = model_dic.get("num_bp3" )
lowercase__ : List[str] = model_dic.get("rate_weight" )
lowercase__ : Optional[int] = model_dic.get("rate_thre" )
# create model instance
lowercase__ : List[str] = CNN(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ )
# modify model parameter
lowercase__ : int = model_dic.get("w_conv1" )
lowercase__ : str = model_dic.get("wkj" )
lowercase__ : List[Any] = model_dic.get("vji" )
lowercase__ : Union[str, Any] = model_dic.get("thre_conv1" )
lowercase__ : Union[str, Any] = model_dic.get("thre_bp2" )
lowercase__ : List[str] = model_dic.get("thre_bp3" )
return conv_ins
def __a ( self , lowerCamelCase ) -> str:
"""simple docstring"""
return 1 / (1 + np.exp(-1 * x ))
def __a ( self , lowerCamelCase ) -> Union[str, Any]:
"""simple docstring"""
return round(lowercase_ , 3 )
def __a ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) -> Optional[int]:
"""simple docstring"""
lowercase__ : List[str] = convs[0]
lowercase__ : Tuple = convs[1]
lowercase__ : Tuple = np.shape(lowercase_ )[0]
# get the data slice of original image data, data_focus
lowercase__ : Dict = []
for i_focus in range(0 , size_data - size_conv + 1 , lowercase_ ):
for j_focus in range(0 , size_data - size_conv + 1 , lowercase_ ):
lowercase__ : Optional[int] = data[
i_focus : i_focus + size_conv, j_focus : j_focus + size_conv
]
data_focus.append(lowercase_ )
# calculate the feature map of every single kernel, and saved as list of matrix
lowercase__ : List[Any] = []
lowercase__ : int = int((size_data - size_conv) / conv_step + 1 )
for i_map in range(lowercase_ ):
lowercase__ : Any = []
for i_focus in range(len(lowercase_ ) ):
lowercase__ : List[Any] = (
np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) )
- thre_convs[i_map]
)
featuremap.append(self.sig(lowercase_ ) )
lowercase__ : Optional[int] = np.asmatrix(lowercase_ ).reshape(
lowercase_ , lowercase_ )
data_featuremap.append(lowercase_ )
# expanding the data slice to One dimenssion
lowercase__ : Optional[Any] = []
for each_focus in data_focus:
focusa_list.extend(self.Expand_Mat(lowercase_ ) )
lowercase__ : Tuple = np.asarray(lowercase_ )
return focus_list, data_featuremap
def __a ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase="average_pool" ) -> Union[str, Any]:
"""simple docstring"""
lowercase__ : int = len(featuremaps[0] )
lowercase__ : Optional[int] = int(size_map / size_pooling )
lowercase__ : Dict = []
for i_map in range(len(lowercase_ ) ):
lowercase__ : Any = featuremaps[i_map]
lowercase__ : List[Any] = []
for i_focus in range(0 , lowercase_ , lowercase_ ):
for j_focus in range(0 , lowercase_ , lowercase_ ):
lowercase__ : List[Any] = feature_map[
i_focus : i_focus + size_pooling,
j_focus : j_focus + size_pooling,
]
if pooling_type == "average_pool":
# average pooling
map_pooled.append(np.average(lowercase_ ) )
elif pooling_type == "max_pooling":
# max pooling
map_pooled.append(np.max(lowercase_ ) )
lowercase__ : int = np.asmatrix(lowercase_ ).reshape(lowercase_ , lowercase_ )
featuremap_pooled.append(lowercase_ )
return featuremap_pooled
def __a ( self , lowerCamelCase ) -> Union[str, Any]:
"""simple docstring"""
lowercase__ : Optional[int] = []
for i in range(len(lowercase_ ) ):
lowercase__ : List[str] = np.shape(data[i] )
lowercase__ : Optional[Any] = data[i].reshape(1 , shapes[0] * shapes[1] )
lowercase__ : int = data_listed.getA().tolist()[0]
data_expanded.extend(lowercase_ )
lowercase__ : Union[str, Any] = np.asarray(lowercase_ )
return data_expanded
def __a ( self , lowerCamelCase ) -> Union[str, Any]:
"""simple docstring"""
lowercase__ : Optional[int] = np.asarray(lowercase_ )
lowercase__ : Optional[Any] = np.shape(lowercase_ )
lowercase__ : Tuple = data_mat.reshape(1 , shapes[0] * shapes[1] )
return data_expanded
def __a ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) -> List[str]:
"""simple docstring"""
lowercase__ : Tuple = []
lowercase__ : List[str] = 0
for i_map in range(lowercase_ ):
lowercase__ : Any = np.ones((size_map, size_map) )
for i in range(0 , lowercase_ , lowercase_ ):
for j in range(0 , lowercase_ , lowercase_ ):
lowercase__ : List[str] = pd_pool[
i_pool
]
lowercase__ : Tuple = i_pool + 1
lowercase__ : Dict = np.multiply(
lowercase_ , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) )
pd_all.append(lowercase_ )
return pd_all
def __a ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase=bool ) -> Union[str, Any]:
"""simple docstring"""
print("----------------------Start Training-------------------------" )
print((" - - Shape: Train_Data ", np.shape(lowercase_ )) )
print((" - - Shape: Teach_Data ", np.shape(lowercase_ )) )
lowercase__ : Tuple = 0
lowercase__ : Optional[Any] = []
lowercase__ : str = 10000
while rp < n_repeat and mse >= error_accuracy:
lowercase__ : Any = 0
print(f"""-------------Learning Time {rp}--------------""" )
for p in range(len(lowercase_ ) ):
# print('------------Learning Image: %d--------------'%p)
lowercase__ : Any = np.asmatrix(datas_train[p] )
lowercase__ : Optional[int] = np.asarray(datas_teach[p] )
lowercase__ : List[Any] = self.convolute(
lowercase_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
lowercase__ : List[Any] = self.pooling(lowercase_ , self.size_poolinga )
lowercase__ : List[str] = np.shape(lowercase_ )
lowercase__ : Dict = self._expand(lowercase_ )
lowercase__ : Tuple = data_bp_input
lowercase__ : Union[str, Any] = np.dot(lowercase_ , self.vji.T ) - self.thre_bpa
lowercase__ : Tuple = self.sig(lowercase_ )
lowercase__ : Tuple = np.dot(lowercase_ , self.wkj.T ) - self.thre_bpa
lowercase__ : Tuple = self.sig(lowercase_ )
# --------------Model Leaning ------------------------
# calculate error and gradient---------------
lowercase__ : int = np.multiply(
(data_teach - bp_outa) , np.multiply(lowercase_ , (1 - bp_outa) ) )
lowercase__ : str = np.multiply(
np.dot(lowercase_ , self.wkj ) , np.multiply(lowercase_ , (1 - bp_outa) ) )
lowercase__ : List[Any] = np.dot(lowercase_ , self.vji )
lowercase__ : Optional[int] = pd_i_all / (self.size_poolinga * self.size_poolinga)
lowercase__ : Tuple = pd_conva_pooled.T.getA().tolist()
lowercase__ : Any = self._calculate_gradient_from_pool(
lowercase_ , lowercase_ , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , )
# weight and threshold learning process---------
# convolution layer
for k_conv in range(self.conva[1] ):
lowercase__ : Dict = self._expand_mat(pd_conva_all[k_conv] )
lowercase__ : Union[str, Any] = self.rate_weight * np.dot(lowercase_ , lowercase_ )
lowercase__ : str = self.w_conva[k_conv] + delta_w.reshape(
(self.conva[0], self.conva[0]) )
lowercase__ : Optional[Any] = (
self.thre_conva[k_conv]
- np.sum(pd_conva_all[k_conv] ) * self.rate_thre
)
# all connected layer
lowercase__ : Optional[int] = self.wkj + pd_k_all.T * bp_outa * self.rate_weight
lowercase__ : int = self.vji + pd_j_all.T * bp_outa * self.rate_weight
lowercase__ : List[Any] = self.thre_bpa - pd_k_all * self.rate_thre
lowercase__ : Union[str, Any] = self.thre_bpa - pd_j_all * self.rate_thre
# calculate the sum error of all single image
lowercase__ : Any = np.sum(abs(data_teach - bp_outa ) )
error_count += errors
# print(' ----Teach ',data_teach)
# print(' ----BP_output ',bp_out3)
lowercase__ : Dict = rp + 1
lowercase__ : Any = error_count / patterns
all_mse.append(lowercase_ )
def draw_error():
lowercase__ : str = [error_accuracy for i in range(int(n_repeat * 1.2 ) )]
plt.plot(lowercase_ , "+-" )
plt.plot(lowercase_ , "r--" )
plt.xlabel("Learning Times" )
plt.ylabel("All_mse" )
plt.grid(lowercase_ , alpha=0.5 )
plt.show()
print("------------------Training Complished---------------------" )
print((" - - Training epoch: ", rp, f""" - - Mse: {mse:.6f}""") )
if draw_e:
draw_error()
return mse
def __a ( self , lowerCamelCase ) -> int:
"""simple docstring"""
lowercase__ : List[Any] = []
print("-------------------Start Testing-------------------------" )
print((" - - Shape: Test_Data ", np.shape(lowercase_ )) )
for p in range(len(lowercase_ ) ):
lowercase__ : Any = np.asmatrix(datas_test[p] )
lowercase__ : Any = self.convolute(
lowercase_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
lowercase__ : List[str] = self.pooling(lowercase_ , self.size_poolinga )
lowercase__ : List[Any] = self._expand(lowercase_ )
lowercase__ : str = data_bp_input
lowercase__ : int = bp_outa * self.vji.T - self.thre_bpa
lowercase__ : Union[str, Any] = self.sig(lowercase_ )
lowercase__ : Tuple = bp_outa * self.wkj.T - self.thre_bpa
lowercase__ : Any = self.sig(lowercase_ )
produce_out.extend(bp_outa.getA().tolist() )
lowercase__ : List[Any] = [list(map(self.do_round , lowercase_ ) ) for each in produce_out]
return np.asarray(lowercase_ )
def __a ( self , lowerCamelCase ) -> Union[str, Any]:
"""simple docstring"""
lowercase__ : str = np.asmatrix(lowercase_ )
lowercase__ : Optional[int] = self.convolute(
lowercase_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
lowercase__ : Dict = self.pooling(lowercase_ , self.size_poolinga )
return data_conveda, data_pooleda
if __name__ == "__main__":
pass
| 708 |
import os
import zipfile
import pytest
from datasets.utils.extract import (
BzipaExtractor,
Extractor,
GzipExtractor,
LzaExtractor,
SevenZipExtractor,
TarExtractor,
XzExtractor,
ZipExtractor,
ZstdExtractor,
)
from .utils import require_lza, require_pyazr, require_zstandard
@pytest.mark.parametrize(
"compression_format, is_archive" ,[
("7z", True),
("bz2", False),
("gzip", False),
("lz4", False),
("tar", True),
("xz", False),
("zip", True),
("zstd", False),
] ,)
def snake_case_ ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,) -> List[Any]:
lowercase__ : List[str] = {
"7z": (seven_zip_file, SevenZipExtractor),
"bz2": (bza_file, BzipaExtractor),
"gzip": (gz_file, GzipExtractor),
"lz4": (lza_file, LzaExtractor),
"tar": (tar_file, TarExtractor),
"xz": (xz_file, XzExtractor),
"zip": (zip_file, ZipExtractor),
"zstd": (zstd_file, ZstdExtractor),
}
lowercase__ , lowercase__ : Tuple = input_paths_and_base_extractors[compression_format]
if input_path is None:
lowercase__ : List[Any] = F"""for '{compression_format}' compression_format, """
if compression_format == "7z":
reason += require_pyazr.kwargs["reason"]
elif compression_format == "lz4":
reason += require_lza.kwargs["reason"]
elif compression_format == "zstd":
reason += require_zstandard.kwargs["reason"]
pytest.skip(SCREAMING_SNAKE_CASE_ )
assert base_extractor.is_extractable(SCREAMING_SNAKE_CASE_ )
lowercase__ : str = tmp_path / ("extracted" if is_archive else "extracted.txt")
base_extractor.extract(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
if is_archive:
assert output_path.is_dir()
for file_path in output_path.iterdir():
assert file_path.name == text_file.name
lowercase__ : Tuple = file_path.read_text(encoding="utf-8" )
else:
lowercase__ : List[str] = output_path.read_text(encoding="utf-8" )
lowercase__ : Dict = text_file.read_text(encoding="utf-8" )
assert extracted_file_content == expected_file_content
@pytest.mark.parametrize(
"compression_format, is_archive" ,[
("7z", True),
("bz2", False),
("gzip", False),
("lz4", False),
("tar", True),
("xz", False),
("zip", True),
("zstd", False),
] ,)
def snake_case_ ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,) -> Optional[Any]:
lowercase__ : Optional[Any] = {
"7z": seven_zip_file,
"bz2": bza_file,
"gzip": gz_file,
"lz4": lza_file,
"tar": tar_file,
"xz": xz_file,
"zip": zip_file,
"zstd": zstd_file,
}
lowercase__ : List[Any] = input_paths[compression_format]
if input_path is None:
lowercase__ : Union[str, Any] = F"""for '{compression_format}' compression_format, """
if compression_format == "7z":
reason += require_pyazr.kwargs["reason"]
elif compression_format == "lz4":
reason += require_lza.kwargs["reason"]
elif compression_format == "zstd":
reason += require_zstandard.kwargs["reason"]
pytest.skip(SCREAMING_SNAKE_CASE_ )
lowercase__ : List[Any] = Extractor.infer_extractor_format(SCREAMING_SNAKE_CASE_ )
assert extractor_format is not None
lowercase__ : Optional[int] = tmp_path / ("extracted" if is_archive else "extracted.txt")
Extractor.extract(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
if is_archive:
assert output_path.is_dir()
for file_path in output_path.iterdir():
assert file_path.name == text_file.name
lowercase__ : Tuple = file_path.read_text(encoding="utf-8" )
else:
lowercase__ : Dict = output_path.read_text(encoding="utf-8" )
lowercase__ : Optional[Any] = text_file.read_text(encoding="utf-8" )
assert extracted_file_content == expected_file_content
@pytest.fixture
def snake_case_ ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) -> int:
import tarfile
lowercase__ : Any = tmp_path / "data_dot_dot"
directory.mkdir()
lowercase__ : Union[str, Any] = directory / "tar_file_with_dot_dot.tar"
with tarfile.TarFile(SCREAMING_SNAKE_CASE_ ,"w" ) as f:
f.add(SCREAMING_SNAKE_CASE_ ,arcname=os.path.join(".." ,text_file.name ) )
return path
@pytest.fixture
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> int:
import tarfile
lowercase__ : List[str] = tmp_path / "data_sym_link"
directory.mkdir()
lowercase__ : Tuple = directory / "tar_file_with_sym_link.tar"
os.symlink(".." ,directory / "subdir" ,target_is_directory=SCREAMING_SNAKE_CASE_ )
with tarfile.TarFile(SCREAMING_SNAKE_CASE_ ,"w" ) as f:
f.add(str(directory / "subdir" ) ,arcname="subdir" ) # str required by os.readlink on Windows and Python < 3.8
return path
@pytest.mark.parametrize(
"insecure_tar_file, error_log" ,[("tar_file_with_dot_dot", "illegal path"), ("tar_file_with_sym_link", "Symlink")] ,)
def snake_case_ ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) -> Tuple:
lowercase__ : Dict = {
"tar_file_with_dot_dot": tar_file_with_dot_dot,
"tar_file_with_sym_link": tar_file_with_sym_link,
}
lowercase__ : Dict = insecure_tar_files[insecure_tar_file]
lowercase__ : Optional[int] = tmp_path / "extracted"
TarExtractor.extract(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
assert caplog.text
for record in caplog.records:
assert record.levelname == "ERROR"
assert error_log in record.msg
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> List[Any]:
# We should have less false positives than zipfile.is_zipfile
# We do that by checking only the magic number
lowercase__ : Dict = tmpdir / "not_a_zip_file"
# From: https://github.com/python/cpython/pull/5053
lowercase__ : str = (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00"
b"\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6'\x00\x00\x00\x15I"
b"DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07"
b"\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82"
)
with not_a_zip_file.open("wb" ) as f:
f.write(SCREAMING_SNAKE_CASE_ )
assert zipfile.is_zipfile(str(SCREAMING_SNAKE_CASE_ ) ) # is a false positive for `zipfile`
assert not ZipExtractor.is_extractable(SCREAMING_SNAKE_CASE_ ) # but we're right
| 298 | 0 |
"""simple docstring"""
import argparse
import os
import re
import torch
from flax.traverse_util import flatten_dict
from tax import checkpoints
from transformers import (
AutoTokenizer,
PixaStructConfig,
PixaStructForConditionalGeneration,
PixaStructImageProcessor,
PixaStructProcessor,
PixaStructTextConfig,
PixaStructVisionConfig,
)
def UpperCAmelCase__ (lowerCAmelCase_ ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ )
return flax_params
def UpperCAmelCase__ (lowerCAmelCase_ ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = {}
__SCREAMING_SNAKE_CASE = {
"token_embedder": "embeddings",
"encoder_norm": "layernorm",
"kernel": "weight",
".out": ".output",
"scale": "weight",
"embedders_0.pos_embedding": "row_embedder.weight",
"embedders_1.pos_embedding": "column_embedder.weight",
}
__SCREAMING_SNAKE_CASE = {
"query": "attention.query",
"key": "attention.key",
"value": "attention.value",
"output.dense": "output",
"encoder_decoder_attention.o": "encoder_decoder_attention.attention.o",
"pre_self_attention_layer_norm": "self_attention.layer_norm",
"pre_cross_attention_layer_norm": "encoder_decoder_attention.layer_norm",
"mlp.": "mlp.DenseReluDense.",
"pre_mlp_layer_norm": "mlp.layer_norm",
"self_attention.o": "self_attention.attention.o",
"decoder.embeddings.embedding": "decoder.embed_tokens.weight",
"decoder.relpos_bias.rel_embedding": "decoder.layer.0.self_attention.attention.relative_attention_bias.weight",
"decoder.decoder_norm.weight": "decoder.final_layer_norm.weight",
"decoder.logits_dense.weight": "decoder.lm_head.weight",
}
for key in flax_dict.keys():
if "target" in key:
# remove the first prefix from the key
__SCREAMING_SNAKE_CASE = ".".join(key[1:] )
# rename the key
for old, new in CONVERSION_MAPPING.items():
__SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ )
if "decoder" in new_key:
for old, new in DECODER_CONVERSION_MAPPING.items():
__SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ )
if "layers" in new_key and "decoder" not in new_key:
# use regex to replace the layer number
__SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = new_key.replace("encoder" , "encoder.encoder" )
elif "layers" in new_key and "decoder" in new_key:
# use regex to replace the layer number
__SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = flax_dict[key]
__SCREAMING_SNAKE_CASE = {}
# convert converted_dict into torch format
for key in converted_dict.keys():
if ("embed_tokens" not in key) and ("embedder" not in key):
__SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key].T )
else:
__SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key] )
return converted_torch_dict
def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=False ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = get_flax_param(lowerCAmelCase_ )
if not use_large:
__SCREAMING_SNAKE_CASE = PixaStructVisionConfig()
__SCREAMING_SNAKE_CASE = PixaStructTextConfig()
else:
__SCREAMING_SNAKE_CASE = PixaStructVisionConfig(
hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 )
__SCREAMING_SNAKE_CASE = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 )
__SCREAMING_SNAKE_CASE = PixaStructConfig(
vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = PixaStructForConditionalGeneration(lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = rename_and_convert_flax_params(lowerCAmelCase_ )
model.load_state_dict(lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("ybelkada/test-pix2struct-tokenizer" )
__SCREAMING_SNAKE_CASE = PixaStructImageProcessor()
__SCREAMING_SNAKE_CASE = PixaStructProcessor(image_processor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ )
if use_large:
__SCREAMING_SNAKE_CASE = 4096
__SCREAMING_SNAKE_CASE = True
# mkdir if needed
os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ )
model.save_pretrained(lowerCAmelCase_ )
processor.save_pretrained(lowerCAmelCase_ )
print("Model saved in {}".format(lowerCAmelCase_ ) )
if __name__ == "__main__":
a__ : Optional[int] = argparse.ArgumentParser()
parser.add_argument('''--t5x_checkpoint_path''', default=None, type=str, help='''Path to the original T5x checkpoint.''')
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument('''--use_large''', action='''store_true''', help='''Use large model.''')
parser.add_argument('''--is_vqa''', action='''store_true''', help='''Use large model.''')
a__ : Optional[Any] = parser.parse_args()
convert_pixastruct_original_pytorch_checkpoint_to_hf(
args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large
)
| 682 |
"""simple docstring"""
import json
import os
import unittest
from transformers.models.roc_bert.tokenization_roc_bert import (
VOCAB_FILES_NAMES,
RoCBertBasicTokenizer,
RoCBertTokenizer,
RoCBertWordpieceTokenizer,
_is_control,
_is_punctuation,
_is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english
@require_tokenizers
class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase):
"""simple docstring"""
snake_case__ : int = RoCBertTokenizer
snake_case__ : int = None
snake_case__ : Optional[Any] = False
snake_case__ : int = True
snake_case__ : Any = filter_non_english
def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]:
super().setUp()
__SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"]
__SCREAMING_SNAKE_CASE = {}
__SCREAMING_SNAKE_CASE = {}
for i, value in enumerate(UpperCAmelCase__ ):
__SCREAMING_SNAKE_CASE = i
__SCREAMING_SNAKE_CASE = i
__SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
__SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] )
__SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) )
with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer:
json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ )
with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer:
json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ )
def UpperCAmelCase_ ( self : Any ) -> List[str]:
__SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file )
__SCREAMING_SNAKE_CASE = tokenizer.tokenize("你好[SEP]你是谁" )
self.assertListEqual(UpperCAmelCase__ , ["你", "好", "[SEP]", "你", "是", "谁"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] )
self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] )
self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] )
def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]:
__SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer()
self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] )
def UpperCAmelCase_ ( self : int ) -> Union[str, Any]:
__SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] )
def UpperCAmelCase_ ( self : Dict ) -> Dict:
__SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] )
def UpperCAmelCase_ ( self : int ) -> Dict:
__SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] )
def UpperCAmelCase_ ( self : Any ) -> Optional[int]:
__SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] )
def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]:
__SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] )
def UpperCAmelCase_ ( self : int ) -> Optional[Any]:
__SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] )
def UpperCAmelCase_ ( self : int ) -> List[Any]:
__SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] )
def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]:
__SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=["[UNK]"] )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] )
def UpperCAmelCase_ ( self : str ) -> List[str]:
__SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]
__SCREAMING_SNAKE_CASE = {}
for i, token in enumerate(UpperCAmelCase__ ):
__SCREAMING_SNAKE_CASE = i
__SCREAMING_SNAKE_CASE = RoCBertWordpieceTokenizer(vocab=UpperCAmelCase__ , unk_token="[UNK]" )
self.assertListEqual(tokenizer.tokenize("" ) , [] )
self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] )
self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] )
def UpperCAmelCase_ ( self : List[Any] ) -> str:
self.assertTrue(_is_whitespace(" " ) )
self.assertTrue(_is_whitespace("\t" ) )
self.assertTrue(_is_whitespace("\r" ) )
self.assertTrue(_is_whitespace("\n" ) )
self.assertTrue(_is_whitespace("\u00A0" ) )
self.assertFalse(_is_whitespace("A" ) )
self.assertFalse(_is_whitespace("-" ) )
def UpperCAmelCase_ ( self : List[Any] ) -> List[str]:
self.assertTrue(_is_control("\u0005" ) )
self.assertFalse(_is_control("A" ) )
self.assertFalse(_is_control(" " ) )
self.assertFalse(_is_control("\t" ) )
self.assertFalse(_is_control("\r" ) )
def UpperCAmelCase_ ( self : List[str] ) -> Tuple:
self.assertTrue(_is_punctuation("-" ) )
self.assertTrue(_is_punctuation("$" ) )
self.assertTrue(_is_punctuation("`" ) )
self.assertTrue(_is_punctuation("." ) )
self.assertFalse(_is_punctuation("A" ) )
self.assertFalse(_is_punctuation(" " ) )
def UpperCAmelCase_ ( self : int ) -> int:
__SCREAMING_SNAKE_CASE = self.get_tokenizer()
# Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] )
if self.test_rust_tokenizer:
__SCREAMING_SNAKE_CASE = self.get_rust_tokenizer()
self.assertListEqual(
[rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] )
def UpperCAmelCase_ ( self : Tuple ) -> List[Any]:
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
__SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence."""
__SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus(
UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , )
__SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , "do_lower_case" ) else False
__SCREAMING_SNAKE_CASE = (
[
((0, 0), tokenizer_r.cls_token),
((0, 1), "A"),
((1, 2), ","),
((3, 5), "na"),
((5, 6), "##ï"),
((6, 8), "##ve"),
((9, 1_5), tokenizer_r.mask_token),
((1_6, 2_1), "Allen"),
((2_1, 2_3), "##NL"),
((2_3, 2_4), "##P"),
((2_5, 3_3), "sentence"),
((3_3, 3_4), "."),
((0, 0), tokenizer_r.sep_token),
]
if not do_lower_case
else [
((0, 0), tokenizer_r.cls_token),
((0, 1), "a"),
((1, 2), ","),
((3, 8), "naive"),
((9, 1_5), tokenizer_r.mask_token),
((1_6, 2_1), "allen"),
((2_1, 2_3), "##nl"),
((2_3, 2_4), "##p"),
((2_5, 3_3), "sentence"),
((3_3, 3_4), "."),
((0, 0), tokenizer_r.sep_token),
]
)
self.assertEqual(
[e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) )
self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] )
def UpperCAmelCase_ ( self : Tuple ) -> Dict:
__SCREAMING_SNAKE_CASE = ["的", "人", "有"]
__SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ )
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
__SCREAMING_SNAKE_CASE = True
__SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ )
# it is expected that each Chinese character is not preceded by "##"
self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ )
self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ )
# it is expected that only the first Chinese character is not preceded by "##".
__SCREAMING_SNAKE_CASE = [
F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ )
]
self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ )
self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ )
@slow
def UpperCAmelCase_ ( self : List[Any] ) -> Tuple:
__SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file )
__SCREAMING_SNAKE_CASE = tokenizer.encode("你好" , add_special_tokens=UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer.encode("你是谁" , add_special_tokens=UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ )
assert encoded_sentence == [1] + text + [2]
assert encoded_pair == [1] + text + [2] + text_a + [2]
def UpperCAmelCase_ ( self : str ) -> Optional[Any]:
__SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=UpperCAmelCase__ )
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
__SCREAMING_SNAKE_CASE = "你好,你是谁"
__SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer.prepare_for_model(
UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = tokenizer.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ )
self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
| 682 | 1 |
import heapq
def _lowerCamelCase ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
A_ = []
# for each node and his adjacency list add them and the rank of the node to queue
# using heapq module the queue will be filled like a Priority Queue
# heapq works with a min priority queue, so I used -1*len(v) to build it
for key, value in graph.items():
# O(log(n))
heapq.heappush(SCREAMING_SNAKE_CASE , [-1 * len(SCREAMING_SNAKE_CASE ), (key, value)] )
# chosen_vertices = set of chosen vertices
A_ = set()
# while queue isn't empty and there are still edges
# (queue[0][0] is the rank of the node with max rank)
while queue and queue[0][0] != 0:
# extract vertex with max rank from queue and add it to chosen_vertices
A_ = heapq.heappop(SCREAMING_SNAKE_CASE )[1][0]
chosen_vertices.add(SCREAMING_SNAKE_CASE )
# Remove all arcs adjacent to argmax
for elem in queue:
# if v haven't adjacent node, skip
if elem[0] == 0:
continue
# if argmax is reachable from elem
# remove argmax from elem's adjacent list and update his rank
if argmax in elem[1][1]:
A_ = elem[1][1].index(SCREAMING_SNAKE_CASE )
del elem[1][1][index]
elem[0] += 1
# re-order the queue
heapq.heapify(SCREAMING_SNAKE_CASE )
return chosen_vertices
if __name__ == "__main__":
import doctest
doctest.testmod()
__lowercase = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]}
print(f'Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}')
| 563 |
from __future__ import annotations
def _lowerCamelCase ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
if len(SCREAMING_SNAKE_CASE ) == 0:
return []
A_ ,A_ = min(SCREAMING_SNAKE_CASE ), max(SCREAMING_SNAKE_CASE )
A_ = int(max_value - min_value ) + 1
A_ = [[] for _ in range(SCREAMING_SNAKE_CASE )]
for i in my_list:
buckets[int(i - min_value )].append(SCREAMING_SNAKE_CASE )
return [v for bucket in buckets for v in sorted(SCREAMING_SNAKE_CASE )]
if __name__ == "__main__":
from doctest import testmod
testmod()
assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5]
assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
| 563 | 1 |
'''simple docstring'''
from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import (
ImageTextPipelineOutput,
UniDiffuserPipeline,
)
else:
from .modeling_text_decoder import UniDiffuserTextDecoder
from .modeling_uvit import UniDiffuserModel, UTransformeraDModel
from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
| 5 |
'''simple docstring'''
from __future__ import annotations
import numpy as np
def UpperCamelCase__ ( lowerCAmelCase ):
"""simple docstring"""
_lowerCAmelCase , _lowerCAmelCase = np.shape(lowerCAmelCase )
if rows != columns:
_lowerCAmelCase = (
"""'table' has to be of square shaped array but got a """
f"{rows}x{columns} array:\n{table}"
)
raise ValueError(lowerCAmelCase )
_lowerCAmelCase = np.zeros((rows, columns) )
_lowerCAmelCase = np.zeros((rows, columns) )
for i in range(lowerCAmelCase ):
for j in range(lowerCAmelCase ):
_lowerCAmelCase = sum(lower[i][k] * upper[k][j] for k in range(lowerCAmelCase ) )
if upper[j][j] == 0:
raise ArithmeticError("""No LU decomposition exists""" )
_lowerCAmelCase = (table[i][j] - total) / upper[j][j]
_lowerCAmelCase = 1
for j in range(lowerCAmelCase , lowerCAmelCase ):
_lowerCAmelCase = sum(lower[i][k] * upper[k][j] for k in range(lowerCAmelCase ) )
_lowerCAmelCase = table[i][j] - total
return lower, upper
if __name__ == "__main__":
import doctest
doctest.testmod()
| 207 | 0 |
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel
if is_vision_available():
from transformers import MaskFormerImageProcessor
if is_vision_available():
from PIL import Image
class __snake_case :
def __init__( self : Dict , _lowercase : List[str] , _lowercase : int=2 , _lowercase : Optional[Any]=True , _lowercase : Optional[int]=False , _lowercase : Tuple=10 , _lowercase : Tuple=3 , _lowercase : Union[str, Any]=32 * 4 , _lowercase : Any=32 * 6 , _lowercase : Any=4 , _lowercase : Any=32 , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = parent
SCREAMING_SNAKE_CASE__ = batch_size
SCREAMING_SNAKE_CASE__ = is_training
SCREAMING_SNAKE_CASE__ = use_auxiliary_loss
SCREAMING_SNAKE_CASE__ = num_queries
SCREAMING_SNAKE_CASE__ = num_channels
SCREAMING_SNAKE_CASE__ = min_size
SCREAMING_SNAKE_CASE__ = max_size
SCREAMING_SNAKE_CASE__ = num_labels
SCREAMING_SNAKE_CASE__ = mask_feature_size
def __a ( self : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
_lowercase )
SCREAMING_SNAKE_CASE__ = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowercase )
SCREAMING_SNAKE_CASE__ = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowercase ) > 0.5
).float()
SCREAMING_SNAKE_CASE__ = (torch.rand((self.batch_size, self.num_labels) , device=_lowercase ) > 0.5).long()
SCREAMING_SNAKE_CASE__ = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def __a ( self : List[Any] ):
"""simple docstring"""
return MaskFormerConfig.from_backbone_and_decoder_configs(
backbone_config=SwinConfig(
depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
decoder_ffn_dim=1_28 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
def __a ( self : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ = {"pixel_values": pixel_values, "pixel_mask": pixel_mask}
return config, inputs_dict
def __a ( self : Union[str, Any] , _lowercase : Optional[Any] , _lowercase : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = output.encoder_hidden_states
SCREAMING_SNAKE_CASE__ = output.pixel_decoder_hidden_states
SCREAMING_SNAKE_CASE__ = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(_lowercase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowercase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowercase ) , config.decoder_config.decoder_layers )
def __a ( self : Dict , _lowercase : Optional[Any] , _lowercase : Dict , _lowercase : Union[str, Any] , _lowercase : List[Any]=False ):
"""simple docstring"""
with torch.no_grad():
SCREAMING_SNAKE_CASE__ = MaskFormerModel(config=_lowercase )
model.to(_lowercase )
model.eval()
SCREAMING_SNAKE_CASE__ = model(pixel_values=_lowercase , pixel_mask=_lowercase )
SCREAMING_SNAKE_CASE__ = model(_lowercase , output_hidden_states=_lowercase )
# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
# encoder and pixel decoder
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(_lowercase , _lowercase )
def __a ( self : Optional[Any] , _lowercase : Any , _lowercase : Any , _lowercase : List[str] , _lowercase : List[Any] , _lowercase : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = MaskFormerForInstanceSegmentation(config=_lowercase )
model.to(_lowercase )
model.eval()
def comm_check_on_output(_lowercase : List[str] ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
SCREAMING_SNAKE_CASE__ = model(pixel_values=_lowercase , pixel_mask=_lowercase )
SCREAMING_SNAKE_CASE__ = model(_lowercase )
comm_check_on_output(_lowercase )
SCREAMING_SNAKE_CASE__ = model(
pixel_values=_lowercase , pixel_mask=_lowercase , mask_labels=_lowercase , class_labels=_lowercase )
comm_check_on_output(_lowercase )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape , torch.Size([1] ) )
@require_torch
class __snake_case ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
lowerCAmelCase_ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
lowerCAmelCase_ = (
{"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation}
if is_torch_available()
else {}
)
lowerCAmelCase_ = False
lowerCAmelCase_ = False
lowerCAmelCase_ = False
lowerCAmelCase_ = False
def __a ( self : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = MaskFormerModelTester(self )
SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=_lowercase , has_text_modality=_lowercase )
def __a ( self : Optional[Any] ):
"""simple docstring"""
self.config_tester.run_common_tests()
def __a ( self : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowercase , **_lowercase , output_hidden_states=_lowercase )
def __a ( self : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowercase )
@unittest.skip(reason="""MaskFormer does not use inputs_embeds""" )
def __a ( self : Optional[int] ):
"""simple docstring"""
pass
@unittest.skip(reason="""MaskFormer does not have a get_input_embeddings method""" )
def __a ( self : Optional[int] ):
"""simple docstring"""
pass
@unittest.skip(reason="""MaskFormer is not a generative model""" )
def __a ( self : Union[str, Any] ):
"""simple docstring"""
pass
@unittest.skip(reason="""MaskFormer does not use token embeddings""" )
def __a ( self : Optional[Any] ):
"""simple docstring"""
pass
@require_torch_multi_gpu
@unittest.skip(
reason="""MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" )
def __a ( self : Tuple ):
"""simple docstring"""
pass
@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" )
def __a ( self : List[str] ):
"""simple docstring"""
pass
def __a ( self : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE__ = model_class(_lowercase )
SCREAMING_SNAKE_CASE__ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
SCREAMING_SNAKE_CASE__ = [*signature.parameters.keys()]
SCREAMING_SNAKE_CASE__ = ["pixel_values"]
self.assertListEqual(arg_names[:1] , _lowercase )
@slow
def __a ( self : Any ):
"""simple docstring"""
for model_name in ["facebook/maskformer-swin-small-coco"]:
SCREAMING_SNAKE_CASE__ = MaskFormerModel.from_pretrained(_lowercase )
self.assertIsNotNone(_lowercase )
def __a ( self : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = (self.model_tester.min_size,) * 2
SCREAMING_SNAKE_CASE__ = {
"pixel_values": torch.randn((2, 3, *size) , device=_lowercase ),
"mask_labels": torch.randn((2, 10, *size) , device=_lowercase ),
"class_labels": torch.zeros(2 , 10 , device=_lowercase ).long(),
}
SCREAMING_SNAKE_CASE__ = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowercase )
SCREAMING_SNAKE_CASE__ = model(**_lowercase )
self.assertTrue(outputs.loss is not None )
def __a ( self : Dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowercase , **_lowercase , output_hidden_states=_lowercase )
def __a ( self : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE__ = model_class(_lowercase ).to(_lowercase )
SCREAMING_SNAKE_CASE__ = model(**_lowercase , output_attentions=_lowercase )
self.assertTrue(outputs.attentions is not None )
def __a ( self : str ):
"""simple docstring"""
if not self.model_tester.is_training:
return
# only MaskFormerForInstanceSegmentation has the loss
SCREAMING_SNAKE_CASE__ = self.all_model_classes[1]
SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ = model_class(_lowercase )
model.to(_lowercase )
model.train()
SCREAMING_SNAKE_CASE__ = model(_lowercase , mask_labels=_lowercase , class_labels=_lowercase ).loss
loss.backward()
def __a ( self : Dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = self.all_model_classes[1]
SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ = True
SCREAMING_SNAKE_CASE__ = True
SCREAMING_SNAKE_CASE__ = model_class(_lowercase )
model.to(_lowercase )
model.train()
SCREAMING_SNAKE_CASE__ = model(_lowercase , mask_labels=_lowercase , class_labels=_lowercase )
SCREAMING_SNAKE_CASE__ = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
SCREAMING_SNAKE_CASE__ = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
SCREAMING_SNAKE_CASE__ = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
SCREAMING_SNAKE_CASE__ = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=_lowercase )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
__lowerCamelCase : Union[str, Any] = 1e-4
def __SCREAMING_SNAKE_CASE ( ) -> List[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
return image
@require_vision
@slow
class __snake_case ( unittest.TestCase ):
@cached_property
def __a ( self : int ):
"""simple docstring"""
return (
MaskFormerImageProcessor.from_pretrained("""facebook/maskformer-swin-small-coco""" )
if is_vision_available()
else None
)
def __a ( self : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = MaskFormerModel.from_pretrained("""facebook/maskformer-swin-small-coco""" ).to(_lowercase )
SCREAMING_SNAKE_CASE__ = self.default_image_processor
SCREAMING_SNAKE_CASE__ = prepare_img()
SCREAMING_SNAKE_CASE__ = image_processor(_lowercase , return_tensors="""pt""" ).to(_lowercase )
SCREAMING_SNAKE_CASE__ = inputs["pixel_values"].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(_lowercase , (1, 3, 8_00, 10_88) )
with torch.no_grad():
SCREAMING_SNAKE_CASE__ = model(**_lowercase )
SCREAMING_SNAKE_CASE__ = torch.tensor(
[[-0.04_82, 0.92_28, 0.49_51], [-0.25_47, 0.80_17, 0.85_27], [-0.00_69, 0.33_85, -0.00_89]] ).to(_lowercase )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowercase , atol=_lowercase ) )
SCREAMING_SNAKE_CASE__ = torch.tensor(
[[-0.84_22, -0.84_34, -0.97_18], [-1.01_44, -0.55_65, -0.41_95], [-1.00_38, -0.44_84, -0.19_61]] ).to(_lowercase )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowercase , atol=_lowercase ) )
SCREAMING_SNAKE_CASE__ = torch.tensor(
[[0.28_52, -0.01_59, 0.97_35], [0.62_54, 0.18_58, 0.85_29], [-0.06_80, -0.41_16, 1.84_13]] ).to(_lowercase )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowercase , atol=_lowercase ) )
def __a ( self : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = (
MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-swin-small-coco""" )
.to(_lowercase )
.eval()
)
SCREAMING_SNAKE_CASE__ = self.default_image_processor
SCREAMING_SNAKE_CASE__ = prepare_img()
SCREAMING_SNAKE_CASE__ = image_processor(_lowercase , return_tensors="""pt""" ).to(_lowercase )
SCREAMING_SNAKE_CASE__ = inputs["pixel_values"].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(_lowercase , (1, 3, 8_00, 10_88) )
with torch.no_grad():
SCREAMING_SNAKE_CASE__ = model(**_lowercase )
# masks_queries_logits
SCREAMING_SNAKE_CASE__ = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
SCREAMING_SNAKE_CASE__ = [
[-1.3_73_71_24, -1.7_72_49_37, -1.9_36_42_33],
[-1.5_97_72_81, -1.9_86_79_39, -2.1_52_36_95],
[-1.5_79_53_98, -1.9_26_98_32, -2.09_39_42],
]
SCREAMING_SNAKE_CASE__ = torch.tensor(_lowercase ).to(_lowercase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowercase , atol=_lowercase ) )
# class_queries_logits
SCREAMING_SNAKE_CASE__ = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
SCREAMING_SNAKE_CASE__ = torch.tensor(
[
[1.6512E00, -5.2572E00, -3.3519E00],
[3.6169E-02, -5.9025E00, -2.9313E00],
[1.0766E-04, -7.7630E00, -5.1263E00],
] ).to(_lowercase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowercase , atol=_lowercase ) )
def __a ( self : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = (
MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-resnet101-coco-stuff""" )
.to(_lowercase )
.eval()
)
SCREAMING_SNAKE_CASE__ = self.default_image_processor
SCREAMING_SNAKE_CASE__ = prepare_img()
SCREAMING_SNAKE_CASE__ = image_processor(_lowercase , return_tensors="""pt""" ).to(_lowercase )
SCREAMING_SNAKE_CASE__ = inputs["pixel_values"].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(_lowercase , (1, 3, 8_00, 10_88) )
with torch.no_grad():
SCREAMING_SNAKE_CASE__ = model(**_lowercase )
# masks_queries_logits
SCREAMING_SNAKE_CASE__ = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
SCREAMING_SNAKE_CASE__ = [[-0.90_46, -2.63_66, -4.60_62], [-3.41_79, -5.78_90, -8.80_57], [-4.91_79, -7.65_60, -10.77_11]]
SCREAMING_SNAKE_CASE__ = torch.tensor(_lowercase ).to(_lowercase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowercase , atol=_lowercase ) )
# class_queries_logits
SCREAMING_SNAKE_CASE__ = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
SCREAMING_SNAKE_CASE__ = torch.tensor(
[[4.71_88, -3.25_85, -2.88_57], [6.68_71, -2.91_81, -1.24_87], [7.24_49, -2.27_64, -2.18_74]] ).to(_lowercase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowercase , atol=_lowercase ) )
def __a ( self : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = (
MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-swin-small-coco""" )
.to(_lowercase )
.eval()
)
SCREAMING_SNAKE_CASE__ = self.default_image_processor
SCREAMING_SNAKE_CASE__ = image_processor(
[np.zeros((3, 8_00, 13_33) ), np.zeros((3, 8_00, 13_33) )] , segmentation_maps=[np.zeros((3_84, 3_84) ).astype(np.floataa ), np.zeros((3_84, 3_84) ).astype(np.floataa )] , return_tensors="""pt""" , )
SCREAMING_SNAKE_CASE__ = inputs["pixel_values"].to(_lowercase )
SCREAMING_SNAKE_CASE__ = [el.to(_lowercase ) for el in inputs["mask_labels"]]
SCREAMING_SNAKE_CASE__ = [el.to(_lowercase ) for el in inputs["class_labels"]]
with torch.no_grad():
SCREAMING_SNAKE_CASE__ = model(**_lowercase )
self.assertTrue(outputs.loss is not None )
| 715 |
from collections.abc import Iterator, MutableMapping
from dataclasses import dataclass
from typing import Generic, TypeVar
__lowerCamelCase : List[str] = TypeVar('''KEY''')
__lowerCamelCase : int = TypeVar('''VAL''')
@dataclass(frozen=lowerCamelCase_ , slots=lowerCamelCase_ )
class __snake_case ( Generic[KEY, VAL] ):
lowerCAmelCase_ = 42
lowerCAmelCase_ = 42
class __snake_case ( _Item ):
def __init__( self : List[Any] ):
"""simple docstring"""
super().__init__(_lowercase , _lowercase )
def __bool__( self : List[str] ):
"""simple docstring"""
return False
__lowerCamelCase : str = _DeletedItem()
class __snake_case ( MutableMapping[KEY, VAL] ):
def __init__( self : Optional[int] , _lowercase : int = 8 , _lowercase : float = 0.75 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = initial_block_size
SCREAMING_SNAKE_CASE__ = [None] * initial_block_size
assert 0.0 < capacity_factor < 1.0
SCREAMING_SNAKE_CASE__ = capacity_factor
SCREAMING_SNAKE_CASE__ = 0
def __a ( self : Union[str, Any] , _lowercase : KEY ):
"""simple docstring"""
return hash(_lowercase ) % len(self._buckets )
def __a ( self : List[str] , _lowercase : int ):
"""simple docstring"""
return (ind + 1) % len(self._buckets )
def __a ( self : Union[str, Any] , _lowercase : int , _lowercase : KEY , _lowercase : VAL ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = self._buckets[ind]
if not stored:
SCREAMING_SNAKE_CASE__ = _Item(_lowercase , _lowercase )
self._len += 1
return True
elif stored.key == key:
SCREAMING_SNAKE_CASE__ = _Item(_lowercase , _lowercase )
return True
else:
return False
def __a ( self : List[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = len(self._buckets ) * self._capacity_factor
return len(self ) >= int(_lowercase )
def __a ( self : Dict ):
"""simple docstring"""
if len(self._buckets ) <= self._initial_block_size:
return False
SCREAMING_SNAKE_CASE__ = len(self._buckets ) * self._capacity_factor / 2
return len(self ) < limit
def __a ( self : List[Any] , _lowercase : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = self._buckets
SCREAMING_SNAKE_CASE__ = [None] * new_size
SCREAMING_SNAKE_CASE__ = 0
for item in old_buckets:
if item:
self._add_item(item.key , item.val )
def __a ( self : Tuple ):
"""simple docstring"""
self._resize(len(self._buckets ) * 2 )
def __a ( self : Tuple ):
"""simple docstring"""
self._resize(len(self._buckets ) // 2 )
def __a ( self : List[str] , _lowercase : KEY ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = self._get_bucket_index(_lowercase )
for _ in range(len(self._buckets ) ):
yield ind
SCREAMING_SNAKE_CASE__ = self._get_next_ind(_lowercase )
def __a ( self : List[str] , _lowercase : KEY , _lowercase : VAL ):
"""simple docstring"""
for ind in self._iterate_buckets(_lowercase ):
if self._try_set(_lowercase , _lowercase , _lowercase ):
break
def __setitem__( self : List[str] , _lowercase : KEY , _lowercase : VAL ):
"""simple docstring"""
if self._is_full():
self._size_up()
self._add_item(_lowercase , _lowercase )
def __delitem__( self : Tuple , _lowercase : KEY ):
"""simple docstring"""
for ind in self._iterate_buckets(_lowercase ):
SCREAMING_SNAKE_CASE__ = self._buckets[ind]
if item is None:
raise KeyError(_lowercase )
if item is _deleted:
continue
if item.key == key:
SCREAMING_SNAKE_CASE__ = _deleted
self._len -= 1
break
if self._is_sparse():
self._size_down()
def __getitem__( self : Tuple , _lowercase : KEY ):
"""simple docstring"""
for ind in self._iterate_buckets(_lowercase ):
SCREAMING_SNAKE_CASE__ = self._buckets[ind]
if item is None:
break
if item is _deleted:
continue
if item.key == key:
return item.val
raise KeyError(_lowercase )
def __len__( self : List[Any] ):
"""simple docstring"""
return self._len
def __iter__( self : List[str] ):
"""simple docstring"""
yield from (item.key for item in self._buckets if item)
def __repr__( self : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = """ ,""".join(
f"""{item.key}: {item.val}""" for item in self._buckets if item )
return f"""HashMap({val_string})"""
| 379 | 0 |
'''simple docstring'''
def SCREAMING_SNAKE_CASE ( a_ : str ):
__a = 0
for ch in input_str:
__a = ord(a_ )
__a = pow(2 , a_ )
# If we already turned on bit for current character's unicode
if bitmap >> ch_unicode & 1 == 1:
return False
bitmap |= ch_bit_index_on
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
| 539 |
'''simple docstring'''
import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import Audio, ClassLabel, Features
from .base import TaskTemplate
@dataclass(frozen=__magic_name__ )
class __lowercase ( __magic_name__ ):
_a = field(default="""audio-classification""" , metadata={"""include_in_asdict_even_if_is_default""": True} )
_a = Features({"""audio""": Audio()} )
_a = Features({"""labels""": ClassLabel} )
_a = "audio"
_a = "labels"
def UpperCamelCase__ ( self , UpperCamelCase ) -> Dict:
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] , UpperCamelCase ):
raise ValueError(f"Column {self.label_column} is not a ClassLabel." )
__a = copy.deepcopy(self )
__a = self.label_schema.copy()
__a = features[self.label_column]
__a = label_schema
return task_template
@property
def UpperCamelCase__ ( self ) -> Dict[str, str]:
return {
self.audio_column: "audio",
self.label_column: "labels",
}
| 539 | 1 |
'''simple docstring'''
def _a ( lowerCamelCase_ ):
snake_case : Dict =0
while len(lowerCamelCase_ ) > 1:
snake_case : Optional[Any] =0
# Consider two files with minimum cost to be merged
for _ in range(2 ):
snake_case : List[Any] =files.index(min(lowerCamelCase_ ) )
temp += files[min_index]
files.pop(lowerCamelCase_ )
files.append(lowerCamelCase_ )
optimal_merge_cost += temp
return optimal_merge_cost
if __name__ == "__main__":
import doctest
doctest.testmod()
| 136 |
'''simple docstring'''
def _a ( ):
for n in range(1 , 1_00_00_00 ):
yield n * (n + 1) // 2
def _a ( lowerCamelCase_ ):
snake_case : Optional[Any] =1
snake_case : int =2
while i * i <= n:
snake_case : Any =0
while n % i == 0:
n //= i
multiplicity += 1
divisors_count *= multiplicity + 1
i += 1
if n > 1:
divisors_count *= 2
return divisors_count
def _a ( ):
return next(i for i in triangle_number_generator() if count_divisors(lowerCamelCase_ ) > 5_00 )
if __name__ == "__main__":
print(solution())
| 136 | 1 |
'''simple docstring'''
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__ : List[Any] = logging.get_logger(__name__)
class A ( SCREAMING_SNAKE_CASE__ ):
snake_case__ :Union[str, Any] = ['pixel_values']
def __init__( self : Union[str, Any] , __magic_name__ : bool = True , __magic_name__ : Optional[Dict[str, int]] = None , __magic_name__ : PILImageResampling = PILImageResampling.BILINEAR , __magic_name__ : bool = True , __magic_name__ : Dict[str, int] = None , __magic_name__ : bool = True , __magic_name__ : Union[int, float] = 1 / 255 , __magic_name__ : bool = True , __magic_name__ : Optional[Union[float, List[float]]] = None , __magic_name__ : Optional[Union[float, List[float]]] = None , **__magic_name__ : Any , ):
"""simple docstring"""
super().__init__(**__magic_name__ )
lowerCAmelCase__ = size if size is not None else {"shortest_edge": 256}
lowerCAmelCase__ = get_size_dict(__magic_name__ , default_to_square=__magic_name__ )
lowerCAmelCase__ = crop_size if crop_size is not None else {"height": 224, "width": 224}
lowerCAmelCase__ = get_size_dict(__magic_name__ , param_name="crop_size" )
lowerCAmelCase__ = do_resize
lowerCAmelCase__ = size
lowerCAmelCase__ = resample
lowerCAmelCase__ = do_center_crop
lowerCAmelCase__ = crop_size
lowerCAmelCase__ = do_rescale
lowerCAmelCase__ = rescale_factor
lowerCAmelCase__ = do_normalize
lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD
def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : np.ndarray , __magic_name__ : Dict[str, int] , __magic_name__ : PILImageResampling = PILImageResampling.BICUBIC , __magic_name__ : Optional[Union[str, ChannelDimension]] = None , **__magic_name__ : int , ):
"""simple docstring"""
lowerCAmelCase__ = get_size_dict(__magic_name__ , default_to_square=__magic_name__ )
if "shortest_edge" not in size:
raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" )
lowerCAmelCase__ = get_resize_output_image_size(__magic_name__ , size=size["shortest_edge"] , default_to_square=__magic_name__ )
return resize(__magic_name__ , size=__magic_name__ , resample=__magic_name__ , data_format=__magic_name__ , **__magic_name__ )
def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : np.ndarray , __magic_name__ : Dict[str, int] , __magic_name__ : Optional[Union[str, ChannelDimension]] = None , **__magic_name__ : Dict , ):
"""simple docstring"""
lowerCAmelCase__ = get_size_dict(__magic_name__ )
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(__magic_name__ , size=(size["height"], size["width"]) , data_format=__magic_name__ , **__magic_name__ )
def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : np.ndarray , __magic_name__ : float , __magic_name__ : Optional[Union[str, ChannelDimension]] = None , **__magic_name__ : Union[str, Any] ):
"""simple docstring"""
return rescale(__magic_name__ , scale=__magic_name__ , data_format=__magic_name__ , **__magic_name__ )
def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : np.ndarray , __magic_name__ : Union[float, List[float]] , __magic_name__ : Union[float, List[float]] , __magic_name__ : Optional[Union[str, ChannelDimension]] = None , **__magic_name__ : Tuple , ):
"""simple docstring"""
return normalize(__magic_name__ , mean=__magic_name__ , std=__magic_name__ , data_format=__magic_name__ , **__magic_name__ )
def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : ImageInput , __magic_name__ : Optional[bool] = None , __magic_name__ : Dict[str, int] = None , __magic_name__ : PILImageResampling = None , __magic_name__ : bool = None , __magic_name__ : Dict[str, int] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[float] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[Union[float, List[float]]] = None , __magic_name__ : Optional[Union[float, List[float]]] = None , __magic_name__ : Optional[Union[str, TensorType]] = None , __magic_name__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__magic_name__ : Union[str, Any] , ):
"""simple docstring"""
lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize
lowerCAmelCase__ = size if size is not None else self.size
lowerCAmelCase__ = get_size_dict(__magic_name__ , default_to_square=__magic_name__ )
lowerCAmelCase__ = resample if resample is not None else self.resample
lowerCAmelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop
lowerCAmelCase__ = crop_size if crop_size is not None else self.crop_size
lowerCAmelCase__ = get_size_dict(__magic_name__ , param_name="crop_size" )
lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale
lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor
lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize
lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean
lowerCAmelCase__ = image_std if image_std is not None else self.image_std
lowerCAmelCase__ = make_list_of_images(__magic_name__ )
if not valid_images(__magic_name__ ):
raise ValueError(
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
"torch.Tensor, tf.Tensor or jax.ndarray." )
if do_resize and size is None:
raise ValueError("Size must be specified if do_resize is True." )
if do_center_crop and crop_size is None:
raise ValueError("Crop size must be specified if do_center_crop is True." )
if do_rescale and rescale_factor is None:
raise ValueError("Rescale factor must be specified if do_rescale is True." )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("Image mean and std must be specified if do_normalize is True." )
# All transformations expect numpy arrays.
lowerCAmelCase__ = [to_numpy_array(__magic_name__ ) for image in images]
if do_resize:
lowerCAmelCase__ = [self.resize(image=__magic_name__ , size=__magic_name__ , resample=__magic_name__ ) for image in images]
if do_center_crop:
lowerCAmelCase__ = [self.center_crop(image=__magic_name__ , size=__magic_name__ ) for image in images]
if do_rescale:
lowerCAmelCase__ = [self.rescale(image=__magic_name__ , scale=__magic_name__ ) for image in images]
if do_normalize:
lowerCAmelCase__ = [self.normalize(image=__magic_name__ , mean=__magic_name__ , std=__magic_name__ ) for image in images]
lowerCAmelCase__ = [to_channel_dimension_format(__magic_name__ , __magic_name__ ) for image in images]
lowerCAmelCase__ = {"pixel_values": images}
return BatchFeature(data=__magic_name__ , tensor_type=__magic_name__ )
def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : Tuple , __magic_name__ : List[Tuple] = None ):
"""simple docstring"""
lowerCAmelCase__ = outputs.logits
# Resize logits and compute semantic segmentation maps
if target_sizes is not None:
if len(__magic_name__ ) != len(__magic_name__ ):
raise ValueError(
"Make sure that you pass in as many target sizes as the batch dimension of the logits" )
if is_torch_tensor(__magic_name__ ):
lowerCAmelCase__ = target_sizes.numpy()
lowerCAmelCase__ = []
for idx in range(len(__magic_name__ ) ):
lowerCAmelCase__ = torch.nn.functional.interpolate(
logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=__magic_name__ )
lowerCAmelCase__ = resized_logits[0].argmax(dim=0 )
semantic_segmentation.append(__magic_name__ )
else:
lowerCAmelCase__ = logits.argmax(dim=1 )
lowerCAmelCase__ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )]
return semantic_segmentation
| 48 |
"""simple docstring"""
import os
import pickle
import unittest
from transformers import AutoTokenizer
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.models.bert_japanese.tokenization_bert_japanese import (
VOCAB_FILES_NAMES,
BertJapaneseTokenizer,
CharacterTokenizer,
JumanppTokenizer,
MecabTokenizer,
SudachiTokenizer,
WordpieceTokenizer,
)
from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi
from ...test_tokenization_common import TokenizerTesterMixin
@custom_tokenizers
class lowerCamelCase (A__ ,unittest.TestCase ):
lowerCamelCase__ : Union[str, Any] = BertJapaneseTokenizer
lowerCamelCase__ : str = False
lowerCamelCase__ : Optional[int] = True
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str:
super().setUp()
SCREAMING_SNAKE_CASE__ = [
"""[UNK]""",
"""[CLS]""",
"""[SEP]""",
"""こんにちは""",
"""こん""",
"""にちは""",
"""ばんは""",
"""##こん""",
"""##にちは""",
"""##ばんは""",
"""世界""",
"""##世界""",
"""、""",
"""##、""",
"""。""",
"""##。""",
]
SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] )
with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer:
vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) )
def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __UpperCAmelCase : Optional[int] ) -> Tuple:
SCREAMING_SNAKE_CASE__ = """こんにちは、世界。 \nこんばんは、世界。"""
SCREAMING_SNAKE_CASE__ = """こんにちは 、 世界 。 こんばんは 、 世界 。"""
return input_text, output_text
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __UpperCAmelCase : Union[str, Any] ) -> int:
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.get_input_output_texts(__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = tokenizer.decode(__UpperCAmelCase , clean_up_tokenization_spaces=__UpperCAmelCase )
return text, ids
def SCREAMING_SNAKE_CASE ( self : Any ) -> Dict:
pass # TODO add if relevant
def SCREAMING_SNAKE_CASE ( self : int ) -> Tuple:
pass # TODO add if relevant
def SCREAMING_SNAKE_CASE ( self : str ) -> Dict:
pass # TODO add if relevant
def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file )
SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""こんにちは、世界。\nこんばんは、世界。""" )
self.assertListEqual(__UpperCAmelCase , ["""こんにちは""", """、""", """世界""", """。""", """こん""", """##ばんは""", """、""", """世界""", """。"""] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [3, 1_2, 1_0, 1_4, 4, 9, 1_2, 1_0, 1_4] )
def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]:
SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , word_tokenizer_type="""mecab""" )
self.assertIsNotNone(__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = """こんにちは、世界。\nこんばんは、世界。"""
SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , ["""こんにちは""", """、""", """世界""", """。""", """こん""", """##ばんは""", """、""", """世界""", """。"""] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [3, 1_2, 1_0, 1_4, 4, 9, 1_2, 1_0, 1_4] )
SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """tokenizer.bin""" )
with open(__UpperCAmelCase , """wb""" ) as handle:
pickle.dump(__UpperCAmelCase , __UpperCAmelCase )
with open(__UpperCAmelCase , """rb""" ) as handle:
SCREAMING_SNAKE_CASE__ = pickle.load(__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = tokenizer_new.tokenize(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
def SCREAMING_SNAKE_CASE ( self : List[str] ) -> int:
SCREAMING_SNAKE_CASE__ = MecabTokenizer(mecab_dic="""ipadic""" )
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップルストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , )
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]:
try:
SCREAMING_SNAKE_CASE__ = MecabTokenizer(mecab_dic="""unidic_lite""" )
except ModuleNotFoundError:
return
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , )
def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict:
try:
SCREAMING_SNAKE_CASE__ = MecabTokenizer(mecab_dic="""unidic""" )
except ModuleNotFoundError:
return
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , )
def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]:
SCREAMING_SNAKE_CASE__ = MecabTokenizer(do_lower_case=__UpperCAmelCase , mecab_dic="""ipadic""" )
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップルストア""", """で""", """iphone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , )
def SCREAMING_SNAKE_CASE ( self : str ) -> List[str]:
try:
SCREAMING_SNAKE_CASE__ = MecabTokenizer(
do_lower_case=__UpperCAmelCase , normalize_text=__UpperCAmelCase , mecab_option="""-d /usr/local/lib/mecab/dic/jumandic""" )
except RuntimeError:
# if dict doesn't exist in the system, previous code raises this error.
return
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップルストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れた""", """\u3000""", """。"""] , )
def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]:
SCREAMING_SNAKE_CASE__ = MecabTokenizer(normalize_text=__UpperCAmelCase , mecab_dic="""ipadic""" )
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップルストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """ """, """。"""] , )
@require_sudachi
def SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]:
SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , word_tokenizer_type="""sudachi""" )
self.assertIsNotNone(__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = """こんにちは、世界。\nこんばんは、世界。"""
SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , ["""こんにちは""", """、""", """世界""", """。""", """こん""", """##ばんは""", """、""", """世界""", """。"""] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [3, 1_2, 1_0, 1_4, 4, 9, 1_2, 1_0, 1_4] )
SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """tokenizer.bin""" )
with open(__UpperCAmelCase , """wb""" ) as handle:
pickle.dump(__UpperCAmelCase , __UpperCAmelCase )
with open(__UpperCAmelCase , """rb""" ) as handle:
SCREAMING_SNAKE_CASE__ = pickle.load(__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = tokenizer_new.tokenize(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
@require_sudachi
def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict:
SCREAMING_SNAKE_CASE__ = SudachiTokenizer(sudachi_dict_type="""core""" )
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , [""" """, """\t""", """アップル""", """ストア""", """で""", """iPhone""", """8""", """ """, """が""", """ """, """ """, """\n """, """発売""", """さ""", """れ""", """た""", """ """, """。""", """ """, """ """] , )
@require_sudachi
def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]:
SCREAMING_SNAKE_CASE__ = SudachiTokenizer(sudachi_dict_type="""core""" , sudachi_split_mode="""A""" )
self.assertListEqual(tokenizer.tokenize("""外国人参政権""" ) , ["""外国""", """人""", """参政""", """権"""] )
@require_sudachi
def SCREAMING_SNAKE_CASE ( self : int ) -> List[str]:
SCREAMING_SNAKE_CASE__ = SudachiTokenizer(sudachi_dict_type="""core""" , sudachi_split_mode="""B""" )
self.assertListEqual(tokenizer.tokenize("""外国人参政権""" ) , ["""外国人""", """参政権"""] )
@require_sudachi
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]:
SCREAMING_SNAKE_CASE__ = SudachiTokenizer(sudachi_dict_type="""core""" , sudachi_split_mode="""C""" )
self.assertListEqual(tokenizer.tokenize("""外国人参政権""" ) , ["""外国人参政権"""] )
@require_sudachi
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]:
SCREAMING_SNAKE_CASE__ = SudachiTokenizer(do_lower_case=__UpperCAmelCase , sudachi_dict_type="""core""" )
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , [""" """, """\t""", """アップル""", """ストア""", """で""", """iphone""", """8""", """ """, """が""", """ """, """ """, """\n """, """発売""", """さ""", """れ""", """た""", """ """, """。""", """ """, """ """] , )
@require_sudachi
def SCREAMING_SNAKE_CASE ( self : Tuple ) -> str:
SCREAMING_SNAKE_CASE__ = SudachiTokenizer(normalize_text=__UpperCAmelCase , sudachi_dict_type="""core""" )
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , [""" """, """\t""", """アップル""", """ストア""", """で""", """iPhone""", """8""", """ """, """が""", """ """, """ """, """\n """, """発売""", """さ""", """れ""", """た""", """\u3000""", """。""", """ """, """ """] , )
@require_sudachi
def SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]:
SCREAMING_SNAKE_CASE__ = SudachiTokenizer(trim_whitespace=__UpperCAmelCase , sudachi_dict_type="""core""" )
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , )
@require_jumanpp
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict:
SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , word_tokenizer_type="""jumanpp""" )
self.assertIsNotNone(__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = """こんにちは、世界。\nこんばんは、世界。"""
SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , ["""こんにちは""", """、""", """世界""", """。""", """こん""", """##ばんは""", """、""", """世界""", """。"""] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [3, 1_2, 1_0, 1_4, 4, 9, 1_2, 1_0, 1_4] )
SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """tokenizer.bin""" )
with open(__UpperCAmelCase , """wb""" ) as handle:
pickle.dump(__UpperCAmelCase , __UpperCAmelCase )
with open(__UpperCAmelCase , """rb""" ) as handle:
SCREAMING_SNAKE_CASE__ = pickle.load(__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = tokenizer_new.tokenize(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
@require_jumanpp
def SCREAMING_SNAKE_CASE ( self : int ) -> List[str]:
SCREAMING_SNAKE_CASE__ = JumanppTokenizer()
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """\u3000""", """が""", """\u3000""", """\u3000""", """\u3000""", """発売""", """さ""", """れた""", """\u3000""", """。"""] , )
@require_jumanpp
def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> int:
SCREAMING_SNAKE_CASE__ = JumanppTokenizer(do_lower_case=__UpperCAmelCase )
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iphone""", """8""", """\u3000""", """が""", """\u3000""", """\u3000""", """\u3000""", """発売""", """さ""", """れた""", """\u3000""", """。"""] , )
@require_jumanpp
def SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE__ = JumanppTokenizer(normalize_text=__UpperCAmelCase )
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""ア""", """ッ""", """フ""", """゚""", """ル""", """ストア""", """で""", """iPhone""", """8""", """\u3000""", """が""", """\u3000""", """\u3000""", """\u3000""", """発売""", """さ""", """れた""", """\u3000""", """。"""] , )
@require_jumanpp
def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]:
SCREAMING_SNAKE_CASE__ = JumanppTokenizer(trim_whitespace=__UpperCAmelCase )
self.assertListEqual(
tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れた""", """。"""] , )
@require_jumanpp
def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]:
SCREAMING_SNAKE_CASE__ = JumanppTokenizer()
self.assertListEqual(
tokenizer.tokenize("""ありがとうございますm(_ _)m見つけるのが大変です。""" ) , ["""ありがとう""", """ございます""", """m(_ _)m""", """見つける""", """の""", """が""", """大変です""", """。"""] , )
def SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]:
SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """こんにちは""", """こん""", """にちは""", """ばんは""", """##こん""", """##にちは""", """##ばんは"""]
SCREAMING_SNAKE_CASE__ = {}
for i, token in enumerate(__UpperCAmelCase ):
SCREAMING_SNAKE_CASE__ = i
SCREAMING_SNAKE_CASE__ = WordpieceTokenizer(vocab=__UpperCAmelCase , unk_token="""[UNK]""" )
self.assertListEqual(tokenizer.tokenize("""""" ) , [] )
self.assertListEqual(tokenizer.tokenize("""こんにちは""" ) , ["""こんにちは"""] )
self.assertListEqual(tokenizer.tokenize("""こんばんは""" ) , ["""こん""", """##ばんは"""] )
self.assertListEqual(tokenizer.tokenize("""こんばんは こんばんにちは こんにちは""" ) , ["""こん""", """##ばんは""", """[UNK]""", """こんにちは"""] )
def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]:
SCREAMING_SNAKE_CASE__ = BertJapaneseTokenizer.from_pretrained("""nlp-waseda/roberta-base-japanese-with-auto-jumanpp""" )
SCREAMING_SNAKE_CASE__ = tokenizer.subword_tokenizer
SCREAMING_SNAKE_CASE__ = subword_tokenizer.tokenize("""国境 の 長い トンネル を 抜ける と 雪国 であった 。""" )
self.assertListEqual(__UpperCAmelCase , ["""▁国境""", """▁の""", """▁長い""", """▁トンネル""", """▁を""", """▁抜ける""", """▁と""", """▁雪""", """国""", """▁であった""", """▁。"""] )
SCREAMING_SNAKE_CASE__ = subword_tokenizer.tokenize("""こんばんは こんばん にち は こんにちは""" )
self.assertListEqual(__UpperCAmelCase , ["""▁こん""", """ばん""", """は""", """▁こん""", """ばん""", """▁に""", """ち""", """▁は""", """▁こんにちは"""] )
def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any:
SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained("""cl-tohoku/bert-base-japanese""" )
SCREAMING_SNAKE_CASE__ = tokenizer.encode("""ありがとう。""" , add_special_tokens=__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = tokenizer.encode("""どういたしまして。""" , add_special_tokens=__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase )
# 2 is for "[CLS]", 3 is for "[SEP]"
assert encoded_sentence == [2] + text + [3]
assert encoded_pair == [2] + text + [3] + text_a + [3]
@custom_tokenizers
class lowerCamelCase (A__ ,unittest.TestCase ):
lowerCamelCase__ : Dict = BertJapaneseTokenizer
lowerCamelCase__ : Tuple = False
def SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]:
super().setUp()
SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """こ""", """ん""", """に""", """ち""", """は""", """ば""", """世""", """界""", """、""", """。"""]
SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] )
with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer:
vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) )
def SCREAMING_SNAKE_CASE ( self : Optional[int] , **__UpperCAmelCase : List[Any] ) -> List[Any]:
return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type="""character""" , **__UpperCAmelCase )
def SCREAMING_SNAKE_CASE ( self : Any , __UpperCAmelCase : Any ) -> List[Any]:
SCREAMING_SNAKE_CASE__ = """こんにちは、世界。 \nこんばんは、世界。"""
SCREAMING_SNAKE_CASE__ = """こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。"""
return input_text, output_text
def SCREAMING_SNAKE_CASE ( self : str ) -> Dict:
pass # TODO add if relevant
def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]:
pass # TODO add if relevant
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]:
pass # TODO add if relevant
def SCREAMING_SNAKE_CASE ( self : Any ) -> Any:
SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , subword_tokenizer_type="""character""" )
SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""こんにちは、世界。 \nこんばんは、世界。""" )
self.assertListEqual(
__UpperCAmelCase , ["""こ""", """ん""", """に""", """ち""", """は""", """、""", """世""", """界""", """。""", """こ""", """ん""", """ば""", """ん""", """は""", """、""", """世""", """界""", """。"""] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [3, 4, 5, 6, 7, 1_1, 9, 1_0, 1_2, 3, 4, 8, 4, 7, 1_1, 9, 1_0, 1_2] )
def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]:
SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """こ""", """ん""", """に""", """ち""", """は""", """ば""", """世""", """界""", """、""", """。"""]
SCREAMING_SNAKE_CASE__ = {}
for i, token in enumerate(__UpperCAmelCase ):
SCREAMING_SNAKE_CASE__ = i
SCREAMING_SNAKE_CASE__ = CharacterTokenizer(vocab=__UpperCAmelCase , unk_token="""[UNK]""" )
self.assertListEqual(tokenizer.tokenize("""""" ) , [] )
self.assertListEqual(tokenizer.tokenize("""こんにちは""" ) , ["""こ""", """ん""", """に""", """ち""", """は"""] )
self.assertListEqual(tokenizer.tokenize("""こんにちほ""" ) , ["""こ""", """ん""", """に""", """ち""", """[UNK]"""] )
def SCREAMING_SNAKE_CASE ( self : Any ) -> str:
SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained("""cl-tohoku/bert-base-japanese-char""" )
SCREAMING_SNAKE_CASE__ = tokenizer.encode("""ありがとう。""" , add_special_tokens=__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = tokenizer.encode("""どういたしまして。""" , add_special_tokens=__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase )
SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase )
# 2 is for "[CLS]", 3 is for "[SEP]"
assert encoded_sentence == [2] + text + [3]
assert encoded_pair == [2] + text + [3] + text_a + [3]
@custom_tokenizers
class lowerCamelCase (unittest.TestCase ):
def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict:
SCREAMING_SNAKE_CASE__ = """cl-tohoku/bert-base-japanese"""
SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained(__UpperCAmelCase )
self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase )
class lowerCamelCase (unittest.TestCase ):
def SCREAMING_SNAKE_CASE ( self : Dict ) -> Any:
SCREAMING_SNAKE_CASE__ = """cl-tohoku/bert-base-japanese"""
with self.assertLogs("""transformers""" , level="""WARNING""" ) as cm:
BertTokenizer.from_pretrained(__UpperCAmelCase )
self.assertTrue(
cm.records[0].message.startswith(
"""The tokenizer class you load from this checkpoint is not the same type as the class this function"""
""" is called from.""" ) )
SCREAMING_SNAKE_CASE__ = """bert-base-cased"""
with self.assertLogs("""transformers""" , level="""WARNING""" ) as cm:
BertJapaneseTokenizer.from_pretrained(__UpperCAmelCase )
self.assertTrue(
cm.records[0].message.startswith(
"""The tokenizer class you load from this checkpoint is not the same type as the class this function"""
""" is called from.""" ) )
| 196 | 0 |
from __future__ import annotations
a__ = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0]
a__ = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1]
def lowercase ( SCREAMING_SNAKE_CASE__ : list[float] ) -> list[float]:
_snake_case : List[str] = []
_snake_case : List[str] = len(SCREAMING_SNAKE_CASE__ )
for i in range(SCREAMING_SNAKE_CASE__ ):
_snake_case : float = -1
for j in range(i + 1 , SCREAMING_SNAKE_CASE__ ):
if arr[i] < arr[j]:
_snake_case : Optional[int] = arr[j]
break
result.append(SCREAMING_SNAKE_CASE__ )
return result
def lowercase ( SCREAMING_SNAKE_CASE__ : list[float] ) -> list[float]:
_snake_case : Union[str, Any] = []
for i, outer in enumerate(SCREAMING_SNAKE_CASE__ ):
_snake_case : float = -1
for inner in arr[i + 1 :]:
if outer < inner:
_snake_case : Union[str, Any] = inner
break
result.append(SCREAMING_SNAKE_CASE__ )
return result
def lowercase ( SCREAMING_SNAKE_CASE__ : list[float] ) -> list[float]:
_snake_case : Optional[Any] = len(SCREAMING_SNAKE_CASE__ )
_snake_case : list[float] = []
_snake_case : list[float] = [-1] * arr_size
for index in reversed(range(SCREAMING_SNAKE_CASE__ ) ):
if stack:
while stack[-1] <= arr[index]:
stack.pop()
if not stack:
break
if stack:
_snake_case : Union[str, Any] = stack[-1]
stack.append(arr[index] )
return result
if __name__ == "__main__":
from doctest import testmod
from timeit import timeit
testmod()
print(next_greatest_element_slow(arr))
print(next_greatest_element_fast(arr))
print(next_greatest_element(arr))
a__ = (
"""from __main__ import arr, next_greatest_element_slow, """
"""next_greatest_element_fast, next_greatest_element"""
)
print(
"""next_greatest_element_slow():""",
timeit("""next_greatest_element_slow(arr)""", setup=setup),
)
print(
"""next_greatest_element_fast():""",
timeit("""next_greatest_element_fast(arr)""", setup=setup),
)
print(
""" next_greatest_element():""",
timeit("""next_greatest_element(arr)""", setup=setup),
)
| 198 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
a__ = {
"""configuration_canine""": ["""CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CanineConfig"""],
"""tokenization_canine""": ["""CanineTokenizer"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a__ = [
"""CANINE_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""CanineForMultipleChoice""",
"""CanineForQuestionAnswering""",
"""CanineForSequenceClassification""",
"""CanineForTokenClassification""",
"""CanineLayer""",
"""CanineModel""",
"""CaninePreTrainedModel""",
"""load_tf_weights_in_canine""",
]
if TYPE_CHECKING:
from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig
from .tokenization_canine import CanineTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_canine import (
CANINE_PRETRAINED_MODEL_ARCHIVE_LIST,
CanineForMultipleChoice,
CanineForQuestionAnswering,
CanineForSequenceClassification,
CanineForTokenClassification,
CanineLayer,
CanineModel,
CaninePreTrainedModel,
load_tf_weights_in_canine,
)
else:
import sys
a__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 198 | 1 |
"""simple docstring"""
from __future__ import annotations
from collections.abc import Callable
def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = 100 , ) -> float:
"""simple docstring"""
__UpperCAmelCase : Optional[int] = x_start
__UpperCAmelCase : List[str] = fnc(UpperCamelCase )
__UpperCAmelCase : Tuple = 0.0
for _ in range(UpperCamelCase ):
# Approximates small segments of curve as linear and solve
# for trapezoidal area
__UpperCAmelCase : int = (x_end - x_start) / steps + xa
__UpperCAmelCase : Tuple = fnc(UpperCamelCase )
area += abs(fxa + fxa ) * (xa - xa) / 2
# Increment step
__UpperCAmelCase : List[Any] = xa
__UpperCAmelCase : Dict = fxa
return area
if __name__ == "__main__":
def _UpperCamelCase ( UpperCamelCase ) -> Optional[int]:
"""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 <= 100_000:
print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''')
i *= 10
| 77 |
import os
# Precomputes a list of the 100 first triangular numbers
__a = [int(0.5 * n * (n + 1)) for n in range(1, 1_0_1)]
def a ( ):
'''simple docstring'''
lowercase_ = os.path.dirname(os.path.realpath(snake_case__ ) )
lowercase_ = os.path.join(snake_case__ , '''words.txt''' )
lowercase_ = ''''''
with open(snake_case__ ) as f:
lowercase_ = f.readline()
lowercase_ = [word.strip('''"''' ) for word in words.strip('''\r\n''' ).split(''',''' )]
lowercase_ = [
word
for word in [sum(ord(snake_case__ ) - 64 for x in word ) for word in words]
if word in TRIANGULAR_NUMBERS
]
return len(snake_case__ )
if __name__ == "__main__":
print(solution())
| 97 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
UpperCamelCase : Any = {
"configuration_albert": ["ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "AlbertConfig", "AlbertOnnxConfig"],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase : str = ["AlbertTokenizer"]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase : List[str] = ["AlbertTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase : Optional[Any] = [
"ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"AlbertForMaskedLM",
"AlbertForMultipleChoice",
"AlbertForPreTraining",
"AlbertForQuestionAnswering",
"AlbertForSequenceClassification",
"AlbertForTokenClassification",
"AlbertModel",
"AlbertPreTrainedModel",
"load_tf_weights_in_albert",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase : Optional[Any] = [
"TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFAlbertForMaskedLM",
"TFAlbertForMultipleChoice",
"TFAlbertForPreTraining",
"TFAlbertForQuestionAnswering",
"TFAlbertForSequenceClassification",
"TFAlbertForTokenClassification",
"TFAlbertMainLayer",
"TFAlbertModel",
"TFAlbertPreTrainedModel",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase : List[Any] = [
"FlaxAlbertForMaskedLM",
"FlaxAlbertForMultipleChoice",
"FlaxAlbertForPreTraining",
"FlaxAlbertForQuestionAnswering",
"FlaxAlbertForSequenceClassification",
"FlaxAlbertForTokenClassification",
"FlaxAlbertModel",
"FlaxAlbertPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_albert import AlbertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_albert_fast import AlbertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_albert import (
ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForPreTraining,
AlbertForQuestionAnswering,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertModel,
AlbertPreTrainedModel,
load_tf_weights_in_albert,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_albert import (
TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFAlbertForMaskedLM,
TFAlbertForMultipleChoice,
TFAlbertForPreTraining,
TFAlbertForQuestionAnswering,
TFAlbertForSequenceClassification,
TFAlbertForTokenClassification,
TFAlbertMainLayer,
TFAlbertModel,
TFAlbertPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_albert import (
FlaxAlbertForMaskedLM,
FlaxAlbertForMultipleChoice,
FlaxAlbertForPreTraining,
FlaxAlbertForQuestionAnswering,
FlaxAlbertForSequenceClassification,
FlaxAlbertForTokenClassification,
FlaxAlbertModel,
FlaxAlbertPreTrainedModel,
)
else:
import sys
UpperCamelCase : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 91 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCamelCase : Dict = {
"configuration_megatron_bert": ["MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegatronBertConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase : Any = [
"MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"MegatronBertForCausalLM",
"MegatronBertForMaskedLM",
"MegatronBertForMultipleChoice",
"MegatronBertForNextSentencePrediction",
"MegatronBertForPreTraining",
"MegatronBertForQuestionAnswering",
"MegatronBertForSequenceClassification",
"MegatronBertForTokenClassification",
"MegatronBertModel",
"MegatronBertPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_megatron_bert import (
MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
MegatronBertForCausalLM,
MegatronBertForMaskedLM,
MegatronBertForMultipleChoice,
MegatronBertForNextSentencePrediction,
MegatronBertForPreTraining,
MegatronBertForQuestionAnswering,
MegatronBertForSequenceClassification,
MegatronBertForTokenClassification,
MegatronBertModel,
MegatronBertPreTrainedModel,
)
else:
import sys
UpperCamelCase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 91 | 1 |
"""simple docstring"""
from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import (
ImageTextPipelineOutput,
UniDiffuserPipeline,
)
else:
from .modeling_text_decoder import UniDiffuserTextDecoder
from .modeling_uvit import UniDiffuserModel, UTransformeraDModel
from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
| 96 |
import warnings
from ...utils import logging
from .image_processing_donut import DonutImageProcessor
snake_case__ = logging.get_logger(__name__)
class UpperCAmelCase ( __lowerCamelCase ):
def __init__( self : Optional[Any] , *lowerCAmelCase : Optional[int] , **lowerCAmelCase : List[Any] ):
warnings.warn(
'''The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'''
''' use DonutImageProcessor instead.''' , lowerCAmelCase , )
super().__init__(*lowerCAmelCase , **lowerCAmelCase )
| 583 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
UpperCamelCase_ = {
'configuration_albert': ['ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AlbertConfig', 'AlbertOnnxConfig'],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ = ['AlbertTokenizer']
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ = ['AlbertTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ = [
'ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST',
'AlbertForMaskedLM',
'AlbertForMultipleChoice',
'AlbertForPreTraining',
'AlbertForQuestionAnswering',
'AlbertForSequenceClassification',
'AlbertForTokenClassification',
'AlbertModel',
'AlbertPreTrainedModel',
'load_tf_weights_in_albert',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ = [
'TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFAlbertForMaskedLM',
'TFAlbertForMultipleChoice',
'TFAlbertForPreTraining',
'TFAlbertForQuestionAnswering',
'TFAlbertForSequenceClassification',
'TFAlbertForTokenClassification',
'TFAlbertMainLayer',
'TFAlbertModel',
'TFAlbertPreTrainedModel',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ = [
'FlaxAlbertForMaskedLM',
'FlaxAlbertForMultipleChoice',
'FlaxAlbertForPreTraining',
'FlaxAlbertForQuestionAnswering',
'FlaxAlbertForSequenceClassification',
'FlaxAlbertForTokenClassification',
'FlaxAlbertModel',
'FlaxAlbertPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_albert import AlbertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_albert_fast import AlbertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_albert import (
ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForPreTraining,
AlbertForQuestionAnswering,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertModel,
AlbertPreTrainedModel,
load_tf_weights_in_albert,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_albert import (
TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFAlbertForMaskedLM,
TFAlbertForMultipleChoice,
TFAlbertForPreTraining,
TFAlbertForQuestionAnswering,
TFAlbertForSequenceClassification,
TFAlbertForTokenClassification,
TFAlbertMainLayer,
TFAlbertModel,
TFAlbertPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_albert import (
FlaxAlbertForMaskedLM,
FlaxAlbertForMultipleChoice,
FlaxAlbertForPreTraining,
FlaxAlbertForQuestionAnswering,
FlaxAlbertForSequenceClassification,
FlaxAlbertForTokenClassification,
FlaxAlbertModel,
FlaxAlbertPreTrainedModel,
)
else:
import sys
UpperCamelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 142 |
import copy
import os
from typing import TYPE_CHECKING, List, Union
if TYPE_CHECKING:
pass
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase_ = logging.get_logger(__name__)
UpperCamelCase_ = {
'kakaobrain/align-base': 'https://huggingface.co/kakaobrain/align-base/resolve/main/config.json',
}
class _SCREAMING_SNAKE_CASE ( _lowerCAmelCase ):
a_ : Tuple = '''align_text_model'''
def __init__(self , UpperCAmelCase=3_0_5_2_2 , UpperCAmelCase=7_6_8 , UpperCAmelCase=1_2 , UpperCAmelCase=1_2 , UpperCAmelCase=3_0_7_2 , UpperCAmelCase="gelu" , UpperCAmelCase=0.1 , UpperCAmelCase=0.1 , UpperCAmelCase=5_1_2 , UpperCAmelCase=2 , UpperCAmelCase=0.02 , UpperCAmelCase=1e-12 , UpperCAmelCase=0 , UpperCAmelCase="absolute" , UpperCAmelCase=True , **UpperCAmelCase , ):
'''simple docstring'''
super().__init__(**UpperCAmelCase)
__UpperCAmelCase =vocab_size
__UpperCAmelCase =hidden_size
__UpperCAmelCase =num_hidden_layers
__UpperCAmelCase =num_attention_heads
__UpperCAmelCase =hidden_act
__UpperCAmelCase =intermediate_size
__UpperCAmelCase =hidden_dropout_prob
__UpperCAmelCase =attention_probs_dropout_prob
__UpperCAmelCase =max_position_embeddings
__UpperCAmelCase =type_vocab_size
__UpperCAmelCase =initializer_range
__UpperCAmelCase =layer_norm_eps
__UpperCAmelCase =position_embedding_type
__UpperCAmelCase =use_cache
__UpperCAmelCase =pad_token_id
@classmethod
def A__ (cls , UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
cls._set_token_in_kwargs(UpperCAmelCase)
__UpperCAmelCase , __UpperCAmelCase =cls.get_config_dict(UpperCAmelCase , **UpperCAmelCase)
# get the text config dict if we are loading from AlignConfig
if config_dict.get('''model_type''') == "align":
__UpperCAmelCase =config_dict['''text_config''']
if "model_type" in config_dict and hasattr(cls , '''model_type''') and config_dict["model_type"] != cls.model_type:
logger.warning(
f"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""")
return cls.from_dict(UpperCAmelCase , **UpperCAmelCase)
class _SCREAMING_SNAKE_CASE ( _lowerCAmelCase ):
a_ : Dict = '''align_vision_model'''
def __init__(self , UpperCAmelCase = 3 , UpperCAmelCase = 6_0_0 , UpperCAmelCase = 2.0 , UpperCAmelCase = 3.1 , UpperCAmelCase = 8 , UpperCAmelCase = [3, 3, 5, 3, 5, 5, 3] , UpperCAmelCase = [3_2, 1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2] , UpperCAmelCase = [1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2, 3_2_0] , UpperCAmelCase = [] , UpperCAmelCase = [1, 2, 2, 2, 1, 2, 1] , UpperCAmelCase = [1, 2, 2, 3, 3, 4, 1] , UpperCAmelCase = [1, 6, 6, 6, 6, 6, 6] , UpperCAmelCase = 0.25 , UpperCAmelCase = "swish" , UpperCAmelCase = 2_5_6_0 , UpperCAmelCase = "mean" , UpperCAmelCase = 0.02 , UpperCAmelCase = 0.001 , UpperCAmelCase = 0.99 , UpperCAmelCase = 0.2 , **UpperCAmelCase , ):
'''simple docstring'''
super().__init__(**UpperCAmelCase)
__UpperCAmelCase =num_channels
__UpperCAmelCase =image_size
__UpperCAmelCase =width_coefficient
__UpperCAmelCase =depth_coefficient
__UpperCAmelCase =depth_divisor
__UpperCAmelCase =kernel_sizes
__UpperCAmelCase =in_channels
__UpperCAmelCase =out_channels
__UpperCAmelCase =depthwise_padding
__UpperCAmelCase =strides
__UpperCAmelCase =num_block_repeats
__UpperCAmelCase =expand_ratios
__UpperCAmelCase =squeeze_expansion_ratio
__UpperCAmelCase =hidden_act
__UpperCAmelCase =hidden_dim
__UpperCAmelCase =pooling_type
__UpperCAmelCase =initializer_range
__UpperCAmelCase =batch_norm_eps
__UpperCAmelCase =batch_norm_momentum
__UpperCAmelCase =drop_connect_rate
__UpperCAmelCase =sum(UpperCAmelCase) * 4
@classmethod
def A__ (cls , UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
cls._set_token_in_kwargs(UpperCAmelCase)
__UpperCAmelCase , __UpperCAmelCase =cls.get_config_dict(UpperCAmelCase , **UpperCAmelCase)
# get the vision config dict if we are loading from AlignConfig
if config_dict.get('''model_type''') == "align":
__UpperCAmelCase =config_dict['''vision_config''']
if "model_type" in config_dict and hasattr(cls , '''model_type''') and config_dict["model_type"] != cls.model_type:
logger.warning(
f"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""")
return cls.from_dict(UpperCAmelCase , **UpperCAmelCase)
class _SCREAMING_SNAKE_CASE ( _lowerCAmelCase ):
a_ : int = '''align'''
a_ : Optional[Any] = True
def __init__(self , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=6_4_0 , UpperCAmelCase=1.0 , UpperCAmelCase=0.02 , **UpperCAmelCase , ):
'''simple docstring'''
super().__init__(**UpperCAmelCase)
if text_config is None:
__UpperCAmelCase ={}
logger.info('''text_config is None. Initializing the AlignTextConfig with default values.''')
if vision_config is None:
__UpperCAmelCase ={}
logger.info('''vision_config is None. Initializing the AlignVisionConfig with default values.''')
__UpperCAmelCase =AlignTextConfig(**UpperCAmelCase)
__UpperCAmelCase =AlignVisionConfig(**UpperCAmelCase)
__UpperCAmelCase =projection_dim
__UpperCAmelCase =temperature_init_value
__UpperCAmelCase =initializer_range
@classmethod
def A__ (cls , UpperCAmelCase , UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **UpperCAmelCase)
def A__ (self):
'''simple docstring'''
__UpperCAmelCase =copy.deepcopy(self.__dict__)
__UpperCAmelCase =self.text_config.to_dict()
__UpperCAmelCase =self.vision_config.to_dict()
__UpperCAmelCase =self.__class__.model_type
return output
| 142 | 1 |
'''simple docstring'''
import inspect
import unittest
import torch
import torch.nn as nn
from accelerate.hooks import (
AlignDevicesHook,
ModelHook,
SequentialHook,
add_hook_to_module,
attach_align_device_hook,
remove_hook_from_module,
remove_hook_from_submodules,
)
from accelerate.test_utils import require_multi_gpu
class lowercase_ (nn.Module ):
"""simple docstring"""
def __init__( self : Tuple ):
super().__init__()
__lowercase = nn.Linear(3 ,4 )
__lowercase = nn.BatchNormad(4 )
__lowercase = nn.Linear(4 ,5 )
def SCREAMING_SNAKE_CASE ( self : List[str] ,lowercase__ : List[Any] ):
return self.lineara(self.batchnorm(self.lineara(lowercase__ ) ) )
class lowercase_ (lowerCamelCase__ ):
"""simple docstring"""
def SCREAMING_SNAKE_CASE ( self : List[Any] ,lowercase__ : Dict ,*lowercase__ : List[str] ,**lowercase__ : List[str] ):
return (args[0] + 1,) + args[1:], kwargs
class lowercase_ (lowerCamelCase__ ):
"""simple docstring"""
def SCREAMING_SNAKE_CASE ( self : List[str] ,lowercase__ : Optional[Any] ,lowercase__ : Optional[Any] ):
return output + 1
class lowercase_ (unittest.TestCase ):
"""simple docstring"""
def SCREAMING_SNAKE_CASE ( self : str ):
__lowercase = ModelForTest()
__lowercase = ModelHook()
add_hook_to_module(lowercase__ ,lowercase__ )
self.assertEqual(test_model._hf_hook ,lowercase__ )
self.assertTrue(hasattr(lowercase__ ,'''_old_forward''' ) )
# Check adding the hook did not change the name or the signature
self.assertEqual(test_model.forward.__name__ ,'''forward''' )
self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) ,['''x'''] )
remove_hook_from_module(lowercase__ )
self.assertFalse(hasattr(lowercase__ ,'''_hf_hook''' ) )
self.assertFalse(hasattr(lowercase__ ,'''_old_forward''' ) )
def SCREAMING_SNAKE_CASE ( self : List[str] ):
__lowercase = ModelForTest()
__lowercase = ModelHook()
add_hook_to_module(lowercase__ ,lowercase__ )
add_hook_to_module(lowercase__ ,lowercase__ ,append=lowercase__ )
self.assertEqual(isinstance(test_model._hf_hook ,lowercase__ ) ,lowercase__ )
self.assertEqual(len(test_model._hf_hook.hooks ) ,2 )
self.assertTrue(hasattr(lowercase__ ,'''_old_forward''' ) )
# Check adding the hook did not change the name or the signature
self.assertEqual(test_model.forward.__name__ ,'''forward''' )
self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) ,['''x'''] )
remove_hook_from_module(lowercase__ )
self.assertFalse(hasattr(lowercase__ ,'''_hf_hook''' ) )
self.assertFalse(hasattr(lowercase__ ,'''_old_forward''' ) )
def SCREAMING_SNAKE_CASE ( self : Optional[int] ):
__lowercase = ModelForTest()
__lowercase = torch.randn(2 ,3 )
__lowercase = test_model(x + 1 )
__lowercase = test_model(x + 2 )
__lowercase = PreForwardHook()
add_hook_to_module(lowercase__ ,lowercase__ )
__lowercase = test_model(lowercase__ )
self.assertTrue(torch.allclose(lowercase__ ,lowercase__ ,atol=1e-5 ) )
# Attaching a hook to a model when it already has one replaces, does not chain
__lowercase = PreForwardHook()
add_hook_to_module(lowercase__ ,lowercase__ )
__lowercase = test_model(lowercase__ )
self.assertTrue(torch.allclose(lowercase__ ,lowercase__ ,atol=1e-5 ) )
# You need to use the sequential hook to chain two or more hooks
__lowercase = SequentialHook(PreForwardHook() ,PreForwardHook() )
add_hook_to_module(lowercase__ ,lowercase__ )
__lowercase = test_model(lowercase__ )
assert torch.allclose(lowercase__ ,lowercase__ ,atol=1e-5 )
def SCREAMING_SNAKE_CASE ( self : Optional[int] ):
__lowercase = ModelForTest()
__lowercase = torch.randn(2 ,3 )
__lowercase = test_model(lowercase__ )
__lowercase = PostForwardHook()
add_hook_to_module(lowercase__ ,lowercase__ )
__lowercase = test_model(lowercase__ )
self.assertTrue(torch.allclose(lowercase__ ,output + 1 ,atol=1e-5 ) )
# Attaching a hook to a model when it already has one replaces, does not chain
__lowercase = PostForwardHook()
add_hook_to_module(lowercase__ ,lowercase__ )
__lowercase = test_model(lowercase__ )
self.assertTrue(torch.allclose(lowercase__ ,output + 1 ,atol=1e-5 ) )
# You need to use the sequential hook to chain two or more hooks
__lowercase = SequentialHook(PostForwardHook() ,PostForwardHook() )
add_hook_to_module(lowercase__ ,lowercase__ )
__lowercase = test_model(lowercase__ )
assert torch.allclose(lowercase__ ,output + 2 ,atol=1e-5 )
def SCREAMING_SNAKE_CASE ( self : int ):
__lowercase = ModelForTest()
__lowercase = torch.randn(2 ,3 )
__lowercase = test_model(lowercase__ )
__lowercase = PostForwardHook()
add_hook_to_module(lowercase__ ,lowercase__ )
__lowercase = test_model(lowercase__ )
self.assertTrue(torch.allclose(lowercase__ ,output + 1 ) )
self.assertTrue(outputa.requires_grad )
__lowercase = True
__lowercase = test_model(lowercase__ )
self.assertFalse(outputa.requires_grad )
@require_multi_gpu
def SCREAMING_SNAKE_CASE ( self : Dict ):
__lowercase = ModelForTest()
# Everything is on CPU
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
# This will move each submodule on different devices
add_hook_to_module(model.lineara ,AlignDevicesHook(execution_device=0 ) )
add_hook_to_module(model.batchnorm ,AlignDevicesHook(execution_device=0 ) )
add_hook_to_module(model.lineara ,AlignDevicesHook(execution_device=1 ) )
self.assertEqual(model.lineara.weight.device ,torch.device(0 ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device(0 ) )
self.assertEqual(model.batchnorm.running_mean.device ,torch.device(0 ) )
self.assertEqual(model.lineara.weight.device ,torch.device(1 ) )
# We can still make a forward pass. The input does not need to be on any particular device
__lowercase = torch.randn(2 ,3 )
__lowercase = model(lowercase__ )
self.assertEqual(output.device ,torch.device(1 ) )
# We can add a general hook to put back output on same device as input.
add_hook_to_module(lowercase__ ,AlignDevicesHook(io_same_device=lowercase__ ) )
__lowercase = torch.randn(2 ,3 ).to(0 )
__lowercase = model(lowercase__ )
self.assertEqual(output.device ,torch.device(0 ) )
def SCREAMING_SNAKE_CASE ( self : str ):
__lowercase = ModelForTest()
# Everything is on CPU
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
# This will move each submodule on different devices
__lowercase = {'''execution_device''': 0 if torch.cuda.is_available() else '''cpu''', '''offload''': True}
add_hook_to_module(model.lineara ,AlignDevicesHook(**lowercase__ ) )
add_hook_to_module(model.batchnorm ,AlignDevicesHook(**lowercase__ ) )
add_hook_to_module(model.lineara ,AlignDevicesHook(**lowercase__ ) )
# Parameters have been offloaded, so on the meta device
self.assertEqual(model.lineara.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''meta''' ) )
# Buffers are not included in the offload by default, so are on the execution device
__lowercase = torch.device(hook_kwargs['''execution_device'''] )
self.assertEqual(model.batchnorm.running_mean.device ,lowercase__ )
__lowercase = torch.randn(2 ,3 )
__lowercase = model(lowercase__ )
self.assertEqual(output.device ,lowercase__ )
# Removing hooks loads back the weights in the model.
remove_hook_from_module(model.lineara )
remove_hook_from_module(model.batchnorm )
remove_hook_from_module(model.lineara )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
# Now test with buffers included in the offload
__lowercase = {
'''execution_device''': 0 if torch.cuda.is_available() else '''cpu''',
'''offload''': True,
'''offload_buffers''': True,
}
add_hook_to_module(model.lineara ,AlignDevicesHook(**lowercase__ ) )
add_hook_to_module(model.batchnorm ,AlignDevicesHook(**lowercase__ ) )
add_hook_to_module(model.lineara ,AlignDevicesHook(**lowercase__ ) )
# Parameters have been offloaded, so on the meta device, buffers included
self.assertEqual(model.lineara.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.batchnorm.running_mean.device ,torch.device('''meta''' ) )
__lowercase = torch.randn(2 ,3 )
__lowercase = model(lowercase__ )
self.assertEqual(output.device ,lowercase__ )
# Removing hooks loads back the weights in the model.
remove_hook_from_module(model.lineara )
remove_hook_from_module(model.batchnorm )
remove_hook_from_module(model.lineara )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
def SCREAMING_SNAKE_CASE ( self : int ):
__lowercase = ModelForTest()
# Everything is on CPU
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
# This will move each submodule on different devices
__lowercase = 0 if torch.cuda.is_available() else '''cpu'''
attach_align_device_hook(lowercase__ ,execution_device=lowercase__ ,offload=lowercase__ )
# Parameters have been offloaded, so on the meta device
self.assertEqual(model.lineara.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''meta''' ) )
# Buffers are not included in the offload by default, so are on the execution device
__lowercase = torch.device(lowercase__ )
self.assertEqual(model.batchnorm.running_mean.device ,lowercase__ )
__lowercase = torch.randn(2 ,3 )
__lowercase = model(lowercase__ )
self.assertEqual(output.device ,lowercase__ )
# Removing hooks loads back the weights in the model.
remove_hook_from_submodules(lowercase__ )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
# Now test with buffers included in the offload
attach_align_device_hook(lowercase__ ,execution_device=lowercase__ ,offload=lowercase__ ,offload_buffers=lowercase__ )
# Parameters have been offloaded, so on the meta device, buffers included
self.assertEqual(model.lineara.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.batchnorm.running_mean.device ,torch.device('''meta''' ) )
__lowercase = torch.randn(2 ,3 )
__lowercase = model(lowercase__ )
self.assertEqual(output.device ,lowercase__ )
# Removing hooks loads back the weights in the model.
remove_hook_from_submodules(lowercase__ )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
def SCREAMING_SNAKE_CASE ( self : List[Any] ):
__lowercase = ModelForTest()
# Everything is on CPU
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
# This will move each submodule on different devices
__lowercase = 0 if torch.cuda.is_available() else '''cpu'''
attach_align_device_hook(
lowercase__ ,execution_device=lowercase__ ,offload=lowercase__ ,weights_map=model.state_dict() )
# Parameters have been offloaded, so on the meta device
self.assertEqual(model.lineara.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''meta''' ) )
# Buffers are not included in the offload by default, so are on the execution device
__lowercase = torch.device(lowercase__ )
self.assertEqual(model.batchnorm.running_mean.device ,lowercase__ )
__lowercase = torch.randn(2 ,3 )
__lowercase = model(lowercase__ )
self.assertEqual(output.device ,lowercase__ )
# Removing hooks loads back the weights in the model.
remove_hook_from_submodules(lowercase__ )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
# Now test with buffers included in the offload
attach_align_device_hook(
lowercase__ ,execution_device=lowercase__ ,offload=lowercase__ ,weights_map=model.state_dict() ,offload_buffers=lowercase__ ,)
# Parameters have been offloaded, so on the meta device, buffers included
self.assertEqual(model.lineara.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''meta''' ) )
self.assertEqual(model.batchnorm.running_mean.device ,torch.device('''meta''' ) )
__lowercase = torch.randn(2 ,3 )
__lowercase = model(lowercase__ )
self.assertEqual(output.device ,lowercase__ )
# Removing hooks loads back the weights in the model.
remove_hook_from_submodules(lowercase__ )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.batchnorm.weight.device ,torch.device('''cpu''' ) )
self.assertEqual(model.lineara.weight.device ,torch.device('''cpu''' ) )
| 41 |
'''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, ChunkPipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_torch_available():
import torch
from transformers.modeling_outputs import BaseModelOutput
from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING
lowerCAmelCase__ = logging.get_logger(__name__)
@add_end_docstrings(lowerCamelCase__ )
class lowercase_ (lowerCamelCase__ ):
"""simple docstring"""
def __init__( self : List[str] ,**lowercase__ : Tuple ):
super().__init__(**lowercase__ )
if self.framework == "tf":
raise ValueError(F"The {self.__class__} is only available in PyTorch." )
requires_backends(self ,'''vision''' )
self.check_model_type(lowercase__ )
def __call__( self : List[str] ,lowercase__ : Union[str, "Image.Image", List[Dict[str, Any]]] ,lowercase__ : Union[str, List[str]] = None ,**lowercase__ : str ,):
if "text_queries" in kwargs:
__lowercase = kwargs.pop('''text_queries''' )
if isinstance(lowercase__ ,(str, Image.Image) ):
__lowercase = {'''image''': image, '''candidate_labels''': candidate_labels}
else:
__lowercase = image
__lowercase = super().__call__(lowercase__ ,**lowercase__ )
return results
def SCREAMING_SNAKE_CASE ( self : int ,**lowercase__ : List[Any] ):
__lowercase = {}
if "threshold" in kwargs:
__lowercase = kwargs['''threshold''']
if "top_k" in kwargs:
__lowercase = kwargs['''top_k''']
return {}, {}, postprocess_params
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,lowercase__ : Optional[Any] ):
__lowercase = load_image(inputs['''image'''] )
__lowercase = inputs['''candidate_labels''']
if isinstance(lowercase__ ,lowercase__ ):
__lowercase = candidate_labels.split(''',''' )
__lowercase = torch.tensor([[image.height, image.width]] ,dtype=torch.intaa )
for i, candidate_label in enumerate(lowercase__ ):
__lowercase = self.tokenizer(lowercase__ ,return_tensors=self.framework )
__lowercase = self.image_processor(lowercase__ ,return_tensors=self.framework )
yield {
"is_last": i == len(lowercase__ ) - 1,
"target_size": target_size,
"candidate_label": candidate_label,
**text_inputs,
**image_features,
}
def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : List[str] ):
__lowercase = model_inputs.pop('''target_size''' )
__lowercase = model_inputs.pop('''candidate_label''' )
__lowercase = model_inputs.pop('''is_last''' )
__lowercase = self.model(**lowercase__ )
__lowercase = {'''target_size''': target_size, '''candidate_label''': candidate_label, '''is_last''': is_last, **outputs}
return model_outputs
def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : int ,lowercase__ : List[Any]=0.1 ,lowercase__ : List[str]=None ):
__lowercase = []
for model_output in model_outputs:
__lowercase = model_output['''candidate_label''']
__lowercase = BaseModelOutput(lowercase__ )
__lowercase = self.image_processor.post_process_object_detection(
outputs=lowercase__ ,threshold=lowercase__ ,target_sizes=model_output['''target_size'''] )[0]
for index in outputs["scores"].nonzero():
__lowercase = outputs['''scores'''][index].item()
__lowercase = self._get_bounding_box(outputs['''boxes'''][index][0] )
__lowercase = {'''score''': score, '''label''': label, '''box''': box}
results.append(lowercase__ )
__lowercase = sorted(lowercase__ ,key=lambda lowercase__ : x["score"] ,reverse=lowercase__ )
if top_k:
__lowercase = results[:top_k]
return results
def SCREAMING_SNAKE_CASE ( self : List[str] ,lowercase__ : "torch.Tensor" ):
if self.framework != "pt":
raise ValueError('''The ZeroShotObjectDetectionPipeline is only available in PyTorch.''' )
__lowercase , __lowercase , __lowercase , __lowercase = box.int().tolist()
__lowercase = {
'''xmin''': xmin,
'''ymin''': ymin,
'''xmax''': xmax,
'''ymax''': ymax,
}
return bbox
| 41 | 1 |
'''simple docstring'''
import argparse
from pathlib import Path
import fairseq
import torch
from fairseq.models.xmod import XMODModel as FairseqXmodModel
from packaging import version
from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification
from transformers.utils import logging
if version.parse(fairseq.__version__) < version.parse('''0.12.2'''):
raise Exception('''requires fairseq >= 0.12.2''')
if version.parse(fairseq.__version__) > version.parse('''2'''):
raise Exception('''requires fairseq < v2''')
logging.set_verbosity_info()
UpperCamelCase__ : List[str] = logging.get_logger(__name__)
UpperCamelCase__ : Optional[int] = '''Hello, World!'''
UpperCamelCase__ : int = '''en_XX'''
def lowerCAmelCase_ ( _lowerCamelCase: str , _lowerCamelCase: str , _lowerCamelCase: bool ):
__SCREAMING_SNAKE_CASE : List[Any] = Path("""data_bin""" )
__SCREAMING_SNAKE_CASE : List[str] = FairseqXmodModel.from_pretrained(
model_name_or_path=str(Path(_lowerCamelCase ).parent ) , checkpoint_file=Path(_lowerCamelCase ).name , _name="""xmod_base""" , arch="""xmod_base""" , task="""multilingual_masked_lm""" , data_name_or_path=str(_lowerCamelCase ) , bpe="""sentencepiece""" , sentencepiece_model=str(Path(_lowerCamelCase ).parent / """sentencepiece.bpe.model""" ) , src_dict=str(data_dir / """dict.txt""" ) , )
xmod.eval() # disable dropout
print(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = xmod.model.encoder.sentence_encoder
__SCREAMING_SNAKE_CASE : Optional[Any] = XmodConfig(
vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_14 , type_vocab_size=1 , layer_norm_eps=1E-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , """bottleneck""" , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , )
if classification_head:
__SCREAMING_SNAKE_CASE : int = xmod.model.classification_heads["""mnli"""].out_proj.weight.shape[0]
print("""Our X-MOD config:""" , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = XmodForSequenceClassification(_lowerCamelCase ) if classification_head else XmodForMaskedLM(_lowerCamelCase )
model.eval()
# Now let's copy all the weights.
# Embeddings
__SCREAMING_SNAKE_CASE : Any = xmod_sent_encoder.embed_tokens.weight
__SCREAMING_SNAKE_CASE : List[Any] = xmod_sent_encoder.embed_positions.weight
__SCREAMING_SNAKE_CASE : List[str] = torch.zeros_like(
model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them.
__SCREAMING_SNAKE_CASE : int = xmod_sent_encoder.layernorm_embedding.weight
__SCREAMING_SNAKE_CASE : str = xmod_sent_encoder.layernorm_embedding.bias
for i in range(config.num_hidden_layers ):
# Encoder: start of layer
__SCREAMING_SNAKE_CASE : Tuple = model.roberta.encoder.layer[i]
__SCREAMING_SNAKE_CASE : int = xmod_sent_encoder.layers[i]
# self attention
__SCREAMING_SNAKE_CASE : Optional[Any] = layer.attention.self
if not (
xmod_layer.self_attn.k_proj.weight.data.shape
== xmod_layer.self_attn.q_proj.weight.data.shape
== xmod_layer.self_attn.v_proj.weight.data.shape
== torch.Size((config.hidden_size, config.hidden_size) )
):
raise AssertionError("""Dimensions of self-attention weights do not match.""" )
__SCREAMING_SNAKE_CASE : Optional[Any] = xmod_layer.self_attn.q_proj.weight
__SCREAMING_SNAKE_CASE : Optional[int] = xmod_layer.self_attn.q_proj.bias
__SCREAMING_SNAKE_CASE : Any = xmod_layer.self_attn.k_proj.weight
__SCREAMING_SNAKE_CASE : Tuple = xmod_layer.self_attn.k_proj.bias
__SCREAMING_SNAKE_CASE : Optional[Any] = xmod_layer.self_attn.v_proj.weight
__SCREAMING_SNAKE_CASE : str = xmod_layer.self_attn.v_proj.bias
# self-attention output
__SCREAMING_SNAKE_CASE : Union[str, Any] = layer.attention.output
if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape:
raise AssertionError("""Dimensions of self-attention output weights do not match.""" )
__SCREAMING_SNAKE_CASE : Optional[int] = xmod_layer.self_attn.out_proj.weight
__SCREAMING_SNAKE_CASE : List[str] = xmod_layer.self_attn.out_proj.bias
__SCREAMING_SNAKE_CASE : Any = xmod_layer.self_attn_layer_norm.weight
__SCREAMING_SNAKE_CASE : Union[str, Any] = xmod_layer.self_attn_layer_norm.bias
# intermediate
__SCREAMING_SNAKE_CASE : List[Any] = layer.intermediate
if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape:
raise AssertionError("""Dimensions of intermediate weights do not match.""" )
__SCREAMING_SNAKE_CASE : Optional[Any] = xmod_layer.fca.weight
__SCREAMING_SNAKE_CASE : int = xmod_layer.fca.bias
# output
__SCREAMING_SNAKE_CASE : int = layer.output
if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
raise AssertionError("""Dimensions of feed-forward weights do not match.""" )
__SCREAMING_SNAKE_CASE : Any = xmod_layer.fca.weight
__SCREAMING_SNAKE_CASE : Optional[int] = xmod_layer.fca.bias
__SCREAMING_SNAKE_CASE : str = xmod_layer.final_layer_norm.weight
__SCREAMING_SNAKE_CASE : str = xmod_layer.final_layer_norm.bias
if bert_output.adapter_layer_norm is not None:
__SCREAMING_SNAKE_CASE : str = xmod_layer.adapter_layer_norm.weight
__SCREAMING_SNAKE_CASE : Optional[int] = xmod_layer.adapter_layer_norm.bias
if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ):
raise AssertionError("""Lists of language adapters do not match.""" )
for lang_code, adapter in xmod_layer.adapter_modules.items():
__SCREAMING_SNAKE_CASE : Union[str, Any] = bert_output.adapter_modules[lang_code]
__SCREAMING_SNAKE_CASE : Optional[int] = xmod_layer.adapter_modules[lang_code]
__SCREAMING_SNAKE_CASE : Optional[int] = from_adapter.fca.weight
__SCREAMING_SNAKE_CASE : List[str] = from_adapter.fca.bias
__SCREAMING_SNAKE_CASE : List[Any] = from_adapter.fca.weight
__SCREAMING_SNAKE_CASE : Optional[int] = from_adapter.fca.bias
# end of layer
if xmod_sent_encoder.layer_norm is not None:
__SCREAMING_SNAKE_CASE : List[Any] = xmod_sent_encoder.layer_norm.weight
__SCREAMING_SNAKE_CASE : Optional[int] = xmod_sent_encoder.layer_norm.bias
if classification_head:
__SCREAMING_SNAKE_CASE : List[Any] = xmod.model.classification_heads["""mnli"""].dense.weight
__SCREAMING_SNAKE_CASE : str = xmod.model.classification_heads["""mnli"""].dense.bias
__SCREAMING_SNAKE_CASE : str = xmod.model.classification_heads["""mnli"""].out_proj.weight
__SCREAMING_SNAKE_CASE : int = xmod.model.classification_heads["""mnli"""].out_proj.bias
else:
# LM Head
__SCREAMING_SNAKE_CASE : Union[str, Any] = xmod.model.encoder.lm_head.dense.weight
__SCREAMING_SNAKE_CASE : Tuple = xmod.model.encoder.lm_head.dense.bias
__SCREAMING_SNAKE_CASE : str = xmod.model.encoder.lm_head.layer_norm.weight
__SCREAMING_SNAKE_CASE : List[str] = xmod.model.encoder.lm_head.layer_norm.bias
__SCREAMING_SNAKE_CASE : Optional[Any] = xmod.model.encoder.lm_head.weight
__SCREAMING_SNAKE_CASE : List[Any] = xmod.model.encoder.lm_head.bias
# Let's check that we get the same results.
__SCREAMING_SNAKE_CASE : int = xmod.encode(_lowerCamelCase ).unsqueeze(0 ) # batch of size 1
model.roberta.set_default_language(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase )[0]
if classification_head:
__SCREAMING_SNAKE_CASE : Dict = xmod.model.classification_heads["""mnli"""](xmod.extract_features(_lowerCamelCase ) )
else:
__SCREAMING_SNAKE_CASE : Any = xmod.model(_lowerCamelCase , lang_id=[SAMPLE_LANGUAGE] )[0]
print(our_output.shape , their_output.shape )
__SCREAMING_SNAKE_CASE : Union[str, Any] = torch.max(torch.abs(our_output - their_output ) ).item()
print(F"max_absolute_diff = {max_absolute_diff}" ) # ~ 1e-7
__SCREAMING_SNAKE_CASE : Dict = torch.allclose(_lowerCamelCase , _lowerCamelCase , atol=1E-3 )
print("""Do both models output the same tensors?""" , """🔥""" if success else """💩""" )
if not success:
raise Exception("""Something went wRoNg""" )
Path(_lowerCamelCase ).mkdir(parents=_lowerCamelCase , exist_ok=_lowerCamelCase )
print(F"Saving model to {pytorch_dump_folder_path}" )
model.save_pretrained(_lowerCamelCase )
if __name__ == "__main__":
UpperCamelCase__ : Optional[int] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--xmod_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.'''
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
parser.add_argument(
'''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.'''
)
UpperCamelCase__ : int = parser.parse_args()
convert_xmod_checkpoint_to_pytorch(
args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
)
| 178 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCamelCase__ : List[Any] = {
'''configuration_time_series_transformer''': [
'''TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''TimeSeriesTransformerConfig''',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : List[Any] = [
'''TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TimeSeriesTransformerForPrediction''',
'''TimeSeriesTransformerModel''',
'''TimeSeriesTransformerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_time_series_transformer import (
TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
TimeSeriesTransformerConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_time_series_transformer import (
TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TimeSeriesTransformerForPrediction,
TimeSeriesTransformerModel,
TimeSeriesTransformerPreTrainedModel,
)
else:
import sys
UpperCamelCase__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 178 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.