code
stringlengths 82
53.2k
| code_codestyle
int64 0
721
| style_context
stringlengths 91
41.9k
| style_context_codestyle
int64 0
699
| label
int64 0
1
|
|---|---|---|---|---|
'''simple docstring'''
import webbrowser
from sys import argv
from urllib.parse import parse_qs, quote
import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent
if __name__ == "__main__":
lowerCamelCase = """%20""".join(argv[1:]) if len(argv) > 1 else quote(str(input("""Search: """)))
print("""Googling.....""")
lowerCamelCase = f"https://www.google.com/search?q={query}&num=100"
lowerCamelCase = requests.get(
url,
headers={"""User-Agent""": str(UserAgent().random)},
)
try:
lowerCamelCase = (
BeautifulSoup(res.text, """html.parser""")
.find("""div""", attrs={"""class""": """yuRUbf"""})
.find("""a""")
.get("""href""")
)
except AttributeError:
lowerCamelCase = parse_qs(
BeautifulSoup(res.text, """html.parser""")
.find("""div""", attrs={"""class""": """kCrYT"""})
.find("""a""")
.get("""href""")
)["""url"""][0]
webbrowser.open(link)
| 474
|
'''simple docstring'''
import os
def _A ( ):
"""simple docstring"""
__lowercase =os.path.join(os.path.dirname(_lowerCAmelCase ) , 'num.txt' )
with open(_lowerCAmelCase ) as file_hand:
return str(sum(int(_lowerCAmelCase ) for line in file_hand ) )[:10]
if __name__ == "__main__":
print(solution())
| 474
| 1
|
def A (__A : int = 1000000 ) -> int:
"""simple docstring"""
UpperCAmelCase_ = limit + 1
UpperCAmelCase_ = [0] * limit
for first_term in range(1 , __A ):
for n in range(__A , __A , __A ):
UpperCAmelCase_ = first_term + n / first_term
if common_difference % 4: # d must be divisble by 4
continue
else:
common_difference /= 4
if (
first_term > common_difference
and first_term < 4 * common_difference
): # since x,y,z are positive integers
frequency[n] += 1 # so z>0 and a>d ,also 4d<a
UpperCAmelCase_ = sum(1 for x in frequency[1:limit] if x == 10 )
return count
if __name__ == "__main__":
print(f"{solution() = }")
| 169
|
from __future__ import annotations
def A (__A : list[int] ) -> list[int]: # This function is recursive
"""simple docstring"""
UpperCAmelCase_ = len(__A )
# If the array contains only one element, we return it (it's the stop condition of
# recursion)
if array_length <= 1:
return array
# Else
UpperCAmelCase_ = array[0]
UpperCAmelCase_ = False
UpperCAmelCase_ = 1
UpperCAmelCase_ = []
while not is_found and i < array_length:
if array[i] < pivot:
UpperCAmelCase_ = True
UpperCAmelCase_ = [element for element in array[i:] if element >= array[i]]
UpperCAmelCase_ = longest_subsequence(__A )
if len(__A ) > len(__A ):
UpperCAmelCase_ = temp_array
else:
i += 1
UpperCAmelCase_ = [element for element in array[1:] if element >= pivot]
UpperCAmelCase_ = [pivot, *longest_subsequence(__A )]
if len(__A ) > len(__A ):
return temp_array
else:
return longest_subseq
if __name__ == "__main__":
import doctest
doctest.testmod()
| 169
| 1
|
'''simple docstring'''
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase : Dict = logging.get_logger(__name__)
UpperCamelCase : Optional[Any] = {
'asapp/sew-tiny-100k': 'https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json',
# See all SEW models at https://huggingface.co/models?filter=sew
}
class UpperCamelCase__ (a ):
'''simple docstring'''
_UpperCamelCase = 'sew'
def __init__( self ,_lowerCAmelCase=32 ,_lowerCAmelCase=7_68 ,_lowerCAmelCase=12 ,_lowerCAmelCase=12 ,_lowerCAmelCase=30_72 ,_lowerCAmelCase=2 ,_lowerCAmelCase="gelu" ,_lowerCAmelCase=0.1 ,_lowerCAmelCase=0.1 ,_lowerCAmelCase=0.1 ,_lowerCAmelCase=0.0 ,_lowerCAmelCase=0.1 ,_lowerCAmelCase=0.1 ,_lowerCAmelCase=0.02 ,_lowerCAmelCase=1E-5 ,_lowerCAmelCase="group" ,_lowerCAmelCase="gelu" ,_lowerCAmelCase=(64, 1_28, 1_28, 1_28, 1_28, 2_56, 2_56, 2_56, 2_56, 5_12, 5_12, 5_12, 5_12) ,_lowerCAmelCase=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) ,_lowerCAmelCase=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) ,_lowerCAmelCase=False ,_lowerCAmelCase=1_28 ,_lowerCAmelCase=16 ,_lowerCAmelCase=True ,_lowerCAmelCase=0.05 ,_lowerCAmelCase=10 ,_lowerCAmelCase=2 ,_lowerCAmelCase=0.0 ,_lowerCAmelCase=10 ,_lowerCAmelCase=0 ,_lowerCAmelCase="mean" ,_lowerCAmelCase=False ,_lowerCAmelCase=False ,_lowerCAmelCase=2_56 ,_lowerCAmelCase=0 ,_lowerCAmelCase=1 ,_lowerCAmelCase=2 ,**_lowerCAmelCase ,):
super().__init__(**_lowerCAmelCase ,pad_token_id=_lowerCAmelCase ,bos_token_id=_lowerCAmelCase ,eos_token_id=_lowerCAmelCase )
lowerCamelCase__ = hidden_size
lowerCamelCase__ = feat_extract_norm
lowerCamelCase__ = feat_extract_activation
lowerCamelCase__ = list(_lowerCAmelCase )
lowerCamelCase__ = list(_lowerCAmelCase )
lowerCamelCase__ = list(_lowerCAmelCase )
lowerCamelCase__ = conv_bias
lowerCamelCase__ = num_conv_pos_embeddings
lowerCamelCase__ = num_conv_pos_embedding_groups
lowerCamelCase__ = len(self.conv_dim )
lowerCamelCase__ = num_hidden_layers
lowerCamelCase__ = intermediate_size
lowerCamelCase__ = squeeze_factor
lowerCamelCase__ = hidden_act
lowerCamelCase__ = num_attention_heads
lowerCamelCase__ = hidden_dropout
lowerCamelCase__ = attention_dropout
lowerCamelCase__ = activation_dropout
lowerCamelCase__ = feat_proj_dropout
lowerCamelCase__ = final_dropout
lowerCamelCase__ = layerdrop
lowerCamelCase__ = layer_norm_eps
lowerCamelCase__ = initializer_range
lowerCamelCase__ = vocab_size
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)`,"""
F'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)'''
F'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
lowerCamelCase__ = apply_spec_augment
lowerCamelCase__ = mask_time_prob
lowerCamelCase__ = mask_time_length
lowerCamelCase__ = mask_time_min_masks
lowerCamelCase__ = mask_feature_prob
lowerCamelCase__ = mask_feature_length
lowerCamelCase__ = mask_feature_min_masks
# ctc loss
lowerCamelCase__ = ctc_loss_reduction
lowerCamelCase__ = ctc_zero_infinity
# sequence classification
lowerCamelCase__ = use_weighted_layer_sum
lowerCamelCase__ = classifier_proj_size
@property
def UpperCamelCase_ ( self ):
return functools.reduce(operator.mul ,self.conv_stride ,1 )
| 50
|
import argparse
import shlex
import runhouse as rh
if __name__ == "__main__":
# Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access
# setup instructions, if using on-demand hardware
# If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster
# If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster
# Throw an error if user passes both BYO and on-demand cluster args
# Otherwise, use default values
UpperCamelCase = argparse.ArgumentParser()
parser.add_argument("""--user""", type=str, default="""ubuntu""")
parser.add_argument("""--host""", type=str, default="""localhost""")
parser.add_argument("""--key_path""", type=str, default=None)
parser.add_argument("""--instance""", type=str, default="""V100:1""")
parser.add_argument("""--provider""", type=str, default="""cheapest""")
parser.add_argument("""--use_spot""", type=bool, default=False)
parser.add_argument("""--example""", type=str, default="""pytorch/text-generation/run_generation.py""")
UpperCamelCase , UpperCamelCase = parser.parse_known_args()
if args.host != "localhost":
if args.instance != "V100:1" or args.provider != "cheapest":
raise ValueError("""Cannot specify both BYO and on-demand cluster args""")
UpperCamelCase = rh.cluster(
name="""rh-cluster""", ips=[args.host], ssh_creds={"""ssh_user""": args.user, """ssh_private_key""": args.key_path}
)
else:
UpperCamelCase = rh.cluster(
name="""rh-cluster""", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot
)
UpperCamelCase = args.example.rsplit("""/""", 1)[0]
# Set up remote environment
cluster.install_packages(["""pip:./"""]) # Installs transformers from local source
# Note transformers is copied into the home directory on the remote machine, so we can install from there
cluster.run([F'''pip install -r transformers/examples/{example_dir}/requirements.txt'''])
cluster.run(["""pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"""])
# Run example. You can bypass the CLI wrapper and paste your own code here.
cluster.run([F'''python transformers/examples/{args.example} {' '.join(shlex.quote(arg) for arg in unknown)}'''])
# Alternatively, we can just import and run a training function (especially if there's no wrapper CLI):
# from my_script... import train
# reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard']
# launch_train_gpu = rh.function(fn=train,
# system=gpu,
# reqs=reqs,
# name='train_bert_glue')
#
# We can pass in arguments just like we would to a function:
# launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16
# stream_logs=True)
| 590
| 0
|
"""simple docstring"""
from ..utils import DummyObject, requires_backends
class UpperCAmelCase_ ( metaclass=_a):
lowerCamelCase__ : str = ["onnx"]
def __init__( self , *a , **a ) -> List[str]:
requires_backends(self , ['onnx'] )
@classmethod
def _UpperCAmelCase ( cls , *a , **a ) -> Tuple:
requires_backends(cls , ['onnx'] )
@classmethod
def _UpperCAmelCase ( cls , *a , **a ) -> str:
requires_backends(cls , ['onnx'] )
| 645
|
"""simple docstring"""
import hashlib
import unittest
from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available
from transformers.pipelines import DepthEstimationPipeline, pipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_tf,
require_timm,
require_torch,
require_vision,
slow,
)
from .test_pipelines_common import ANY
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
else:
class UpperCAmelCase_ :
@staticmethod
def _UpperCAmelCase ( *a , **a ) -> int:
pass
def a_ ( _lowerCAmelCase : Image ):
'''simple docstring'''
lowercase__ : List[str] = hashlib.mda(image.tobytes() )
return m.hexdigest()
@is_pipeline_test
@require_vision
@require_timm
@require_torch
class UpperCAmelCase_ ( unittest.TestCase):
lowerCamelCase__ : Union[str, Any] = MODEL_FOR_DEPTH_ESTIMATION_MAPPING
def _UpperCAmelCase ( self , a , a , a ) -> Dict:
lowercase__ : Union[str, Any] = DepthEstimationPipeline(model=a , image_processor=a )
return depth_estimator, [
"./tests/fixtures/tests_samples/COCO/000000039769.png",
"./tests/fixtures/tests_samples/COCO/000000039769.png",
]
def _UpperCAmelCase ( self , a , a ) -> Optional[int]:
lowercase__ : Tuple = depth_estimator('./tests/fixtures/tests_samples/COCO/000000039769.png' )
self.assertEqual({'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )} , a )
import datasets
lowercase__ : Tuple = datasets.load_dataset('hf-internal-testing/fixtures_image_utils' , 'image' , split='test' )
lowercase__ : List[Any] = depth_estimator(
[
Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ),
'http://images.cocodataset.org/val2017/000000039769.jpg',
# RGBA
dataset[0]['file'],
# LA
dataset[1]['file'],
# L
dataset[2]['file'],
] )
self.assertEqual(
[
{'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )},
{'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )},
{'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )},
{'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )},
{'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )},
] , a , )
@require_tf
@unittest.skip('Depth estimation is not implemented in TF' )
def _UpperCAmelCase ( self ) -> Optional[int]:
pass
@slow
@require_torch
def _UpperCAmelCase ( self ) -> Tuple:
lowercase__ : Tuple = 'Intel/dpt-large'
lowercase__ : Optional[int] = pipeline('depth-estimation' , model=a )
lowercase__ : List[Any] = depth_estimator('http://images.cocodataset.org/val2017/000000039769.jpg' )
lowercase__ : Optional[Any] = hashimage(outputs['depth'] )
# This seems flaky.
# self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977")
self.assertEqual(nested_simplify(outputs['predicted_depth'].max().item() ) , 29.304 )
self.assertEqual(nested_simplify(outputs['predicted_depth'].min().item() ) , 2.662 )
@require_torch
def _UpperCAmelCase ( self ) -> Optional[int]:
# This is highly irregular to have no small tests.
self.skipTest('There is not hf-internal-testing tiny model for either GLPN nor DPT' )
| 645
| 1
|
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__snake_case ={
"""configuration_whisper""": ["""WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """WhisperConfig""", """WhisperOnnxConfig"""],
"""feature_extraction_whisper""": ["""WhisperFeatureExtractor"""],
"""processing_whisper""": ["""WhisperProcessor"""],
"""tokenization_whisper""": ["""WhisperTokenizer"""],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case =["""WhisperTokenizerFast"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case =[
"""WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""WhisperForConditionalGeneration""",
"""WhisperModel""",
"""WhisperPreTrainedModel""",
"""WhisperForAudioClassification""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case =[
"""TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFWhisperForConditionalGeneration""",
"""TFWhisperModel""",
"""TFWhisperPreTrainedModel""",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case =[
"""FlaxWhisperForConditionalGeneration""",
"""FlaxWhisperModel""",
"""FlaxWhisperPreTrainedModel""",
"""FlaxWhisperForAudioClassification""",
]
if TYPE_CHECKING:
from .configuration_whisper import WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP, WhisperConfig, WhisperOnnxConfig
from .feature_extraction_whisper import WhisperFeatureExtractor
from .processing_whisper import WhisperProcessor
from .tokenization_whisper import WhisperTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_whisper_fast import WhisperTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_whisper import (
WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST,
WhisperForAudioClassification,
WhisperForConditionalGeneration,
WhisperModel,
WhisperPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_whisper import (
TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST,
TFWhisperForConditionalGeneration,
TFWhisperModel,
TFWhisperPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_whisper import (
FlaxWhisperForAudioClassification,
FlaxWhisperForConditionalGeneration,
FlaxWhisperModel,
FlaxWhisperPreTrainedModel,
)
else:
import sys
__snake_case =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 133
|
'''simple docstring'''
import random
import timeit
from functools import wraps
from typing import Callable, Optional
from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
Benchmark,
Memory,
MemorySummary,
measure_peak_memory_cpu,
start_memory_tracing,
stop_memory_tracing,
)
if is_tf_available():
import tensorflow as tf
from tensorflow.python.framework.errors_impl import ResourceExhaustedError
from .benchmark_args_tf import TensorFlowBenchmarkArguments
if is_pyanvml_available():
import pyanvml.pyanvml as nvml
__snake_case =logging.get_logger(__name__)
def a_ ( lowerCamelCase : bool , lowerCamelCase : bool ):
def run_func(lowerCamelCase : Dict ):
@wraps(lowerCamelCase )
def run_in_eager_mode(*lowerCamelCase : int , **lowerCamelCase : Dict ):
return func(*lowerCamelCase , **lowerCamelCase )
@wraps(lowerCamelCase )
@tf.function(experimental_compile=lowerCamelCase )
def run_in_graph_mode(*lowerCamelCase : Tuple , **lowerCamelCase : Union[str, Any] ):
return func(*lowerCamelCase , **lowerCamelCase )
if do_eager_mode is True:
if use_xla is not False:
raise ValueError(
'Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.' )
return run_in_eager_mode
else:
return run_in_graph_mode
return run_func
def a_ ( lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : int ):
lowerCAmelCase = random.Random()
lowerCAmelCase = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )]
return tf.constant(lowerCamelCase , shape=(batch_size, sequence_length) , dtype=tf.intaa )
class UpperCAmelCase_ ( __lowercase ):
lowerCamelCase : TensorFlowBenchmarkArguments
lowerCamelCase : PretrainedConfig
lowerCamelCase : str = "TensorFlow"
@property
def __UpperCAmelCase ( self : List[str] ) -> Dict:
return tf.__version__
def __UpperCAmelCase ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> float:
# initialize GPU on separate process
lowerCAmelCase = self.args.strategy
if strategy is None:
raise ValueError('A device strategy has to be initialized before using TensorFlow.' )
lowerCAmelCase = self._prepare_inference_func(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
return self._measure_speed(_inference )
def __UpperCAmelCase ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> float:
lowerCAmelCase = self.args.strategy
if strategy is None:
raise ValueError('A device strategy has to be initialized before using TensorFlow.' )
lowerCAmelCase = self._prepare_train_func(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
return self._measure_speed(_train )
def __UpperCAmelCase ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> [Memory, Optional[MemorySummary]]:
# initialize GPU on separate process
if self.args.is_gpu:
tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , UpperCAmelCase__ )
lowerCAmelCase = self.args.strategy
if strategy is None:
raise ValueError('A device strategy has to be initialized before using TensorFlow.' )
lowerCAmelCase = self._prepare_inference_func(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
return self._measure_memory(_inference )
def __UpperCAmelCase ( self : Dict , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> [Memory, Optional[MemorySummary]]:
if self.args.is_gpu:
tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , UpperCAmelCase__ )
lowerCAmelCase = self.args.strategy
if strategy is None:
raise ValueError('A device strategy has to be initialized before using TensorFlow.' )
lowerCAmelCase = self._prepare_train_func(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
return self._measure_memory(_train )
def __UpperCAmelCase ( self : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Callable[[], None]:
lowerCAmelCase = self.config_dict[model_name]
if self.args.fpaa:
raise NotImplementedError('Mixed precision is currently not supported.' )
lowerCAmelCase = (
hasattr(UpperCAmelCase__ , 'architectures' )
and isinstance(config.architectures , UpperCAmelCase__ )
and len(config.architectures ) > 0
)
if not self.args.only_pretrain_model and has_model_class_in_config:
try:
lowerCAmelCase = 'TF' + config.architectures[0] # prepend 'TF' for tensorflow model
lowerCAmelCase = __import__('transformers' , fromlist=[model_class] )
lowerCAmelCase = getattr(UpperCAmelCase__ , UpperCAmelCase__ )
lowerCAmelCase = model_cls(UpperCAmelCase__ )
except ImportError:
raise ImportError(
F'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
' set `--only_pretrain_model` or `args.only_pretrain_model=True`.' )
else:
lowerCAmelCase = TF_MODEL_MAPPING[config.__class__](UpperCAmelCase__ )
# encoder-decoder has vocab size saved differently
lowerCAmelCase = config.vocab_size if hasattr(UpperCAmelCase__ , 'vocab_size' ) else config.encoder.vocab_size
lowerCAmelCase = random_input_ids(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
@run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla )
def encoder_decoder_forward():
return model(UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ , training=UpperCAmelCase__ )
@run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla )
def encoder_forward():
return model(UpperCAmelCase__ , training=UpperCAmelCase__ )
lowerCAmelCase = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward
return _inference
def __UpperCAmelCase ( self : str , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Callable[[], None]:
lowerCAmelCase = self.config_dict[model_name]
if self.args.eager_mode is not False:
raise ValueError('Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.' )
if self.args.fpaa:
raise NotImplementedError('Mixed precision is currently not supported.' )
lowerCAmelCase = (
hasattr(UpperCAmelCase__ , 'architectures' )
and isinstance(config.architectures , UpperCAmelCase__ )
and len(config.architectures ) > 0
)
if not self.args.only_pretrain_model and has_model_class_in_config:
try:
lowerCAmelCase = 'TF' + config.architectures[0] # prepend 'TF' for tensorflow model
lowerCAmelCase = __import__('transformers' , fromlist=[model_class] )
lowerCAmelCase = getattr(UpperCAmelCase__ , UpperCAmelCase__ )
lowerCAmelCase = model_cls(UpperCAmelCase__ )
except ImportError:
raise ImportError(
F'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
' set `--only_pretrain_model` or `args.only_pretrain_model=True`.' )
else:
lowerCAmelCase = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](UpperCAmelCase__ )
# encoder-decoder has vocab size saved differently
lowerCAmelCase = config.vocab_size if hasattr(UpperCAmelCase__ , 'vocab_size' ) else config.encoder.vocab_size
lowerCAmelCase = random_input_ids(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
@run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla )
def encoder_decoder_train():
lowerCAmelCase = model(UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , training=UpperCAmelCase__ )[0]
lowerCAmelCase = tf.gradients(UpperCAmelCase__ , model.trainable_variables )
return gradients
@run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla )
def encoder_train():
lowerCAmelCase = model(UpperCAmelCase__ , labels=UpperCAmelCase__ , training=UpperCAmelCase__ )[0]
lowerCAmelCase = tf.gradients(UpperCAmelCase__ , model.trainable_variables )
return gradients
lowerCAmelCase = encoder_decoder_train if config.is_encoder_decoder else encoder_train
return _train
def __UpperCAmelCase ( self : int , UpperCAmelCase__ : str ) -> float:
with self.args.strategy.scope():
try:
if self.args.is_tpu or self.args.use_xla:
# run additional 10 times to stabilize compilation for tpu
logger.info('Do inference on TPU. Running model 5 times to stabilize compilation' )
timeit.repeat(UpperCAmelCase__ , repeat=1 , number=5 )
# as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
lowerCAmelCase = timeit.repeat(
UpperCAmelCase__ , repeat=self.args.repeat , number=1_0 , )
return min(UpperCAmelCase__ ) / 10.0
except ResourceExhaustedError as e:
self.print_fn(F'''Doesn\'t fit on GPU. {e}''' )
def __UpperCAmelCase ( self : Optional[Any] , UpperCAmelCase__ : Callable[[], None] ) -> [Memory, MemorySummary]:
logger.info(
'Note that TensorFlow allocates more memory than '
'it might need to speed up computation. '
'The memory reported here corresponds to the memory '
'reported by `nvidia-smi`, which can vary depending '
'on total available memory on the GPU that is used.' )
with self.args.strategy.scope():
try:
if self.args.trace_memory_line_by_line:
if not self.args.eager_mode:
raise ValueError(
'`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory'
' consumption line by line.' )
lowerCAmelCase = start_memory_tracing('transformers' )
if self.args.is_tpu:
# tpu
raise NotImplementedError(
'Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking'
' with `args.memory=False`' )
elif self.args.is_gpu:
# gpu
if not is_pyanvml_available():
logger.warning(
'py3nvml not installed, we won\'t log GPU memory usage. '
'Install py3nvml (pip install py3nvml) to log information about GPU.' )
lowerCAmelCase = 'N/A'
else:
logger.info(
'Measuring total GPU usage on GPU device. Make sure to not have additional processes'
' running on the same GPU.' )
# init nvml
nvml.nvmlInit()
func()
lowerCAmelCase = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx )
lowerCAmelCase = nvml.nvmlDeviceGetMemoryInfo(UpperCAmelCase__ )
lowerCAmelCase = meminfo.used
lowerCAmelCase = Memory(UpperCAmelCase__ )
# shutdown nvml
nvml.nvmlShutdown()
else:
# cpu
if self.args.trace_memory_line_by_line:
logger.info(
'When enabling line by line tracing, the max peak memory for CPU is inaccurate in'
' TensorFlow.' )
lowerCAmelCase = None
else:
lowerCAmelCase = measure_peak_memory_cpu(UpperCAmelCase__ )
lowerCAmelCase = Memory(UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else memory_bytes
if self.args.trace_memory_line_by_line:
lowerCAmelCase = stop_memory_tracing(UpperCAmelCase__ )
if memory is None:
lowerCAmelCase = summary.total
else:
lowerCAmelCase = None
return memory, summary
except ResourceExhaustedError as e:
self.print_fn(F'''Doesn\'t fit on GPU. {e}''' )
return "N/A", None
| 133
| 1
|
'''simple docstring'''
import math_equivalence # From: git+https://github.com/hendrycks/math.git
import datasets
A_ : List[str] = "\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n"
A_ : int = "\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy.\n"
A_ : Optional[Any] = R"\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting \"1/2\" to \"\\frac{1}{2}\")\n\nExamples:\n >>> metric = datasets.load_metric(\"competition_math\")\n >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"])\n >>> print(results)\n {'accuracy': 1.0}\n"
@datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class __snake_case ( datasets.Metric ):
'''simple docstring'''
def __UpperCamelCase ( self ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"""predictions""": datasets.Value("""string""" ),
"""references""": datasets.Value("""string""" ),
} ) , homepage="""https://github.com/hendrycks/math""" , codebase_urls=["""https://github.com/hendrycks/math"""] , )
def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
snake_case__ : Optional[int] = 0.0
for i, j in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
n_correct += 1.0 if math_equivalence.is_equiv(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else 0.0
snake_case__ : str = n_correct / len(__SCREAMING_SNAKE_CASE )
return {
"accuracy": accuracy,
}
| 419
|
'''simple docstring'''
class __snake_case :
'''simple docstring'''
def __init__( self , __SCREAMING_SNAKE_CASE ):
snake_case__ : Dict = val
snake_case__ : List[str] = None
snake_case__ : Tuple = None
def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ):
if self.val:
if val < self.val:
if self.left is None:
snake_case__ : Any = Node(__SCREAMING_SNAKE_CASE )
else:
self.left.insert(__SCREAMING_SNAKE_CASE )
elif val > self.val:
if self.right is None:
snake_case__ : List[Any] = Node(__SCREAMING_SNAKE_CASE )
else:
self.right.insert(__SCREAMING_SNAKE_CASE )
else:
snake_case__ : Tuple = val
def UpperCamelCase__ ( __magic_name__ : Optional[int] , __magic_name__ : Union[str, Any] ) -> List[Any]:
'''simple docstring'''
if root:
inorder(root.left , __magic_name__ )
res.append(root.val )
inorder(root.right , __magic_name__ )
def UpperCamelCase__ ( __magic_name__ : Union[str, Any] ) -> str:
'''simple docstring'''
if len(__magic_name__ ) == 0:
return arr
snake_case__ : int = Node(arr[0] )
for i in range(1 , len(__magic_name__ ) ):
root.insert(arr[i] )
# Traverse BST in order.
snake_case__ : str = []
inorder(__magic_name__ , __magic_name__ )
return res
if __name__ == "__main__":
print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
| 419
| 1
|
'''simple docstring'''
def lowercase__( __UpperCamelCase: str ):
"""simple docstring"""
return " ".join(input_str.split()[::-1] )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 28
|
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
UpperCamelCase_ = {
"configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"],
"tokenization_roformer": ["RoFormerTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ = ["RoFormerTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ = [
"ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
"RoFormerForCausalLM",
"RoFormerForMaskedLM",
"RoFormerForMultipleChoice",
"RoFormerForQuestionAnswering",
"RoFormerForSequenceClassification",
"RoFormerForTokenClassification",
"RoFormerLayer",
"RoFormerModel",
"RoFormerPreTrainedModel",
"load_tf_weights_in_roformer",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ = [
"TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFRoFormerForCausalLM",
"TFRoFormerForMaskedLM",
"TFRoFormerForMultipleChoice",
"TFRoFormerForQuestionAnswering",
"TFRoFormerForSequenceClassification",
"TFRoFormerForTokenClassification",
"TFRoFormerLayer",
"TFRoFormerModel",
"TFRoFormerPreTrainedModel",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ = [
"FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
"FlaxRoFormerForMaskedLM",
"FlaxRoFormerForMultipleChoice",
"FlaxRoFormerForQuestionAnswering",
"FlaxRoFormerForSequenceClassification",
"FlaxRoFormerForTokenClassification",
"FlaxRoFormerModel",
"FlaxRoFormerPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig
from .tokenization_roformer import RoFormerTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_roformer_fast import RoFormerTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_roformer import (
ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
RoFormerForCausalLM,
RoFormerForMaskedLM,
RoFormerForMultipleChoice,
RoFormerForQuestionAnswering,
RoFormerForSequenceClassification,
RoFormerForTokenClassification,
RoFormerLayer,
RoFormerModel,
RoFormerPreTrainedModel,
load_tf_weights_in_roformer,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_roformer import (
TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TFRoFormerForCausalLM,
TFRoFormerForMaskedLM,
TFRoFormerForMultipleChoice,
TFRoFormerForQuestionAnswering,
TFRoFormerForSequenceClassification,
TFRoFormerForTokenClassification,
TFRoFormerLayer,
TFRoFormerModel,
TFRoFormerPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_roformer import (
FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
FlaxRoFormerForMaskedLM,
FlaxRoFormerForMultipleChoice,
FlaxRoFormerForQuestionAnswering,
FlaxRoFormerForSequenceClassification,
FlaxRoFormerForTokenClassification,
FlaxRoFormerModel,
FlaxRoFormerPreTrainedModel,
)
else:
import sys
UpperCamelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 28
| 1
|
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_speech_available,
is_tf_available,
is_torch_available,
)
_lowerCamelCase = {
"""configuration_speech_to_text""": ["""SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2TextConfig"""],
"""processing_speech_to_text""": ["""Speech2TextProcessor"""],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase = ["""Speech2TextTokenizer"""]
try:
if not is_speech_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase = ["""Speech2TextFeatureExtractor"""]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase = [
"""TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFSpeech2TextForConditionalGeneration""",
"""TFSpeech2TextModel""",
"""TFSpeech2TextPreTrainedModel""",
]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase = [
"""SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""Speech2TextForConditionalGeneration""",
"""Speech2TextModel""",
"""Speech2TextPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig
from .processing_speech_to_text import SpeechaTextProcessor
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_speech_to_text import SpeechaTextTokenizer
try:
if not is_speech_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_speech_to_text import (
TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFSpeechaTextForConditionalGeneration,
TFSpeechaTextModel,
TFSpeechaTextPreTrainedModel,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_speech_to_text import (
SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
SpeechaTextForConditionalGeneration,
SpeechaTextModel,
SpeechaTextPreTrainedModel,
)
else:
import sys
_lowerCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 700
|
'''simple docstring'''
import random
import torch
from huggingface_hub import HfApi
from diffusers import UNetaDModel
_lowerCamelCase : Optional[int] = HfApi()
_lowerCamelCase : Union[str, Any] = {}
# fmt: off
_lowerCamelCase : List[Any] = torch.tensor([
-0.7_515, -1.6_883, 0.2_420, 0.0_300, 0.6_347, 1.3_433, -1.1_743, -3.7_467,
1.2_342, -2.2_485, 0.4_636, 0.8_076, -0.7_991, 0.3_969, 0.8_498, 0.9_189,
-1.8_887, -3.3_522, 0.7_639, 0.2_040, 0.6_271, -2.7_148, -1.6_316, 3.0_839,
0.3_186, 0.2_721, -0.9_759, -1.2_461, 2.6_257, 1.3_557
])
_lowerCamelCase : Tuple = torch.tensor([
-2.3_639, -2.5_344, 0.0_054, -0.6_674, 1.5_990, 1.0_158, 0.3_124, -2.1_436,
1.8_795, -2.5_429, -0.1_566, -0.3_973, 1.2_490, 2.6_447, 1.2_283, -0.5_208,
-2.8_154, -3.5_119, 2.3_838, 1.2_033, 1.7_201, -2.1_256, -1.4_576, 2.7_948,
2.4_204, -0.9_752, -1.2_546, 0.8_027, 3.2_758, 3.1_365
])
_lowerCamelCase : str = torch.tensor([
-0.6_531, -0.6_891, -0.3_172, -0.5_375, -0.9_140, -0.5_367, -0.1_175, -0.7_869,
-0.3_808, -0.4_513, -0.2_098, -0.0_083, 0.3_183, 0.5_140, 0.2_247, -0.1_304,
-0.1_302, -0.2_802, -0.2_084, -0.2_025, -0.4_967, -0.4_873, -0.0_861, 0.6_925,
0.0_250, 0.1_290, -0.1_543, 0.6_316, 1.0_460, 1.4_943
])
_lowerCamelCase : List[str] = torch.tensor([
0.0_911, 0.1_107, 0.0_182, 0.0_435, -0.0_805, -0.0_608, 0.0_381, 0.2_172,
-0.0_280, 0.1_327, -0.0_299, -0.0_255, -0.0_050, -0.1_170, -0.1_046, 0.0_309,
0.1_367, 0.1_728, -0.0_533, -0.0_748, -0.0_534, 0.1_624, 0.0_384, -0.1_805,
-0.0_707, 0.0_642, 0.0_220, -0.0_134, -0.1_333, -0.1_505
])
_lowerCamelCase : Tuple = torch.tensor([
0.1_321, 0.1_337, 0.0_440, 0.0_622, -0.0_591, -0.0_370, 0.0_503, 0.2_133,
-0.0_177, 0.1_415, -0.0_116, -0.0_112, 0.0_044, -0.0_980, -0.0_789, 0.0_395,
0.1_502, 0.1_785, -0.0_488, -0.0_514, -0.0_404, 0.1_539, 0.0_454, -0.1_559,
-0.0_665, 0.0_659, 0.0_383, -0.0_005, -0.1_266, -0.1_386
])
_lowerCamelCase : List[Any] = torch.tensor([
0.1_154, 0.1_218, 0.0_307, 0.0_526, -0.0_711, -0.0_541, 0.0_366, 0.2_078,
-0.0_267, 0.1_317, -0.0_226, -0.0_193, -0.0_014, -0.1_055, -0.0_902, 0.0_330,
0.1_391, 0.1_709, -0.0_562, -0.0_693, -0.0_560, 0.1_482, 0.0_381, -0.1_683,
-0.0_681, 0.0_661, 0.0_331, -0.0_046, -0.1_268, -0.1_431
])
_lowerCamelCase : str = torch.tensor([
0.1_192, 0.1_240, 0.0_414, 0.0_606, -0.0_557, -0.0_412, 0.0_430, 0.2_042,
-0.0_200, 0.1_385, -0.0_115, -0.0_132, 0.0_017, -0.0_965, -0.0_802, 0.0_398,
0.1_433, 0.1_747, -0.0_458, -0.0_533, -0.0_407, 0.1_545, 0.0_419, -0.1_574,
-0.0_645, 0.0_626, 0.0_341, -0.0_010, -0.1_199, -0.1_390
])
_lowerCamelCase : List[Any] = torch.tensor([
0.1_075, 0.1_074, 0.0_205, 0.0_431, -0.0_774, -0.0_607, 0.0_298, 0.2_042,
-0.0_320, 0.1_267, -0.0_281, -0.0_250, -0.0_064, -0.1_091, -0.0_946, 0.0_290,
0.1_328, 0.1_650, -0.0_580, -0.0_738, -0.0_586, 0.1_440, 0.0_337, -0.1_746,
-0.0_712, 0.0_605, 0.0_250, -0.0_099, -0.1_316, -0.1_473
])
_lowerCamelCase : Dict = torch.tensor([
-1.4_572, -2.0_481, -0.0_414, -0.6_005, 1.4_136, 0.5_848, 0.4_028, -2.7_330,
1.2_212, -2.1_228, 0.2_155, 0.4_039, 0.7_662, 2.0_535, 0.7_477, -0.3_243,
-2.1_758, -2.7_648, 1.6_947, 0.7_026, 1.2_338, -1.6_078, -0.8_682, 2.2_810,
1.8_574, -0.5_718, -0.5_586, -0.0_186, 2.3_415, 2.1_251])
_lowerCamelCase : List[str] = torch.tensor([
-1.3_690, -1.9_720, -0.4_090, -0.6_966, 1.4_660, 0.9_938, -0.1_385, -2.7_324,
0.7_736, -1.8_917, 0.2_923, 0.4_293, 0.1_693, 1.4_112, 1.1_887, -0.3_181,
-2.2_160, -2.6_381, 1.3_170, 0.8_163, 0.9_240, -1.6_544, -0.6_099, 2.5_259,
1.6_430, -0.9_090, -0.9_392, -0.0_126, 2.4_268, 2.3_266
])
_lowerCamelCase : int = torch.tensor([
-1.3_525, -1.9_628, -0.3_956, -0.6_860, 1.4_664, 1.0_014, -0.1_259, -2.7_212,
0.7_772, -1.8_811, 0.2_996, 0.4_388, 0.1_704, 1.4_029, 1.1_701, -0.3_027,
-2.2_053, -2.6_287, 1.3_350, 0.8_131, 0.9_274, -1.6_292, -0.6_098, 2.5_131,
1.6_505, -0.8_958, -0.9_298, -0.0_151, 2.4_257, 2.3_355
])
_lowerCamelCase : Union[str, Any] = torch.tensor([
-2.0_585, -2.7_897, -0.2_850, -0.8_940, 1.9_052, 0.5_702, 0.6_345, -3.8_959,
1.5_932, -3.2_319, 0.1_974, 0.0_287, 1.7_566, 2.6_543, 0.8_387, -0.5_351,
-3.2_736, -4.3_375, 2.9_029, 1.6_390, 1.4_640, -2.1_701, -1.9_013, 2.9_341,
3.4_981, -0.6_255, -1.1_644, -0.1_591, 3.7_097, 3.2_066
])
_lowerCamelCase : Union[str, Any] = torch.tensor([
-2.3_139, -2.5_594, -0.0_197, -0.6_785, 1.7_001, 1.1_606, 0.3_075, -2.1_740,
1.8_071, -2.5_630, -0.0_926, -0.3_811, 1.2_116, 2.6_246, 1.2_731, -0.5_398,
-2.8_153, -3.6_140, 2.3_893, 1.3_262, 1.6_258, -2.1_856, -1.3_267, 2.8_395,
2.3_779, -1.0_623, -1.2_468, 0.8_959, 3.3_367, 3.2_243
])
_lowerCamelCase : Dict = torch.tensor([
-2.0_628, -2.7_667, -0.2_089, -0.8_263, 2.0_539, 0.5_992, 0.6_495, -3.8_336,
1.6_025, -3.2_817, 0.1_721, -0.0_633, 1.7_516, 2.7_039, 0.8_100, -0.5_908,
-3.2_113, -4.4_343, 2.9_257, 1.3_632, 1.5_562, -2.1_489, -1.9_894, 3.0_560,
3.3_396, -0.7_328, -1.0_417, 0.0_383, 3.7_093, 3.2_343
])
_lowerCamelCase : int = torch.tensor([
-1.4_574, -2.0_569, -0.0_473, -0.6_117, 1.4_018, 0.5_769, 0.4_129, -2.7_344,
1.2_241, -2.1_397, 0.2_000, 0.3_937, 0.7_616, 2.0_453, 0.7_324, -0.3_391,
-2.1_746, -2.7_744, 1.6_963, 0.6_921, 1.2_187, -1.6_172, -0.8_877, 2.2_439,
1.8_471, -0.5_839, -0.5_605, -0.0_464, 2.3_250, 2.1_219
])
# fmt: on
_lowerCamelCase : List[str] = api.list_models(filter="""diffusers""")
for mod in models:
if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256":
_lowerCamelCase : Union[str, Any] = """/home/patrick/google_checkpoints/""" + mod.modelId.split("""/""")[-1]
print(f"Started running {mod.modelId}!!!")
if mod.modelId.startswith("""CompVis"""):
_lowerCamelCase : int = UNetaDModel.from_pretrained(local_checkpoint, subfolder="""unet""")
else:
_lowerCamelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint)
torch.manual_seed(0)
random.seed(0)
_lowerCamelCase : Union[str, Any] = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
_lowerCamelCase : List[str] = torch.tensor([10] * noise.shape[0])
with torch.no_grad():
_lowerCamelCase : str = model(noise, time_step).sample
assert torch.allclose(
logits[0, 0, 0, :30], results["""_""".join("""_""".join(mod.modelId.split("""/""")).split("""-"""))], atol=1e-3
)
print(f"{mod.modelId} has passed successfully!!!")
| 512
| 0
|
import os
import tempfile
import unittest
import numpy as np
from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import require_flax, slow
if is_flax_available():
import jax
import jax.numpy as jnp
from flax.jax_utils import replicate
from flax.training.common_utils import shard
from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline
@require_flax
class UpperCamelCase ( unittest.TestCase ):
def A_ (self ) -> Union[str, Any]:
with tempfile.TemporaryDirectory() as tmpdirname:
# pipeline has Flax weights
UpperCamelCase_ : List[Any] = FlaxDiffusionPipeline.from_pretrained(
"""hf-internal-testing/tiny-stable-diffusion-pipe""" , safety_checker=__UpperCamelCase , cache_dir=__UpperCamelCase )
UpperCamelCase_ : List[Any] = [t[-1] for t in os.walk(os.path.join(__UpperCamelCase , os.listdir(__UpperCamelCase )[0] , """snapshots""" ) )]
UpperCamelCase_ : Tuple = [item for sublist in all_root_files for item in sublist]
# None of the downloaded files should be a PyTorch file even if we have some here:
# https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin
assert not any(f.endswith(""".bin""" ) for f in files )
@slow
@require_flax
class UpperCamelCase ( unittest.TestCase ):
def A_ (self ) -> Union[str, Any]:
UpperCamelCase_,UpperCamelCase_ : Tuple = FlaxStableDiffusionPipeline.from_pretrained(
"""hf-internal-testing/tiny-stable-diffusion-pipe""" , safety_checker=__UpperCamelCase )
UpperCamelCase_ : str = (
"""A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
""" field, close up, split lighting, cinematic"""
)
UpperCamelCase_ : str = jax.random.PRNGKey(0 )
UpperCamelCase_ : int = 4
UpperCamelCase_ : Union[str, Any] = jax.device_count()
UpperCamelCase_ : int = num_samples * [prompt]
UpperCamelCase_ : Any = pipeline.prepare_inputs(__UpperCamelCase )
# shard inputs and rng
UpperCamelCase_ : str = replicate(__UpperCamelCase )
UpperCamelCase_ : str = jax.random.split(__UpperCamelCase , __UpperCamelCase )
UpperCamelCase_ : List[str] = shard(__UpperCamelCase )
UpperCamelCase_ : Tuple = pipeline(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , jit=__UpperCamelCase ).images
assert images.shape == (num_samples, 1, 64, 64, 3)
if jax.device_count() == 8:
assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.1_514_745 ) < 1E-3
assert np.abs(np.abs(__UpperCamelCase , dtype=np.floataa ).sum() - 49_947.875 ) < 5E-1
UpperCamelCase_ : Union[str, Any] = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) )
assert len(__UpperCamelCase ) == num_samples
def A_ (self ) -> int:
UpperCamelCase_,UpperCamelCase_ : Optional[Any] = FlaxStableDiffusionPipeline.from_pretrained(
"""CompVis/stable-diffusion-v1-4""" , revision="""flax""" , safety_checker=__UpperCamelCase )
UpperCamelCase_ : str = (
"""A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
""" field, close up, split lighting, cinematic"""
)
UpperCamelCase_ : Optional[Any] = jax.random.PRNGKey(0 )
UpperCamelCase_ : List[str] = 50
UpperCamelCase_ : Tuple = jax.device_count()
UpperCamelCase_ : Optional[Any] = num_samples * [prompt]
UpperCamelCase_ : Tuple = pipeline.prepare_inputs(__UpperCamelCase )
# shard inputs and rng
UpperCamelCase_ : Tuple = replicate(__UpperCamelCase )
UpperCamelCase_ : Optional[int] = jax.random.split(__UpperCamelCase , __UpperCamelCase )
UpperCamelCase_ : Dict = shard(__UpperCamelCase )
UpperCamelCase_ : int = pipeline(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , jit=__UpperCamelCase ).images
assert images.shape == (num_samples, 1, 512, 512, 3)
if jax.device_count() == 8:
assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.05_652_401) ) < 1E-3
assert np.abs((np.abs(__UpperCamelCase , dtype=np.floataa ).sum() - 2_383_808.2) ) < 5E-1
def A_ (self ) -> Optional[Any]:
UpperCamelCase_,UpperCamelCase_ : str = FlaxStableDiffusionPipeline.from_pretrained(
"""CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , safety_checker=__UpperCamelCase )
UpperCamelCase_ : List[str] = (
"""A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
""" field, close up, split lighting, cinematic"""
)
UpperCamelCase_ : Union[str, Any] = jax.random.PRNGKey(0 )
UpperCamelCase_ : Any = 50
UpperCamelCase_ : int = jax.device_count()
UpperCamelCase_ : Dict = num_samples * [prompt]
UpperCamelCase_ : Dict = pipeline.prepare_inputs(__UpperCamelCase )
# shard inputs and rng
UpperCamelCase_ : List[str] = replicate(__UpperCamelCase )
UpperCamelCase_ : Optional[int] = jax.random.split(__UpperCamelCase , __UpperCamelCase )
UpperCamelCase_ : str = shard(__UpperCamelCase )
UpperCamelCase_ : List[str] = pipeline(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , jit=__UpperCamelCase ).images
assert images.shape == (num_samples, 1, 512, 512, 3)
if jax.device_count() == 8:
assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04_003_906) ) < 1E-3
assert np.abs((np.abs(__UpperCamelCase , dtype=np.floataa ).sum() - 2_373_516.75) ) < 5E-1
def A_ (self ) -> Tuple:
UpperCamelCase_,UpperCamelCase_ : List[str] = FlaxStableDiffusionPipeline.from_pretrained(
"""CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa )
UpperCamelCase_ : Optional[Any] = (
"""A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
""" field, close up, split lighting, cinematic"""
)
UpperCamelCase_ : Union[str, Any] = jax.random.PRNGKey(0 )
UpperCamelCase_ : Optional[Any] = 50
UpperCamelCase_ : str = jax.device_count()
UpperCamelCase_ : str = num_samples * [prompt]
UpperCamelCase_ : Dict = pipeline.prepare_inputs(__UpperCamelCase )
# shard inputs and rng
UpperCamelCase_ : Optional[Any] = replicate(__UpperCamelCase )
UpperCamelCase_ : Tuple = jax.random.split(__UpperCamelCase , __UpperCamelCase )
UpperCamelCase_ : Union[str, Any] = shard(__UpperCamelCase )
UpperCamelCase_ : List[Any] = pipeline(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , jit=__UpperCamelCase ).images
assert images.shape == (num_samples, 1, 512, 512, 3)
if jax.device_count() == 8:
assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04_003_906) ) < 1E-3
assert np.abs((np.abs(__UpperCamelCase , dtype=np.floataa ).sum() - 2_373_516.75) ) < 5E-1
def A_ (self ) -> Optional[int]:
UpperCamelCase_ : int = FlaxDDIMScheduler(
beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , set_alpha_to_one=__UpperCamelCase , steps_offset=1 , )
UpperCamelCase_,UpperCamelCase_ : Dict = FlaxStableDiffusionPipeline.from_pretrained(
"""CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , scheduler=__UpperCamelCase , safety_checker=__UpperCamelCase , )
UpperCamelCase_ : str = scheduler.create_state()
UpperCamelCase_ : Optional[int] = scheduler_state
UpperCamelCase_ : Union[str, Any] = (
"""A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
""" field, close up, split lighting, cinematic"""
)
UpperCamelCase_ : Union[str, Any] = jax.random.PRNGKey(0 )
UpperCamelCase_ : Optional[Any] = 50
UpperCamelCase_ : Any = jax.device_count()
UpperCamelCase_ : int = num_samples * [prompt]
UpperCamelCase_ : Optional[Any] = pipeline.prepare_inputs(__UpperCamelCase )
# shard inputs and rng
UpperCamelCase_ : str = replicate(__UpperCamelCase )
UpperCamelCase_ : Union[str, Any] = jax.random.split(__UpperCamelCase , __UpperCamelCase )
UpperCamelCase_ : Any = shard(__UpperCamelCase )
UpperCamelCase_ : int = pipeline(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , jit=__UpperCamelCase ).images
assert images.shape == (num_samples, 1, 512, 512, 3)
if jax.device_count() == 8:
assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.045_043_945) ) < 1E-3
assert np.abs((np.abs(__UpperCamelCase , dtype=np.floataa ).sum() - 2_347_693.5) ) < 5E-1
def A_ (self ) -> Tuple:
UpperCamelCase_ : Optional[Any] = (
"""A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
""" field, close up, split lighting, cinematic"""
)
UpperCamelCase_ : Any = jax.device_count()
UpperCamelCase_ : Optional[Any] = num_samples * [prompt]
UpperCamelCase_ : int = jax.random.split(jax.random.PRNGKey(0 ) , __UpperCamelCase )
UpperCamelCase_,UpperCamelCase_ : str = FlaxStableDiffusionPipeline.from_pretrained(
"""CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , safety_checker=__UpperCamelCase , )
UpperCamelCase_ : Any = replicate(__UpperCamelCase )
UpperCamelCase_ : List[Any] = pipeline.prepare_inputs(__UpperCamelCase )
UpperCamelCase_ : Optional[int] = shard(__UpperCamelCase )
UpperCamelCase_ : Optional[Any] = pipeline(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , jit=__UpperCamelCase ).images
assert images.shape == (num_samples, 1, 512, 512, 3)
UpperCamelCase_ : int = images[2, 0, 256, 10:17, 1]
# With memory efficient attention
UpperCamelCase_,UpperCamelCase_ : Union[str, Any] = FlaxStableDiffusionPipeline.from_pretrained(
"""CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , safety_checker=__UpperCamelCase , use_memory_efficient_attention=__UpperCamelCase , )
UpperCamelCase_ : Dict = replicate(__UpperCamelCase )
UpperCamelCase_ : Any = pipeline.prepare_inputs(__UpperCamelCase )
UpperCamelCase_ : Union[str, Any] = shard(__UpperCamelCase )
UpperCamelCase_ : Tuple = pipeline(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , jit=__UpperCamelCase ).images
assert images_eff.shape == (num_samples, 1, 512, 512, 3)
UpperCamelCase_ : str = images[2, 0, 256, 10:17, 1]
# I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum`
# over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now.
assert abs(slice_eff - slice ).max() < 1E-2
| 635
|
import sacrebleu as scb
from packaging import version
from sacrebleu import CHRF
import datasets
SCREAMING_SNAKE_CASE : Tuple = "\\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"
SCREAMING_SNAKE_CASE : Tuple = "\\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"
SCREAMING_SNAKE_CASE : Optional[int] = "\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 A_ (self ) -> Dict:
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 A_ (self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = CHRF.CHAR_ORDER , __UpperCamelCase = CHRF.WORD_ORDER , __UpperCamelCase = CHRF.BETA , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = False , ) -> List[Any]:
UpperCamelCase_ : List[str] = len(references[0] )
if any(len(__UpperCamelCase ) != references_per_prediction for refs in references ):
raise ValueError("""Sacrebleu requires the same number of references for each prediction""" )
UpperCamelCase_ : Optional[Any] = [[refs[i] for refs in references] for i in range(__UpperCamelCase )]
UpperCamelCase_ : List[Any] = CHRF(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
UpperCamelCase_ : int = sb_chrf.corpus_score(__UpperCamelCase , __UpperCamelCase )
return {
"score": output.score,
"char_order": output.char_order,
"word_order": output.word_order,
"beta": output.beta,
}
| 635
| 1
|
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 __magic_name__ ( __a , unittest.TestCase ):
"""simple docstring"""
lowerCAmelCase : Dict = MgpstrTokenizer
lowerCAmelCase : int = False
lowerCAmelCase : Optional[Any] = {}
lowerCAmelCase : int = False
def lowerCAmelCase ( self : Any ):
"""simple docstring"""
super().setUp()
# fmt: off
_UpperCamelCase: 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
_UpperCamelCase: Any = dict(zip(_lowercase , range(len(_lowercase ) ) ) )
_UpperCamelCase: int = 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 lowerCAmelCase ( self : int , **_lowercase : Optional[Any] ):
"""simple docstring"""
return MgpstrTokenizer.from_pretrained(self.tmpdirname , **_lowercase )
def lowerCAmelCase ( self : Dict , _lowercase : int ):
"""simple docstring"""
_UpperCamelCase: Optional[Any] = '''tester'''
_UpperCamelCase: str = '''tester'''
return input_text, output_text
@unittest.skip('''MGP-STR always lower cases letters.''' )
def lowerCAmelCase ( self : Any ):
"""simple docstring"""
pass
def lowerCAmelCase ( self : int ):
"""simple docstring"""
_UpperCamelCase: List[Any] = self.get_tokenizers(do_lower_case=_lowercase )
for tokenizer in tokenizers:
with self.subTest(f"""{tokenizer.__class__.__name__}""" ):
_UpperCamelCase: Optional[Any] = '''[SPECIAL_TOKEN]'''
tokenizer.add_special_tokens({'''cls_token''': special_token} )
_UpperCamelCase: int = tokenizer.encode([special_token] , add_special_tokens=_lowercase )
self.assertEqual(len(_lowercase ) , 1 )
_UpperCamelCase: int = tokenizer.decode(_lowercase , skip_special_tokens=_lowercase )
self.assertTrue(special_token not in decoded )
def lowerCAmelCase ( self : Dict ):
"""simple docstring"""
_UpperCamelCase: Tuple = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(f"""{tokenizer.__class__.__name__}""" ):
_UpperCamelCase , _UpperCamelCase: Any = self.get_input_output_texts(_lowercase )
_UpperCamelCase: Optional[Any] = tokenizer.tokenize(_lowercase )
_UpperCamelCase: Tuple = tokenizer.convert_tokens_to_ids(_lowercase )
_UpperCamelCase: List[str] = tokenizer.encode(_lowercase , add_special_tokens=_lowercase )
self.assertListEqual(_lowercase , _lowercase )
_UpperCamelCase: Dict = tokenizer.convert_ids_to_tokens(_lowercase )
self.assertNotEqual(len(_lowercase ) , 0 )
_UpperCamelCase: Tuple = tokenizer.decode(_lowercase )
self.assertIsInstance(_lowercase , _lowercase )
self.assertEqual(text_a.replace(''' ''' , '''''' ) , _lowercase )
@unittest.skip('''MGP-STR tokenizer only handles one sequence.''' )
def lowerCAmelCase ( self : int ):
"""simple docstring"""
pass
@unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer''' )
def lowerCAmelCase ( self : Dict ):
"""simple docstring"""
pass
| 264
|
import inspect
import unittest
from huggingface_hub import hf_hub_download
from transformers import ConvNextConfig, UperNetConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import UperNetForSemanticSegmentation
from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class __magic_name__ :
"""simple docstring"""
def __init__( self : List[str] , _lowercase : Union[str, Any] , _lowercase : int=13 , _lowercase : Optional[int]=32 , _lowercase : Optional[Any]=3 , _lowercase : Union[str, Any]=4 , _lowercase : Any=[10, 20, 30, 40] , _lowercase : str=[2, 2, 3, 2] , _lowercase : Any=True , _lowercase : Union[str, Any]=True , _lowercase : int=37 , _lowercase : Union[str, Any]="gelu" , _lowercase : Union[str, Any]=10 , _lowercase : Tuple=0.02 , _lowercase : int=["stage2", "stage3", "stage4"] , _lowercase : Optional[Any]=3 , _lowercase : Optional[int]=None , ):
"""simple docstring"""
_UpperCamelCase: Optional[int] = parent
_UpperCamelCase: str = batch_size
_UpperCamelCase: str = image_size
_UpperCamelCase: Any = num_channels
_UpperCamelCase: Union[str, Any] = num_stages
_UpperCamelCase: Any = hidden_sizes
_UpperCamelCase: int = depths
_UpperCamelCase: Dict = is_training
_UpperCamelCase: Optional[int] = use_labels
_UpperCamelCase: Optional[int] = intermediate_size
_UpperCamelCase: int = hidden_act
_UpperCamelCase: Tuple = type_sequence_label_size
_UpperCamelCase: List[Any] = initializer_range
_UpperCamelCase: Dict = out_features
_UpperCamelCase: Union[str, Any] = num_labels
_UpperCamelCase: Tuple = scope
_UpperCamelCase: Union[str, Any] = num_stages
def lowerCAmelCase ( self : Optional[Any] ):
"""simple docstring"""
_UpperCamelCase: Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
_UpperCamelCase: Any = None
if self.use_labels:
_UpperCamelCase: List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_UpperCamelCase: Union[str, Any] = self.get_config()
return config, pixel_values, labels
def lowerCAmelCase ( self : Any ):
"""simple docstring"""
return ConvNextConfig(
num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , )
def lowerCAmelCase ( self : Optional[Any] ):
"""simple docstring"""
return UperNetConfig(
backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_lowercase , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_lowercase , loss_ignore_index=255 , num_labels=self.num_labels , )
def lowerCAmelCase ( self : Tuple , _lowercase : Tuple , _lowercase : Optional[Any] , _lowercase : Dict ):
"""simple docstring"""
_UpperCamelCase: Optional[Any] = UperNetForSemanticSegmentation(config=_lowercase )
model.to(_lowercase )
model.eval()
_UpperCamelCase: int = model(_lowercase )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) )
def lowerCAmelCase ( self : Union[str, Any] ):
"""simple docstring"""
_UpperCamelCase: List[str] = self.prepare_config_and_inputs()
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) ,
): str = config_and_inputs
_UpperCamelCase: Dict = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class __magic_name__ ( __a , __a , unittest.TestCase ):
"""simple docstring"""
lowerCAmelCase : List[Any] = (UperNetForSemanticSegmentation,) if is_torch_available() else ()
lowerCAmelCase : Tuple = {'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {}
lowerCAmelCase : Dict = False
lowerCAmelCase : str = False
lowerCAmelCase : Optional[Any] = False
lowerCAmelCase : Optional[Any] = False
lowerCAmelCase : List[Any] = False
lowerCAmelCase : Union[str, Any] = False
def lowerCAmelCase ( self : Dict ):
"""simple docstring"""
_UpperCamelCase: Optional[int] = UperNetModelTester(self )
_UpperCamelCase: List[str] = ConfigTester(self , config_class=_lowercase , has_text_modality=_lowercase , hidden_size=37 )
def lowerCAmelCase ( self : str ):
"""simple docstring"""
self.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def lowerCAmelCase ( self : List[Any] ):
"""simple docstring"""
return
def lowerCAmelCase ( self : List[str] ):
"""simple docstring"""
_UpperCamelCase , _UpperCamelCase: Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase: List[Any] = model_class(_lowercase )
_UpperCamelCase: Tuple = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_UpperCamelCase: Any = [*signature.parameters.keys()]
_UpperCamelCase: List[Any] = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , _lowercase )
def lowerCAmelCase ( self : Tuple ):
"""simple docstring"""
_UpperCamelCase: Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*_lowercase )
@unittest.skip(reason='''UperNet does not use inputs_embeds''' )
def lowerCAmelCase ( self : Tuple ):
"""simple docstring"""
pass
@unittest.skip(reason='''UperNet does not support input and output embeddings''' )
def lowerCAmelCase ( self : List[str] ):
"""simple docstring"""
pass
@unittest.skip(reason='''UperNet does not have a base model''' )
def lowerCAmelCase ( self : Any ):
"""simple docstring"""
pass
@unittest.skip(reason='''UperNet does not have a base model''' )
def lowerCAmelCase ( self : Optional[Any] ):
"""simple docstring"""
pass
@require_torch_multi_gpu
@unittest.skip(reason='''UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' )
def lowerCAmelCase ( self : Dict ):
"""simple docstring"""
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def lowerCAmelCase ( self : Tuple ):
"""simple docstring"""
pass
def lowerCAmelCase ( self : Optional[Any] ):
"""simple docstring"""
def check_hidden_states_output(_lowercase : List[str] , _lowercase : List[str] , _lowercase : List[str] ):
_UpperCamelCase: Any = model_class(_lowercase )
model.to(_lowercase )
model.eval()
with torch.no_grad():
_UpperCamelCase: Union[str, Any] = model(**self._prepare_for_class(_lowercase , _lowercase ) )
_UpperCamelCase: Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
_UpperCamelCase: List[str] = self.model_tester.num_stages
self.assertEqual(len(_lowercase ) , expected_num_stages + 1 )
# ConvNext'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 // 4, self.model_tester.image_size // 4] , )
_UpperCamelCase , _UpperCamelCase: Any = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase: Optional[int] = True
check_hidden_states_output(_lowercase , _lowercase , _lowercase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
_UpperCamelCase: Union[str, Any] = True
check_hidden_states_output(_lowercase , _lowercase , _lowercase )
def lowerCAmelCase ( self : Tuple ):
"""simple docstring"""
_UpperCamelCase , _UpperCamelCase: List[str] = self.model_tester.prepare_config_and_inputs_for_common()
_UpperCamelCase: int = _config_zero_init(_lowercase )
_UpperCamelCase: List[Any] = _config_zero_init(configs_no_init.backbone_config )
for model_class in self.all_model_classes:
_UpperCamelCase: int = model_class(config=_lowercase )
for name, param in model.named_parameters():
if param.requires_grad:
self.assertIn(
((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" , )
@unittest.skip(reason='''UperNet does not have tied weights''' )
def lowerCAmelCase ( self : Tuple ):
"""simple docstring"""
pass
@slow
def lowerCAmelCase ( self : Optional[Any] ):
"""simple docstring"""
for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase: Union[str, Any] = UperNetForSemanticSegmentation.from_pretrained(_lowercase )
self.assertIsNotNone(_lowercase )
def lowerCAmelCase_ ( ) -> Dict:
'''simple docstring'''
_UpperCamelCase: Any = hf_hub_download(
repo_id='''hf-internal-testing/fixtures_ade20k''' , repo_type='''dataset''' , filename='''ADE_val_00000001.jpg''' )
_UpperCamelCase: Any = Image.open(lowercase ).convert('''RGB''' )
return image
@require_torch
@require_vision
@slow
class __magic_name__ ( unittest.TestCase ):
"""simple docstring"""
def lowerCAmelCase ( self : Optional[Any] ):
"""simple docstring"""
_UpperCamelCase: Any = AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny''' )
_UpperCamelCase: Optional[Any] = UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny''' ).to(_lowercase )
_UpperCamelCase: List[Any] = prepare_img()
_UpperCamelCase: int = processor(images=_lowercase , return_tensors='''pt''' ).to(_lowercase )
with torch.no_grad():
_UpperCamelCase: Any = model(**_lowercase )
_UpperCamelCase: Any = torch.Size((1, model.config.num_labels, 512, 512) )
self.assertEqual(outputs.logits.shape , _lowercase )
_UpperCamelCase: Tuple = torch.tensor(
[[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]] ).to(_lowercase )
self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _lowercase , atol=1E-4 ) )
def lowerCAmelCase ( self : int ):
"""simple docstring"""
_UpperCamelCase: Tuple = AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny''' )
_UpperCamelCase: int = UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny''' ).to(_lowercase )
_UpperCamelCase: int = prepare_img()
_UpperCamelCase: Union[str, Any] = processor(images=_lowercase , return_tensors='''pt''' ).to(_lowercase )
with torch.no_grad():
_UpperCamelCase: List[Any] = model(**_lowercase )
_UpperCamelCase: Tuple = torch.Size((1, model.config.num_labels, 512, 512) )
self.assertEqual(outputs.logits.shape , _lowercase )
_UpperCamelCase: Optional[Any] = torch.tensor(
[[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] ).to(_lowercase )
self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _lowercase , atol=1E-4 ) )
| 264
| 1
|
'''simple docstring'''
import json
import pathlib
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DetrImageProcessor
class a ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : int , snake_case_ : Tuple , snake_case_ : Optional[int]=7 , snake_case_ : List[Any]=3 , snake_case_ : Tuple=3_0 , snake_case_ : Optional[int]=4_0_0 , snake_case_ : int=True , snake_case_ : Optional[int]=None , snake_case_ : Optional[int]=True , snake_case_ : List[str]=1 / 2_5_5 , snake_case_ : List[str]=True , snake_case_ : Tuple=[0.5, 0.5, 0.5] , snake_case_ : str=[0.5, 0.5, 0.5] , snake_case_ : Tuple=True , ):
'''simple docstring'''
snake_case__ : Any = size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}
snake_case__ : Tuple = parent
snake_case__ : List[Any] = batch_size
snake_case__ : List[Any] = num_channels
snake_case__ : List[str] = min_resolution
snake_case__ : List[Any] = max_resolution
snake_case__ : Tuple = do_resize
snake_case__ : List[str] = size
snake_case__ : Dict = do_rescale
snake_case__ : Any = rescale_factor
snake_case__ : List[str] = do_normalize
snake_case__ : Optional[Any] = image_mean
snake_case__ : Optional[Any] = image_std
snake_case__ : str = do_pad
def __magic_name__ ( self : str ):
'''simple docstring'''
return {
"do_resize": self.do_resize,
"size": self.size,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_pad": self.do_pad,
}
def __magic_name__ ( self : int , snake_case_ : List[str] , snake_case_ : Optional[int]=False ):
'''simple docstring'''
if not batched:
snake_case__ : List[Any] = image_inputs[0]
if isinstance(snake_case_ , Image.Image ):
snake_case__ : Any = image.size
else:
snake_case__ : Dict = image.shape[1], image.shape[2]
if w < h:
snake_case__ : str = int(self.size['''shortest_edge'''] * h / w )
snake_case__ : Optional[int] = self.size['shortest_edge']
elif w > h:
snake_case__ : Optional[Any] = self.size['shortest_edge']
snake_case__ : Tuple = int(self.size['''shortest_edge'''] * w / h )
else:
snake_case__ : Optional[int] = self.size['shortest_edge']
snake_case__ : Optional[int] = self.size['shortest_edge']
else:
snake_case__ : int = []
for image in image_inputs:
snake_case__ : int = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
snake_case__ : Dict = max(snake_case_ , key=lambda snake_case_ : item[0] )[0]
snake_case__ : Optional[int] = max(snake_case_ , key=lambda snake_case_ : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class a ( a__ , unittest.TestCase ):
"""simple docstring"""
__UpperCAmelCase = DetrImageProcessor if is_vision_available() else None
def __magic_name__ ( self : List[Any] ):
'''simple docstring'''
snake_case__ : Union[str, Any] = DetrImageProcessingTester(self )
@property
def __magic_name__ ( self : List[str] ):
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def __magic_name__ ( self : Optional[int] ):
'''simple docstring'''
snake_case__ : Any = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(snake_case_ , '''image_mean''' ) )
self.assertTrue(hasattr(snake_case_ , '''image_std''' ) )
self.assertTrue(hasattr(snake_case_ , '''do_normalize''' ) )
self.assertTrue(hasattr(snake_case_ , '''do_rescale''' ) )
self.assertTrue(hasattr(snake_case_ , '''rescale_factor''' ) )
self.assertTrue(hasattr(snake_case_ , '''do_resize''' ) )
self.assertTrue(hasattr(snake_case_ , '''size''' ) )
self.assertTrue(hasattr(snake_case_ , '''do_pad''' ) )
def __magic_name__ ( self : str ):
'''simple docstring'''
snake_case__ : int = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} )
self.assertEqual(image_processor.do_pad , snake_case_ )
snake_case__ : Any = self.image_processing_class.from_dict(
self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=snake_case_ )
self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} )
self.assertEqual(image_processor.do_pad , snake_case_ )
def __magic_name__ ( self : str ):
'''simple docstring'''
pass
def __magic_name__ ( self : Dict ):
'''simple docstring'''
snake_case__ : List[Any] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
snake_case__ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ )
for image in image_inputs:
self.assertIsInstance(snake_case_ , Image.Image )
# Test not batched input
snake_case__ : List[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
snake_case__ : List[str] = self.image_processor_tester.get_expected_values(snake_case_ )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
snake_case__ : Optional[int] = self.image_processor_tester.get_expected_values(snake_case_ , batched=snake_case_ )
snake_case__ : Tuple = image_processing(snake_case_ , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def __magic_name__ ( self : Optional[int] ):
'''simple docstring'''
snake_case__ : str = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
snake_case__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ , numpify=snake_case_ )
for image in image_inputs:
self.assertIsInstance(snake_case_ , np.ndarray )
# Test not batched input
snake_case__ : Any = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
snake_case__ : int = self.image_processor_tester.get_expected_values(snake_case_ )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
snake_case__ : str = image_processing(snake_case_ , return_tensors='''pt''' ).pixel_values
snake_case__ : Optional[int] = self.image_processor_tester.get_expected_values(snake_case_ , batched=snake_case_ )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def __magic_name__ ( self : List[str] ):
'''simple docstring'''
snake_case__ : List[Any] = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
snake_case__ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ , torchify=snake_case_ )
for image in image_inputs:
self.assertIsInstance(snake_case_ , torch.Tensor )
# Test not batched input
snake_case__ : List[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
snake_case__ : List[Any] = self.image_processor_tester.get_expected_values(snake_case_ )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
snake_case__ : str = image_processing(snake_case_ , return_tensors='''pt''' ).pixel_values
snake_case__ : Dict = self.image_processor_tester.get_expected_values(snake_case_ , batched=snake_case_ )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
@slow
def __magic_name__ ( self : Dict ):
'''simple docstring'''
snake_case__ : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f:
snake_case__ : Any = json.loads(f.read() )
snake_case__ : Optional[int] = {'image_id': 3_9_7_6_9, 'annotations': target}
# encode them
snake_case__ : Optional[Any] = DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50''' )
snake_case__ : List[str] = image_processing(images=snake_case_ , annotations=snake_case_ , return_tensors='''pt''' )
# verify pixel values
snake_case__ : Optional[Any] = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['''pixel_values'''].shape , snake_case_ )
snake_case__ : Tuple = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , snake_case_ , atol=1e-4 ) )
# verify area
snake_case__ : List[Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , snake_case_ ) )
# verify boxes
snake_case__ : Tuple = torch.Size([6, 4] )
self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , snake_case_ )
snake_case__ : List[Any] = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , snake_case_ , atol=1e-3 ) )
# verify image_id
snake_case__ : Union[str, Any] = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , snake_case_ ) )
# verify is_crowd
snake_case__ : Dict = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , snake_case_ ) )
# verify class_labels
snake_case__ : Any = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , snake_case_ ) )
# verify orig_size
snake_case__ : Dict = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , snake_case_ ) )
# verify size
snake_case__ : Optional[Any] = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , snake_case_ ) )
@slow
def __magic_name__ ( self : List[Any] ):
'''simple docstring'''
snake_case__ : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f:
snake_case__ : Any = json.loads(f.read() )
snake_case__ : Dict = {'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target}
snake_case__ : Any = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' )
# encode them
snake_case__ : int = DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50-panoptic''' )
snake_case__ : Optional[int] = image_processing(images=snake_case_ , annotations=snake_case_ , masks_path=snake_case_ , return_tensors='''pt''' )
# verify pixel values
snake_case__ : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['''pixel_values'''].shape , snake_case_ )
snake_case__ : Optional[int] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , snake_case_ , atol=1e-4 ) )
# verify area
snake_case__ : Dict = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , snake_case_ ) )
# verify boxes
snake_case__ : Optional[Any] = torch.Size([6, 4] )
self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , snake_case_ )
snake_case__ : Any = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , snake_case_ , atol=1e-3 ) )
# verify image_id
snake_case__ : Tuple = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , snake_case_ ) )
# verify is_crowd
snake_case__ : str = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , snake_case_ ) )
# verify class_labels
snake_case__ : Optional[int] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , snake_case_ ) )
# verify masks
snake_case__ : str = 8_2_2_8_7_3
self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , snake_case_ )
# verify orig_size
snake_case__ : int = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , snake_case_ ) )
# verify size
snake_case__ : List[str] = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , snake_case_ ) )
| 347
|
'''simple docstring'''
def UpperCAmelCase ( UpperCAmelCase__ : int = 50):
lowerCamelCase : List[Any] = [1] * (length + 1)
for row_length in range(length + 1):
for tile_length in range(2 , 5):
for tile_start in range(row_length - tile_length + 1):
ways_number[row_length] += ways_number[
row_length - tile_start - tile_length
]
return ways_number[length]
if __name__ == "__main__":
print(f"""{solution() = }""")
| 320
| 0
|
import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union
import torch
from filelock import FileLock
from torch.utils.data import Dataset
from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features
UpperCamelCase__ : List[str] = logging.get_logger(__name__)
UpperCamelCase__ : Union[str, Any] = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCamelCase__ : List[Any] = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class _UpperCamelCase :
'''simple docstring'''
lowerCamelCase : str = field(
default=A_ , metadata={'help': 'Model type selected in the list: ' + ', '.join(A_ )} )
lowerCamelCase : str = field(
default=A_ , metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'} )
lowerCamelCase : int = field(
default=128 , metadata={
'help': (
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
lowerCamelCase : int = field(
default=128 , metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'} , )
lowerCamelCase : int = field(
default=64 , metadata={
'help': (
'The maximum number of tokens for the question. Questions longer than this will '
'be truncated to this length.'
)
} , )
lowerCamelCase : int = field(
default=30 , metadata={
'help': (
'The maximum length of an answer that can be generated. This is needed because the start '
'and end predictions are not conditioned on one another.'
)
} , )
lowerCamelCase : bool = field(
default=A_ , metadata={'help': 'Overwrite the cached training and evaluation sets'} )
lowerCamelCase : bool = field(
default=A_ , metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'} )
lowerCamelCase : float = field(
default=0.0 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
lowerCamelCase : int = field(
default=20 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
lowerCamelCase : int = field(
default=0 , metadata={
'help': (
'language id of input for language-specific xlm models (see'
' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
)
} , )
lowerCamelCase : int = field(default=1 , metadata={'help': 'multiple threads for converting example to features'} )
class _UpperCamelCase ( A_ ):
'''simple docstring'''
lowerCamelCase : List[str] = 'train'
lowerCamelCase : Optional[int] = 'dev'
class _UpperCamelCase ( A_ ):
'''simple docstring'''
lowerCamelCase : SquadDataTrainingArguments
lowerCamelCase : List[SquadFeatures]
lowerCamelCase : Split
lowerCamelCase : bool
def __init__( self : str , __lowercase : SquadDataTrainingArguments , __lowercase : PreTrainedTokenizer , __lowercase : Optional[int] = None , __lowercase : Union[str, Split] = Split.train , __lowercase : Optional[bool] = False , __lowercase : Optional[str] = None , __lowercase : Optional[str] = "pt" , ):
'''simple docstring'''
UpperCAmelCase_ = args
UpperCAmelCase_ = is_language_sensitive
UpperCAmelCase_ = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
if isinstance(__lowercase , __lowercase ):
try:
UpperCAmelCase_ = Split[mode]
except KeyError:
raise KeyError("""mode is not a valid split name""" )
UpperCAmelCase_ = mode
# Load data features from cache or dataset file
UpperCAmelCase_ = """v2""" if args.version_2_with_negative else """v1"""
UpperCAmelCase_ = os.path.join(
cache_dir if cache_dir is not None else args.data_dir , F"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}""" , )
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
UpperCAmelCase_ = cached_features_file + """.lock"""
with FileLock(__lowercase ):
if os.path.exists(__lowercase ) and not args.overwrite_cache:
UpperCAmelCase_ = time.time()
UpperCAmelCase_ = torch.load(__lowercase )
# Legacy cache files have only features, while new cache files
# will have dataset and examples also.
UpperCAmelCase_ = self.old_features["""features"""]
UpperCAmelCase_ = self.old_features.get("""dataset""" , __lowercase )
UpperCAmelCase_ = self.old_features.get("""examples""" , __lowercase )
logger.info(
F"""Loading features from cached file {cached_features_file} [took %.3f s]""" , time.time() - start )
if self.dataset is None or self.examples is None:
logger.warning(
F"""Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"""
""" future run""" )
else:
if mode == Split.dev:
UpperCAmelCase_ = self.processor.get_dev_examples(args.data_dir )
else:
UpperCAmelCase_ = self.processor.get_train_examples(args.data_dir )
UpperCAmelCase_ , UpperCAmelCase_ = squad_convert_examples_to_features(
examples=self.examples , tokenizer=__lowercase , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=__lowercase , )
UpperCAmelCase_ = time.time()
torch.save(
{"""features""": self.features, """dataset""": self.dataset, """examples""": self.examples} , __lowercase , )
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
logger.info(
F"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""" )
def __len__( self : int ):
'''simple docstring'''
return len(self.features )
def __getitem__( self : List[Any] , __lowercase : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase_ = self.features[i]
UpperCAmelCase_ = torch.tensor(feature.input_ids , dtype=torch.long )
UpperCAmelCase_ = torch.tensor(feature.attention_mask , dtype=torch.long )
UpperCAmelCase_ = torch.tensor(feature.token_type_ids , dtype=torch.long )
UpperCAmelCase_ = torch.tensor(feature.cls_index , dtype=torch.long )
UpperCAmelCase_ = torch.tensor(feature.p_mask , dtype=torch.float )
UpperCAmelCase_ = torch.tensor(feature.is_impossible , dtype=torch.float )
UpperCAmelCase_ = {
"""input_ids""": input_ids,
"""attention_mask""": attention_mask,
"""token_type_ids""": token_type_ids,
}
if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
del inputs["token_type_ids"]
if self.args.model_type in ["xlnet", "xlm"]:
inputs.update({"""cls_index""": cls_index, """p_mask""": p_mask} )
if self.args.version_2_with_negative:
inputs.update({"""is_impossible""": is_impossible} )
if self.is_language_sensitive:
inputs.update({"""langs""": (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} )
if self.mode == Split.train:
UpperCAmelCase_ = torch.tensor(feature.start_position , dtype=torch.long )
UpperCAmelCase_ = torch.tensor(feature.end_position , dtype=torch.long )
inputs.update({"""start_positions""": start_positions, """end_positions""": end_positions} )
return inputs
| 710
|
import argparse
import gc
import json
import os
import re
import torch
from huggingface_hub import hf_hub_download
from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig
from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint
UpperCamelCase__ : int = {
"""169M""": 12,
"""430M""": 24,
"""1B5""": 24,
"""3B""": 32,
"""7B""": 32,
"""14B""": 40,
}
UpperCamelCase__ : Union[str, Any] = {
"""169M""": 7_68,
"""430M""": 10_24,
"""1B5""": 20_48,
"""3B""": 25_60,
"""7B""": 40_96,
"""14B""": 51_20,
}
def A_( A ):
UpperCAmelCase_ = list(state_dict.keys() )
for name in state_dict_keys:
UpperCAmelCase_ = state_dict.pop(A )
# emb -> embedding
if name.startswith("""emb.""" ):
UpperCAmelCase_ = name.replace("""emb.""" , """embeddings.""" )
# ln_0 -> pre_ln (only present at block 0)
if name.startswith("""blocks.0.ln0""" ):
UpperCAmelCase_ = name.replace("""blocks.0.ln0""" , """blocks.0.pre_ln""" )
# att -> attention
UpperCAmelCase_ = re.sub(R"""blocks\.(\d+)\.att""" , R"""blocks.\1.attention""" , A )
# ffn -> feed_forward
UpperCAmelCase_ = re.sub(R"""blocks\.(\d+)\.ffn""" , R"""blocks.\1.feed_forward""" , A )
# time_mix_k -> time_mix_key and reshape
if name.endswith(""".time_mix_k""" ):
UpperCAmelCase_ = name.replace(""".time_mix_k""" , """.time_mix_key""" )
# time_mix_v -> time_mix_value and reshape
if name.endswith(""".time_mix_v""" ):
UpperCAmelCase_ = name.replace(""".time_mix_v""" , """.time_mix_value""" )
# time_mix_r -> time_mix_key and reshape
if name.endswith(""".time_mix_r""" ):
UpperCAmelCase_ = name.replace(""".time_mix_r""" , """.time_mix_receptance""" )
if name != "head.weight":
UpperCAmelCase_ = """rwkv.""" + name
UpperCAmelCase_ = weight
return state_dict
def A_( A , A , A , A=None , A=None , A=False , A=None ):
# 1. If possible, build the tokenizer.
if tokenizer_file is None:
print("""No `--tokenizer_file` provided, we will use the default tokenizer.""" )
UpperCAmelCase_ = 50277
UpperCAmelCase_ = AutoTokenizer.from_pretrained("""EleutherAI/gpt-neox-20b""" )
else:
UpperCAmelCase_ = PreTrainedTokenizerFast(tokenizer_file=A )
UpperCAmelCase_ = len(A )
tokenizer.save_pretrained(A )
# 2. Build the config
UpperCAmelCase_ = list(NUM_HIDDEN_LAYERS_MAPPING.keys() )
if size is None:
# Try to infer size from the checkpoint name
for candidate in possible_sizes:
if candidate in checkpoint_file:
UpperCAmelCase_ = candidate
break
if size is None:
raise ValueError("""Could not infer the size, please provide it with the `--size` argument.""" )
if size not in possible_sizes:
raise ValueError(f"""`size` should be one of {possible_sizes}, got {size}.""" )
UpperCAmelCase_ = RwkvConfig(
vocab_size=A , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , )
config.save_pretrained(A )
# 3. Download model file then convert state_dict
UpperCAmelCase_ = hf_hub_download(A , A )
UpperCAmelCase_ = torch.load(A , map_location="""cpu""" )
UpperCAmelCase_ = convert_state_dict(A )
# 4. Split in shards and save
UpperCAmelCase_ , UpperCAmelCase_ = shard_checkpoint(A )
for shard_file, shard in shards.items():
torch.save(A , os.path.join(A , A ) )
if index is not None:
UpperCAmelCase_ = os.path.join(A , A )
# Save the index as well
with open(A , """w""" , encoding="""utf-8""" ) as f:
UpperCAmelCase_ = json.dumps(A , indent=2 , sort_keys=A ) + """\n"""
f.write(A )
# 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict
print(
"""Cleaning up shards. This may error with an OOM error, it this is the case don't worry you still have converted the model.""" )
UpperCAmelCase_ = list(shards.keys() )
del state_dict
del shards
gc.collect()
for shard_file in shard_files:
UpperCAmelCase_ = torch.load(os.path.join(A , A ) )
torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(A , A ) )
del state_dict
gc.collect()
if push_to_hub:
if model_name is None:
raise ValueError("""Please provide a `model_name` to push the model to the Hub.""" )
UpperCAmelCase_ = AutoModelForCausalLM.from_pretrained(A )
model.push_to_hub(A , max_shard_size="""2GB""" )
tokenizer.push_to_hub(A )
if __name__ == "__main__":
UpperCamelCase__ : Optional[int] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--repo_id""", default=None, type=str, required=True, help="""Repo ID from which to pull the checkpoint."""
)
parser.add_argument(
"""--checkpoint_file""", default=None, type=str, required=True, help="""Name of the checkpoint file in the repo."""
)
parser.add_argument(
"""--output_dir""", default=None, type=str, required=True, help="""Where to save the converted model."""
)
parser.add_argument(
"""--tokenizer_file""",
default=None,
type=str,
help="""Path to the tokenizer file to use (if not provided, only the model is converted).""",
)
parser.add_argument(
"""--size""",
default=None,
type=str,
help="""Size of the model. Will be inferred from the `checkpoint_file` if not passed.""",
)
parser.add_argument(
"""--push_to_hub""",
action="""store_true""",
help="""Push to the Hub the converted model.""",
)
parser.add_argument(
"""--model_name""",
default=None,
type=str,
help="""Name of the pushed model on the Hub, including the username / organization.""",
)
UpperCamelCase__ : List[str] = parser.parse_args()
convert_rmkv_checkpoint_to_hf_format(
args.repo_id,
args.checkpoint_file,
args.output_dir,
size=args.size,
tokenizer_file=args.tokenizer_file,
push_to_hub=args.push_to_hub,
model_name=args.model_name,
)
| 486
| 0
|
'''simple docstring'''
from typing import List
import datasets
from datasets.tasks import AudioClassification
from ..folder_based_builder import folder_based_builder
A : Union[str, Any] = datasets.utils.logging.get_logger(__name__)
class lowerCAmelCase_ ( folder_based_builder.FolderBasedBuilderConfig ):
__UpperCAmelCase = None
__UpperCAmelCase = None
class lowerCAmelCase_ ( folder_based_builder.FolderBasedBuilder ):
__UpperCAmelCase = datasets.Audio()
__UpperCAmelCase = 'audio'
__UpperCAmelCase = AudioFolderConfig
__UpperCAmelCase = 42 # definition at the bottom of the script
__UpperCAmelCase = AudioClassification(audio_column='audio' , label_column='label' )
A : Optional[int] = [
""".aiff""",
""".au""",
""".avr""",
""".caf""",
""".flac""",
""".htk""",
""".svx""",
""".mat4""",
""".mat5""",
""".mpc2k""",
""".ogg""",
""".paf""",
""".pvf""",
""".raw""",
""".rf64""",
""".sd2""",
""".sds""",
""".ircam""",
""".voc""",
""".w64""",
""".wav""",
""".nist""",
""".wavex""",
""".wve""",
""".xi""",
""".mp3""",
""".opus""",
]
A : Optional[int] = AUDIO_EXTENSIONS
| 349
|
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tokenizers_available,
is_torch_available,
)
A : List[Any] = {}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A : Tuple = ["""NllbTokenizer"""]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A : Union[str, Any] = ["""NllbTokenizerFast"""]
if TYPE_CHECKING:
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_nllb import NllbTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_nllb_fast import NllbTokenizerFast
else:
import sys
A : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 349
| 1
|
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list:
return [
txt[:a] + txt[a].upper() + txt[a + 1 :]
for a in range(len(_UpperCAmelCase ) )
if txt[a].isalpha()
]
if __name__ == "__main__":
__import__('''doctest''').testmod()
| 506
|
'''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,
)
A__: int = {'''configuration_xglm''': ['''XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XGLMConfig''']}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A__: Tuple = ['''XGLMTokenizer''']
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A__: List[Any] = ['''XGLMTokenizerFast''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A__: Tuple = [
'''XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''XGLMForCausalLM''',
'''XGLMModel''',
'''XGLMPreTrainedModel''',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A__: Dict = [
'''FlaxXGLMForCausalLM''',
'''FlaxXGLMModel''',
'''FlaxXGLMPreTrainedModel''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A__: List[Any] = [
'''TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFXGLMForCausalLM''',
'''TFXGLMModel''',
'''TFXGLMPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_xglm import XGLMTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_xglm_fast import XGLMTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_xglm import (
TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
TFXGLMForCausalLM,
TFXGLMModel,
TFXGLMPreTrainedModel,
)
else:
import sys
A__: List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
| 506
| 1
|
'''simple docstring'''
import warnings
from ...utils import logging
from .image_processing_chinese_clip import ChineseCLIPImageProcessor
lowerCAmelCase_ : Union[str, Any] = logging.get_logger(__name__)
class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ):
"""simple docstring"""
def __init__( self : Optional[Any] , *__a : Dict , **__a : List[Any] ):
warnings.warn(
"The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
" Please use ChineseCLIPImageProcessor instead." , __a , )
super().__init__(*__a , **__a )
| 692
|
'''simple docstring'''
import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401
from coval.conll import reader, util
from coval.eval import evaluator
import datasets
lowerCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__)
lowerCAmelCase_ : Tuple = '\\n@InProceedings{moosavi2019minimum,\n author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n year = {2019},\n booktitle = {Proceedings of the 57th Annual Meeting of\n the Association for Computational Linguistics (Volume 1: Long Papers)},\n publisher = {Association for Computational Linguistics},\n address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n author = {Amit Bagga and Breck Baldwin},\n title = {Algorithms for Scoring Coreference Chains},\n booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n year = {1998},\n pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n author = {Xiaoqiang Luo},\n title = {On coreference resolution performance metrics},\n booktitle = {In Proc. of HLT/EMNLP},\n year = {2005},\n pages = {25--32},\n publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n title = "Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric",\n author = "Moosavi, Nafise Sadat and\n Strube, Michael",\n booktitle = "Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",\n month = aug,\n year = "2016",\n address = "Berlin, Germany",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/P16-1060",\n doi = "10.18653/v1/P16-1060",\n pages = "632--642",\n}\n\n'
lowerCAmelCase_ : Union[str, Any] = '\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn Type Description\n1 Document ID This is a variation on the document filename\n2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3 Word number\n4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5 Part-of-Speech\n6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the "([pos] [word])" string (or leaf) and concatenating the items in the rows of that column.\n7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a "-"\n8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7.\n9 Word sense This is the word sense of the word in Column 3.\n10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11 Named Entities These columns identifies the spans representing various named entities.\n12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN Coreference Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section "*_conll File Format"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n'
lowerCAmelCase_ : Union[str, Any] = '\nCalculates coreference evaluation metrics.\nArgs:\n predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n Each prediction is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n Each reference is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n keep_singletons: After extracting all mentions of key or system files,\n mentions whose corresponding coreference chain is of size one,\n are considered as singletons. The default evaluation mode will include\n singletons in evaluations if they are included in the key or the system files.\n By setting \'keep_singletons=False\', all singletons in the key and system files\n will be excluded from the evaluation.\n NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n leave out the resolution of VPs. By setting the \'NP_only\' option, the scorer will only evaluate the resolution of NPs.\n min_span: By setting \'min_span\', the scorer reports the results based on automatically detected minimum spans.\n Minimum spans are determined using the MINA algorithm.\n\nReturns:\n \'mentions\': mentions\n \'muc\': MUC metric [Vilain et al, 1995]\n \'bcub\': B-cubed [Bagga and Baldwin, 1998]\n \'ceafe\': CEAFe [Luo et al., 2005]\n \'lea\': LEA [Moosavi and Strube, 2016]\n \'conll_score\': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n >>> coval = datasets.load_metric(\'coval\')\n >>> words = [\'bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -\',\n ... \'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)\',\n ... \'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)\',\n ... \'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -\',\n ... \'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -\',\n ... \'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -\']\n >>> references = [words]\n >>> predictions = [words]\n >>> results = coval.compute(predictions=predictions, references=references)\n >>> print(results) # doctest:+ELLIPSIS\n {\'mentions/recall\': 1.0,[...] \'conll_score\': 100.0}\n'
def _lowerCamelCase ( lowercase : Tuple , lowercase : List[Any] , lowercase : Optional[int]=False , lowercase : Dict=False , lowercase : Optional[int]=True , lowercase : Union[str, Any]=False , lowercase : int="dummy_doc" ) -> Union[str, Any]:
_a = {doc: key_lines}
_a = {doc: sys_lines}
_a = {}
_a = 0
_a = 0
_a = 0
_a = 0
_a = 0
_a = 0
_a , _a = reader.get_doc_mentions(lowercase , key_doc_lines[doc] , lowercase )
key_singletons_num += singletons_num
if NP_only or min_span:
_a = reader.set_annotated_parse_trees(lowercase , key_doc_lines[doc] , lowercase , lowercase )
_a , _a = reader.get_doc_mentions(lowercase , sys_doc_lines[doc] , lowercase )
sys_singletons_num += singletons_num
if NP_only or min_span:
_a = reader.set_annotated_parse_trees(lowercase , key_doc_lines[doc] , lowercase , lowercase )
if remove_nested:
_a , _a = reader.remove_nested_coref_mentions(lowercase , lowercase )
key_nested_coref_num += nested_mentions
key_removed_nested_clusters += removed_clusters
_a , _a = reader.remove_nested_coref_mentions(lowercase , lowercase )
sys_nested_coref_num += nested_mentions
sys_removed_nested_clusters += removed_clusters
_a = reader.get_mention_assignments(lowercase , lowercase )
_a = reader.get_mention_assignments(lowercase , lowercase )
_a = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster)
if remove_nested:
logger.info(
"Number of removed nested coreferring mentions in the key "
F'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' )
logger.info(
"Number of resulting singleton clusters in the key "
F'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' )
if not keep_singletons:
logger.info(
F'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system '
"files, respectively" )
return doc_coref_infos
def _lowerCamelCase ( lowercase : List[Any] , lowercase : Any , lowercase : Optional[Any] , lowercase : Union[str, Any] , lowercase : Any , lowercase : List[str] , lowercase : Dict ) -> str:
_a = get_coref_infos(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase )
_a = {}
_a = 0
_a = 0
for name, metric in metrics:
_a , _a , _a = evaluator.evaluate_documents(lowercase , lowercase , beta=1 )
if name in ["muc", "bcub", "ceafe"]:
conll += fa
conll_subparts_num += 1
output_scores.update({F'{name}/recall': recall, F'{name}/precision': precision, F'{name}/f1': fa} )
logger.info(
name.ljust(10 ) , F'Recall: {recall * 100:.2f}' , F' Precision: {precision * 100:.2f}' , F' F1: {fa * 100:.2f}' , )
if conll_subparts_num == 3:
_a = (conll / 3) * 100
logger.info(F'CoNLL score: {conll:.2f}' )
output_scores.update({"conll_score": conll} )
return output_scores
def _lowerCamelCase ( lowercase : Any ) -> str:
_a = False
for line in key_lines:
if not line.startswith("#" ):
if len(line.split() ) > 6:
_a = line.split()[5]
if not parse_col == "-":
_a = True
break
else:
break
return has_gold_parse
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class __SCREAMING_SNAKE_CASE (datasets.Metric ):
"""simple docstring"""
def UpperCamelCase__ ( self : str ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"predictions": datasets.Sequence(datasets.Value("string" ) ),
"references": datasets.Sequence(datasets.Value("string" ) ),
} ) , codebase_urls=["https://github.com/ns-moosavi/coval"] , reference_urls=[
"https://github.com/ns-moosavi/coval",
"https://www.aclweb.org/anthology/P16-1060",
"http://www.conll.cemantix.org/2012/data.html",
] , )
def UpperCamelCase__ ( self : int , __a : Any , __a : int , __a : Optional[Any]=True , __a : Optional[Any]=False , __a : str=False , __a : List[str]=False ):
_a = [
("mentions", evaluator.mentions),
("muc", evaluator.muc),
("bcub", evaluator.b_cubed),
("ceafe", evaluator.ceafe),
("lea", evaluator.lea),
]
if min_span:
_a = util.check_gold_parse_annotation(__a )
if not has_gold_parse:
raise NotImplementedError("References should have gold parse annotation to use 'min_span'." )
# util.parse_key_file(key_file)
# key_file = key_file + ".parsed"
_a = evaluate(
key_lines=__a , sys_lines=__a , metrics=__a , NP_only=__a , remove_nested=__a , keep_singletons=__a , min_span=__a , )
return score
| 692
| 1
|
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
UpperCAmelCase__ = {
"""configuration_roc_bert""": ["""ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """RoCBertConfig"""],
"""tokenization_roc_bert""": ["""RoCBertTokenizer"""],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
pass
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase__ = [
"""ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""RoCBertForCausalLM""",
"""RoCBertForMaskedLM""",
"""RoCBertForMultipleChoice""",
"""RoCBertForPreTraining""",
"""RoCBertForQuestionAnswering""",
"""RoCBertForSequenceClassification""",
"""RoCBertForTokenClassification""",
"""RoCBertLayer""",
"""RoCBertModel""",
"""RoCBertPreTrainedModel""",
"""load_tf_weights_in_roc_bert""",
]
if TYPE_CHECKING:
from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig
from .tokenization_roc_bert import RoCBertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
raise OptionalDependencyNotAvailable()
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_roc_bert import (
ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
RoCBertForCausalLM,
RoCBertForMaskedLM,
RoCBertForMultipleChoice,
RoCBertForPreTraining,
RoCBertForQuestionAnswering,
RoCBertForSequenceClassification,
RoCBertForTokenClassification,
RoCBertLayer,
RoCBertModel,
RoCBertPreTrainedModel,
load_tf_weights_in_roc_bert,
)
else:
import sys
UpperCAmelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 275
|
"""simple docstring"""
from __future__ import annotations
from random import choice
def __UpperCAmelCase ( lowercase ):
"""simple docstring"""
return choice(lowercase )
def __UpperCAmelCase ( lowercase ,lowercase ):
"""simple docstring"""
_UpperCAmelCase = random_pivot(lowercase )
# partition based on pivot
# linear time
_UpperCAmelCase = [e for e in lst if e < pivot]
_UpperCAmelCase = [e for e in lst if e > pivot]
# if we get lucky, pivot might be the element we want.
# we can easily see this:
# small (elements smaller than k)
# + pivot (kth element)
# + big (elements larger than k)
if len(lowercase ) == k - 1:
return pivot
# pivot is in elements bigger than k
elif len(lowercase ) < k - 1:
return kth_number(lowercase ,k - len(lowercase ) - 1 )
# pivot is in elements smaller than k
else:
return kth_number(lowercase ,lowercase )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 275
| 1
|
'''simple docstring'''
from typing import Optional, Union
import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig
_a : List[Any] = logging.get_logger(__name__)
# General docstring
_a : Union[str, Any] = "MobileNetV1Config"
# Base docstring
_a : int = "google/mobilenet_v1_1.0_224"
_a : Any = [1, 1_024, 7, 7]
# Image classification docstring
_a : Any = "google/mobilenet_v1_1.0_224"
_a : Tuple = "tabby, tabby cat"
_a : Tuple = [
"google/mobilenet_v1_1.0_224",
"google/mobilenet_v1_0.75_192",
# See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]
def _a (lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Tuple=None ) -> Optional[int]:
"""simple docstring"""
__snake_case = {}
if isinstance(lowercase__ , lowercase__ ):
__snake_case = model.mobilenet_va
else:
__snake_case = model
__snake_case = 'MobilenetV1/Conv2d_0/'
__snake_case = backbone.conv_stem.convolution.weight
__snake_case = backbone.conv_stem.normalization.bias
__snake_case = backbone.conv_stem.normalization.weight
__snake_case = backbone.conv_stem.normalization.running_mean
__snake_case = backbone.conv_stem.normalization.running_var
for i in range(1_3 ):
__snake_case = i + 1
__snake_case = i * 2
__snake_case = backbone.layer[pt_index]
__snake_case = f'MobilenetV1/Conv2d_{tf_index}_depthwise/'
__snake_case = pointer.convolution.weight
__snake_case = pointer.normalization.bias
__snake_case = pointer.normalization.weight
__snake_case = pointer.normalization.running_mean
__snake_case = pointer.normalization.running_var
__snake_case = backbone.layer[pt_index + 1]
__snake_case = f'MobilenetV1/Conv2d_{tf_index}_pointwise/'
__snake_case = pointer.convolution.weight
__snake_case = pointer.normalization.bias
__snake_case = pointer.normalization.weight
__snake_case = pointer.normalization.running_mean
__snake_case = pointer.normalization.running_var
if isinstance(lowercase__ , lowercase__ ):
__snake_case = 'MobilenetV1/Logits/Conv2d_1c_1x1/'
__snake_case = model.classifier.weight
__snake_case = model.classifier.bias
return tf_to_pt_map
def _a (lowercase__ : List[str] , lowercase__ : Optional[Any] , lowercase__ : Tuple ) -> str:
"""simple docstring"""
try:
import numpy as np
import tensorflow as tf
except ImportError:
logger.error(
'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see '
'https://www.tensorflow.org/install/ for installation instructions.' )
raise
# Load weights from TF model
__snake_case = tf.train.list_variables(lowercase__ )
__snake_case = {}
for name, shape in init_vars:
logger.info(f'Loading TF weight {name} with shape {shape}' )
__snake_case = tf.train.load_variable(lowercase__ , lowercase__ )
__snake_case = array
# Build TF to PyTorch weights loading map
__snake_case = _build_tf_to_pytorch_map(lowercase__ , lowercase__ , lowercase__ )
for name, pointer in tf_to_pt_map.items():
logger.info(f'Importing {name}' )
if name not in tf_weights:
logger.info(f'{name} not in tf pre-trained weights, skipping' )
continue
__snake_case = tf_weights[name]
if "depthwise_weights" in name:
logger.info('Transposing depthwise' )
__snake_case = np.transpose(lowercase__ , (2, 3, 0, 1) )
elif "weights" in name:
logger.info('Transposing' )
if len(pointer.shape ) == 2: # copying into linear layer
__snake_case = array.squeeze().transpose()
else:
__snake_case = np.transpose(lowercase__ , (3, 2, 0, 1) )
if pointer.shape != array.shape:
raise ValueError(f'Pointer shape {pointer.shape} and array shape {array.shape} mismatched' )
logger.info(f'Initialize PyTorch weight {name} {array.shape}' )
__snake_case = torch.from_numpy(lowercase__ )
tf_weights.pop(lowercase__ , lowercase__ )
tf_weights.pop(name + '/RMSProp' , lowercase__ )
tf_weights.pop(name + '/RMSProp_1' , lowercase__ )
tf_weights.pop(name + '/ExponentialMovingAverage' , lowercase__ )
logger.info(f'Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}' )
return model
def _a (lowercase__ : torch.Tensor , lowercase__ : nn.Convad ) -> torch.Tensor:
"""simple docstring"""
__snake_case , __snake_case = features.shape[-2:]
__snake_case , __snake_case = conv_layer.stride
__snake_case , __snake_case = conv_layer.kernel_size
if in_height % stride_height == 0:
__snake_case = max(kernel_height - stride_height , 0 )
else:
__snake_case = max(kernel_height - (in_height % stride_height) , 0 )
if in_width % stride_width == 0:
__snake_case = max(kernel_width - stride_width , 0 )
else:
__snake_case = max(kernel_width - (in_width % stride_width) , 0 )
__snake_case = pad_along_width // 2
__snake_case = pad_along_width - pad_left
__snake_case = pad_along_height // 2
__snake_case = pad_along_height - pad_top
__snake_case = (pad_left, pad_right, pad_top, pad_bottom)
return nn.functional.pad(lowercase__ , lowercase__ , 'constant' , 0.0 )
class _lowercase ( nn.Module ):
def __init__( self : Tuple , SCREAMING_SNAKE_CASE_ : MobileNetVaConfig , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] = 1 , SCREAMING_SNAKE_CASE_ : Optional[int] = 1 , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : Optional[bool or str] = True , ) -> None:
super().__init__()
__snake_case = config
if in_channels % groups != 0:
raise ValueError(f'Input channels ({in_channels}) are not divisible by {groups} groups.' )
if out_channels % groups != 0:
raise ValueError(f'Output channels ({out_channels}) are not divisible by {groups} groups.' )
__snake_case = 0 if config.tf_padding else int((kernel_size - 1) / 2 )
__snake_case = nn.Convad(
in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , kernel_size=SCREAMING_SNAKE_CASE_ , stride=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , groups=SCREAMING_SNAKE_CASE_ , bias=SCREAMING_SNAKE_CASE_ , padding_mode='zeros' , )
if use_normalization:
__snake_case = nn.BatchNormad(
num_features=SCREAMING_SNAKE_CASE_ , eps=config.layer_norm_eps , momentum=0.9_9_9_7 , affine=SCREAMING_SNAKE_CASE_ , track_running_stats=SCREAMING_SNAKE_CASE_ , )
else:
__snake_case = None
if use_activation:
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
__snake_case = ACTaFN[use_activation]
elif isinstance(config.hidden_act , SCREAMING_SNAKE_CASE_ ):
__snake_case = ACTaFN[config.hidden_act]
else:
__snake_case = config.hidden_act
else:
__snake_case = None
def a ( self : List[str] , SCREAMING_SNAKE_CASE_ : torch.Tensor ) -> torch.Tensor:
if self.config.tf_padding:
__snake_case = apply_tf_padding(SCREAMING_SNAKE_CASE_ , self.convolution )
__snake_case = self.convolution(SCREAMING_SNAKE_CASE_ )
if self.normalization is not None:
__snake_case = self.normalization(SCREAMING_SNAKE_CASE_ )
if self.activation is not None:
__snake_case = self.activation(SCREAMING_SNAKE_CASE_ )
return features
class _lowercase ( __lowercase ):
_SCREAMING_SNAKE_CASE : Tuple = MobileNetVaConfig
_SCREAMING_SNAKE_CASE : Optional[Any] = load_tf_weights_in_mobilenet_va
_SCREAMING_SNAKE_CASE : Any = "mobilenet_v1"
_SCREAMING_SNAKE_CASE : Optional[Any] = "pixel_values"
_SCREAMING_SNAKE_CASE : List[Any] = False
def a ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[nn.Linear, nn.Convad] ) -> None:
if isinstance(SCREAMING_SNAKE_CASE_ , (nn.Linear, nn.Convad) ):
module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range )
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(SCREAMING_SNAKE_CASE_ , nn.BatchNormad ):
module.bias.data.zero_()
module.weight.data.fill_(1.0 )
_a : Optional[Any] = R"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"
_a : str = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`MobileNetV1ImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"
@add_start_docstrings(
"The bare MobileNetV1 model outputting raw hidden-states without any specific head on top." , __lowercase , )
class _lowercase ( __lowercase ):
def __init__( self : str , SCREAMING_SNAKE_CASE_ : MobileNetVaConfig , SCREAMING_SNAKE_CASE_ : bool = True ) -> Any:
super().__init__(SCREAMING_SNAKE_CASE_ )
__snake_case = config
__snake_case = 32
__snake_case = max(int(depth * config.depth_multiplier ) , config.min_depth )
__snake_case = MobileNetVaConvLayer(
SCREAMING_SNAKE_CASE_ , in_channels=config.num_channels , out_channels=SCREAMING_SNAKE_CASE_ , kernel_size=3 , stride=2 , )
__snake_case = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]
__snake_case = nn.ModuleList()
for i in range(13 ):
__snake_case = out_channels
if strides[i] == 2 or i == 0:
depth *= 2
__snake_case = max(int(depth * config.depth_multiplier ) , config.min_depth )
self.layer.append(
MobileNetVaConvLayer(
SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , kernel_size=3 , stride=strides[i] , groups=SCREAMING_SNAKE_CASE_ , ) )
self.layer.append(
MobileNetVaConvLayer(
SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , kernel_size=1 , ) )
__snake_case = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None
# Initialize weights and apply final processing
self.post_init()
def a ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : int ) -> Dict:
raise NotImplementedError
@add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE_ )
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC , output_type=SCREAMING_SNAKE_CASE_ , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , )
def a ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , ) -> Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
__snake_case = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
__snake_case = return_dict if return_dict is not None else self.config.use_return_dict
if pixel_values is None:
raise ValueError('You have to specify pixel_values' )
__snake_case = self.conv_stem(SCREAMING_SNAKE_CASE_ )
__snake_case = () if output_hidden_states else None
for i, layer_module in enumerate(self.layer ):
__snake_case = layer_module(SCREAMING_SNAKE_CASE_ )
if output_hidden_states:
__snake_case = all_hidden_states + (hidden_states,)
__snake_case = hidden_states
if self.pooler is not None:
__snake_case = torch.flatten(self.pooler(SCREAMING_SNAKE_CASE_ ) , start_dim=1 )
else:
__snake_case = None
if not return_dict:
return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None )
return BaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=SCREAMING_SNAKE_CASE_ , pooler_output=SCREAMING_SNAKE_CASE_ , hidden_states=SCREAMING_SNAKE_CASE_ , )
@add_start_docstrings(
"\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , __lowercase , )
class _lowercase ( __lowercase ):
def __init__( self : int , SCREAMING_SNAKE_CASE_ : MobileNetVaConfig ) -> None:
super().__init__(SCREAMING_SNAKE_CASE_ )
__snake_case = config.num_labels
__snake_case = MobileNetVaModel(SCREAMING_SNAKE_CASE_ )
__snake_case = self.mobilenet_va.layer[-1].convolution.out_channels
# Classifier head
__snake_case = nn.Dropout(config.classifier_dropout_prob , inplace=SCREAMING_SNAKE_CASE_ )
__snake_case = nn.Linear(SCREAMING_SNAKE_CASE_ , config.num_labels ) if config.num_labels > 0 else nn.Identity()
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE_ )
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=SCREAMING_SNAKE_CASE_ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , )
def a ( self : Tuple , SCREAMING_SNAKE_CASE_ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , SCREAMING_SNAKE_CASE_ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , ) -> Union[tuple, ImageClassifierOutputWithNoAttention]:
__snake_case = return_dict if return_dict is not None else self.config.use_return_dict
__snake_case = self.mobilenet_va(SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ )
__snake_case = outputs.pooler_output if return_dict else outputs[1]
__snake_case = self.classifier(self.dropout(SCREAMING_SNAKE_CASE_ ) )
__snake_case = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
__snake_case = 'regression'
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
__snake_case = 'single_label_classification'
else:
__snake_case = 'multi_label_classification'
if self.config.problem_type == "regression":
__snake_case = MSELoss()
if self.num_labels == 1:
__snake_case = loss_fct(logits.squeeze() , labels.squeeze() )
else:
__snake_case = loss_fct(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
elif self.config.problem_type == "single_label_classification":
__snake_case = CrossEntropyLoss()
__snake_case = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
elif self.config.problem_type == "multi_label_classification":
__snake_case = BCEWithLogitsLoss()
__snake_case = loss_fct(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
if not return_dict:
__snake_case = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return ImageClassifierOutputWithNoAttention(
loss=SCREAMING_SNAKE_CASE_ , logits=SCREAMING_SNAKE_CASE_ , hidden_states=outputs.hidden_states , )
| 56
|
# 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 __UpperCAmelCase ( __A ):
"""simple docstring"""
_lowerCamelCase = (
"""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."""
)
_lowerCamelCase = """CIDAS/clipseg-rd64-refined"""
_lowerCamelCase = """image_segmenter"""
_lowerCamelCase = CLIPSegForImageSegmentation
_lowerCamelCase = ["""image""", """text"""]
_lowerCamelCase = ["""image"""]
def __init__( self , *__A , **__A ):
requires_backends(self , ["""vision"""] )
super().__init__(*__A , **__A )
def snake_case_ ( self , __A , __A ):
return self.pre_processor(text=[label] , images=[image] , padding=__A , return_tensors="""pt""" )
def snake_case_ ( self , __A ):
with torch.no_grad():
__a = self.model(**__A ).logits
return logits
def snake_case_ ( self , __A ):
__a = outputs.cpu().detach().numpy()
__a = 0
__a = 1
return Image.fromarray((array * 255).astype(np.uinta ) )
| 99
| 0
|
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
SCREAMING_SNAKE_CASE = {
'configuration_luke': ['LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LukeConfig'],
'tokenization_luke': ['LukeTokenizer'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE = [
'LUKE_PRETRAINED_MODEL_ARCHIVE_LIST',
'LukeForEntityClassification',
'LukeForEntityPairClassification',
'LukeForEntitySpanClassification',
'LukeForMultipleChoice',
'LukeForQuestionAnswering',
'LukeForSequenceClassification',
'LukeForTokenClassification',
'LukeForMaskedLM',
'LukeModel',
'LukePreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig
from .tokenization_luke import LukeTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_luke import (
LUKE_PRETRAINED_MODEL_ARCHIVE_LIST,
LukeForEntityClassification,
LukeForEntityPairClassification,
LukeForEntitySpanClassification,
LukeForMaskedLM,
LukeForMultipleChoice,
LukeForQuestionAnswering,
LukeForSequenceClassification,
LukeForTokenClassification,
LukeModel,
LukePreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 186
|
from math import pow, sqrt
def _lowerCamelCase ( *__A : float ) -> bool:
_UpperCAmelCase : str = len(__A ) > 0 and all(value > 0.0 for value in values )
return result
def _lowerCamelCase ( __A : float , __A : float ) -> float | ValueError:
return (
round(sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(__A , __A )
else ValueError('''Input Error: Molar mass values must greater than 0.''' )
)
def _lowerCamelCase ( __A : float , __A : float , __A : float ) -> float | ValueError:
return (
round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(__A , __A , __A )
else ValueError(
'''Input Error: Molar mass and effusion rate values must greater than 0.''' )
)
def _lowerCamelCase ( __A : float , __A : float , __A : float ) -> float | ValueError:
return (
round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(__A , __A , __A )
else ValueError(
'''Input Error: Molar mass and effusion rate values must greater than 0.''' )
)
def _lowerCamelCase ( __A : float , __A : float , __A : float ) -> float | ValueError:
return (
round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 )
if validate(__A , __A , __A )
else ValueError(
'''Input Error: Molar mass and effusion rate values must greater than 0.''' )
)
def _lowerCamelCase ( __A : float , __A : float , __A : float ) -> float | ValueError:
return (
round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 )
if validate(__A , __A , __A )
else ValueError(
'''Input Error: Molar mass and effusion rate values must greater than 0.''' )
)
| 186
| 1
|
'''simple docstring'''
def a_ ( _UpperCAmelCase : int ) -> str:
if number > 0:
raise ValueError('input must be a negative integer' )
__snake_case : Dict = len(bin(_UpperCAmelCase )[3:] )
__snake_case : List[Any] = bin(abs(_UpperCAmelCase ) - (1 << binary_number_length) )[3:]
__snake_case : List[str] = (
(
'''1'''
+ '''0''' * (binary_number_length - len(_UpperCAmelCase ))
+ twos_complement_number
)
if number < 0
else '''0'''
)
return "0b" + twos_complement_number
if __name__ == "__main__":
import doctest
doctest.testmod()
| 286
|
'''simple docstring'''
import argparse
import json
import os
import fairseq
import torch
from fairseq.data import Dictionary
from transformers import (
WavaVecaConformerConfig,
WavaVecaConformerForCTC,
WavaVecaConformerForPreTraining,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaProcessor,
logging,
)
logging.set_verbosity_info()
UpperCamelCase_ = logging.get_logger(__name__)
UpperCamelCase_ = {
"""post_extract_proj""": """feature_projection.projection""",
"""encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""",
"""self_attn.linear_k""": """encoder.layers.*.self_attn.linear_k""",
"""self_attn.linear_v""": """encoder.layers.*.self_attn.linear_v""",
"""self_attn.linear_q""": """encoder.layers.*.self_attn.linear_q""",
"""self_attn.pos_bias_u""": """encoder.layers.*.self_attn.pos_bias_u""",
"""self_attn.pos_bias_v""": """encoder.layers.*.self_attn.pos_bias_v""",
"""self_attn.linear_out""": """encoder.layers.*.self_attn.linear_out""",
"""self_attn.linear_pos""": """encoder.layers.*.self_attn.linear_pos""",
"""self_attn.rotary_emb""": """encoder.embed_positions""",
"""self_attn_layer_norm""": """encoder.layers.*.self_attn_layer_norm""",
"""conv_module.pointwise_conv1""": """encoder.layers.*.conv_module.pointwise_conv1""",
"""conv_module.pointwise_conv2""": """encoder.layers.*.conv_module.pointwise_conv2""",
"""conv_module.depthwise_conv""": """encoder.layers.*.conv_module.depthwise_conv""",
"""conv_module.batch_norm""": """encoder.layers.*.conv_module.batch_norm""",
"""conv_module.layer_norm""": """encoder.layers.*.conv_module.layer_norm""",
"""ffn1.w_1""": """encoder.layers.*.ffn1.intermediate_dense""",
"""ffn1.w_2""": """encoder.layers.*.ffn1.output_dense""",
"""ffn1.layer_norm""": """encoder.layers.*.ffn1_layer_norm""",
"""ffn2.w_1""": """encoder.layers.*.ffn2.intermediate_dense""",
"""ffn2.w_2""": """encoder.layers.*.ffn2.output_dense""",
"""ffn2.layer_norm""": """encoder.layers.*.ffn2_layer_norm""",
"""final_layer_norm""": """encoder.layers.*.final_layer_norm""",
"""encoder.layer_norm""": """encoder.layer_norm""",
"""w2v_model.layer_norm""": """feature_projection.layer_norm""",
"""quantizer.weight_proj""": """quantizer.weight_proj""",
"""quantizer.vars""": """quantizer.codevectors""",
"""project_q""": """project_q""",
"""final_proj""": """project_hid""",
"""w2v_encoder.proj""": """lm_head""",
"""mask_emb""": """masked_spec_embed""",
}
UpperCamelCase_ = [
"""lm_head""",
"""quantizer.weight_proj""",
"""quantizer.codevectors""",
"""project_q""",
"""project_hid""",
]
def _lowerCAmelCase ( __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple ) -> str:
for attribute in key.split('''.''' ):
lowercase : Tuple =getattr(__magic_name__ , __magic_name__ )
if weight_type is not None:
lowercase : Optional[int] =getattr(__magic_name__ , __magic_name__ ).shape
else:
lowercase : List[Any] =hf_pointer.shape
if hf_shape != value.shape:
raise ValueError(
f'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'''
f''' {value.shape} for {full_name}''' )
if weight_type == "weight":
lowercase : Any =value
elif weight_type == "weight_g":
lowercase : List[Any] =value
elif weight_type == "weight_v":
lowercase : Union[str, Any] =value
elif weight_type == "bias":
lowercase : Tuple =value
elif weight_type == "running_mean":
lowercase : Union[str, Any] =value
elif weight_type == "running_var":
lowercase : str =value
elif weight_type == "num_batches_tracked":
lowercase : Tuple =value
elif weight_type == "inv_freq":
lowercase : Optional[Any] =value
else:
lowercase : Tuple =value
logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' )
def _lowerCAmelCase ( __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : str ) -> Union[str, Any]:
lowercase : Optional[int] =[]
lowercase : Tuple =fairseq_model.state_dict()
lowercase : List[Any] =hf_model.wavaveca_conformer.feature_extractor
for name, value in fairseq_dict.items():
lowercase : Tuple =False
if "conv_layers" in name:
load_conv_layer(
__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , hf_model.config.feat_extract_norm == '''group''' , )
lowercase : List[Any] =True
else:
for key, mapped_key in MAPPING.items():
lowercase : Optional[int] ='''wav2vec2_conformer.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]:
lowercase : Union[str, Any] =True
if "*" in mapped_key:
lowercase : Optional[int] =name.split(__magic_name__ )[0].split('''.''' )[-2]
lowercase : List[str] =mapped_key.replace('''*''' , __magic_name__ )
if "pos_bias_u" in name:
lowercase : Optional[Any] =None
elif "pos_bias_v" in name:
lowercase : Union[str, Any] =None
elif "weight_g" in name:
lowercase : Any ='''weight_g'''
elif "weight_v" in name:
lowercase : Tuple ='''weight_v'''
elif "bias" in name:
lowercase : Optional[int] ='''bias'''
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
lowercase : Optional[int] ='''weight'''
elif "running_mean" in name:
lowercase : Union[str, Any] ='''running_mean'''
elif "inv_freq" in name:
lowercase : Any ='''inv_freq'''
elif "running_var" in name:
lowercase : Tuple ='''running_var'''
elif "num_batches_tracked" in name:
lowercase : Dict ='''num_batches_tracked'''
else:
lowercase : str =None
set_recursively(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ )
continue
if not is_used:
unused_weights.append(__magic_name__ )
logger.warning(f'''Unused weights: {unused_weights}''' )
def _lowerCAmelCase ( __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Tuple ) -> int:
lowercase : Optional[Any] =full_name.split('''conv_layers.''' )[-1]
lowercase : Any =name.split('''.''' )
lowercase : List[str] =int(items[0] )
lowercase : Union[str, Any] =int(items[1] )
if type_id == 0:
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
raise ValueError(
f'''{full_name} has size {value.shape}, but'''
f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' )
lowercase : Union[str, Any] =value
logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
raise ValueError(
f'''{full_name} has size {value.shape}, but'''
f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' )
lowercase : Optional[Any] =value
logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
raise ValueError(
f'''{full_name} has size {value.shape}, but'''
f''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' )
lowercase : Optional[int] =value
logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
raise ValueError(
f'''{full_name} has size {value.shape}, but'''
f''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' )
lowercase : str =value
logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
else:
unused_weights.append(__magic_name__ )
@torch.no_grad()
def _lowerCAmelCase ( __magic_name__ : List[str] , __magic_name__ : Optional[Any] , __magic_name__ : Tuple=None , __magic_name__ : Optional[Any]=None , __magic_name__ : Union[str, Any]=True ) -> Union[str, Any]:
if config_path is not None:
lowercase : Optional[Any] =WavaVecaConformerConfig.from_pretrained(__magic_name__ , hidden_act='''swish''' )
else:
lowercase : Optional[int] =WavaVecaConformerConfig()
if "rope" in checkpoint_path:
lowercase : Dict ='''rotary'''
if is_finetuned:
if dict_path:
lowercase : Optional[Any] =Dictionary.load(__magic_name__ )
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
lowercase : str =target_dict.pad_index
lowercase : Union[str, Any] =target_dict.bos_index
lowercase : Any =target_dict.eos_index
lowercase : Tuple =len(target_dict.symbols )
lowercase : str =os.path.join(__magic_name__ , '''vocab.json''' )
if not os.path.isdir(__magic_name__ ):
logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(__magic_name__ ) )
return
os.makedirs(__magic_name__ , exist_ok=__magic_name__ )
lowercase : Dict =target_dict.indices
# fairseq has the <pad> and <s> switched
lowercase : str =0
lowercase : List[Any] =1
with open(__magic_name__ , '''w''' , encoding='''utf-8''' ) as vocab_handle:
json.dump(__magic_name__ , __magic_name__ )
lowercase : List[str] =WavaVecaCTCTokenizer(
__magic_name__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=__magic_name__ , )
lowercase : Optional[int] =True if config.feat_extract_norm == '''layer''' else False
lowercase : str =WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=__magic_name__ , return_attention_mask=__magic_name__ , )
lowercase : Tuple =WavaVecaProcessor(feature_extractor=__magic_name__ , tokenizer=__magic_name__ )
processor.save_pretrained(__magic_name__ )
lowercase : str =WavaVecaConformerForCTC(__magic_name__ )
else:
lowercase : Tuple =WavaVecaConformerForPreTraining(__magic_name__ )
if is_finetuned:
lowercase , lowercase , lowercase : Optional[int] =fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} )
else:
lowercase : Dict =argparse.Namespace(task='''audio_pretraining''' )
lowercase : Optional[int] =fairseq.tasks.setup_task(__magic_name__ )
lowercase , lowercase , lowercase : str =fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=__magic_name__ )
lowercase : List[Any] =model[0].eval()
recursively_load_weights(__magic_name__ , __magic_name__ , not is_finetuned )
hf_wavavec.save_pretrained(__magic_name__ )
if __name__ == "__main__":
UpperCamelCase_ = argparse.ArgumentParser()
parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""")
parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""")
parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
parser.add_argument(
"""--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not"""
)
UpperCamelCase_ = parser.parse_args()
convert_wavaveca_conformer_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
)
| 92
| 0
|
"""simple docstring"""
import warnings
warnings.warn(
"memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: "
"`from accelerate import find_executable_batch_size` to avoid this warning.",
FutureWarning,
)
| 359
|
"""simple docstring"""
import os
import pytest
import yaml
from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
"""files""" , [
["""full:README.md""", """dataset_infos.json"""],
["""empty:README.md""", """dataset_infos.json"""],
["""dataset_infos.json"""],
["""full:README.md"""],
] , )
def _snake_case ( UpperCamelCase : str , UpperCamelCase : Optional[Any] ):
UpperCAmelCase : List[Any] = tmp_path_factory.mktemp("""dset_infos_dir""" )
if "full:README.md" in files:
with open(dataset_infos_dir / """README.md""" , """w""" ) as f:
f.write("""---\ndataset_info:\n dataset_size: 42\n---""" )
if "empty:README.md" in files:
with open(dataset_infos_dir / """README.md""" , """w""" ) as f:
f.write("""""" )
# we want to support dataset_infos.json for backward compatibility
if "dataset_infos.json" in files:
with open(dataset_infos_dir / """dataset_infos.json""" , """w""" ) as f:
f.write("""{\"default\": {\"dataset_size\": 42}}""" )
UpperCAmelCase : str = DatasetInfosDict.from_directory(UpperCamelCase )
assert dataset_infos
assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
"""dataset_info""" , [
DatasetInfo(),
DatasetInfo(
description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=42 , ),
] , )
def _snake_case ( UpperCamelCase : str , UpperCamelCase : DatasetInfo ):
UpperCAmelCase : List[Any] = str(UpperCamelCase )
dataset_info.write_to_directory(UpperCamelCase )
UpperCAmelCase : List[str] = DatasetInfo.from_directory(UpperCamelCase )
assert dataset_info == reloaded
assert os.path.exists(os.path.join(UpperCamelCase , """dataset_info.json""" ) )
def _snake_case ( ):
UpperCAmelCase : List[str] = DatasetInfo(
description="""foo""" , citation="""bar""" , homepage="""https://foo.bar""" , license="""CC0""" , features=Features({"""a""": Value("""int32""" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train""", """num_examples""": 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , )
UpperCAmelCase : str = dataset_info._to_yaml_dict()
assert sorted(UpperCamelCase ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML )
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
assert key in dataset_info_yaml_dict
assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) )
UpperCAmelCase : Union[str, Any] = yaml.safe_dump(UpperCamelCase )
UpperCAmelCase : List[str] = yaml.safe_load(UpperCamelCase )
assert dataset_info_yaml_dict == reloaded
def _snake_case ( ):
UpperCAmelCase : List[str] = DatasetInfo()
UpperCAmelCase : Union[str, Any] = dataset_info._to_yaml_dict()
assert dataset_info_yaml_dict == {}
@pytest.mark.parametrize(
"""dataset_infos_dict""" , [
DatasetInfosDict(),
DatasetInfosDict({"""default""": DatasetInfo()} ),
DatasetInfosDict({"""my_config_name""": DatasetInfo()} ),
DatasetInfosDict(
{
"""default""": DatasetInfo(
description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=42 , )
} ),
DatasetInfosDict(
{
"""v1""": DatasetInfo(dataset_size=42 ),
"""v2""": DatasetInfo(dataset_size=1337 ),
} ),
] , )
def _snake_case ( UpperCamelCase : Optional[int] , UpperCamelCase : DatasetInfosDict ):
UpperCAmelCase : List[str] = str(UpperCamelCase )
dataset_infos_dict.write_to_directory(UpperCamelCase )
UpperCAmelCase : List[Any] = DatasetInfosDict.from_directory(UpperCamelCase )
# the config_name of the dataset_infos_dict take over the attribute
for config_name, dataset_info in dataset_infos_dict.items():
UpperCAmelCase : Union[str, Any] = config_name
# the yaml representation doesn't include fields like description or citation
# so we just test that we can recover what we can from the yaml
UpperCAmelCase : Optional[Any] = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() )
assert dataset_infos_dict == reloaded
if dataset_infos_dict:
assert os.path.exists(os.path.join(UpperCamelCase , """README.md""" ) )
| 359
| 1
|
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
_A : Optional[Any] = {
'configuration_data2vec_audio': ['DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecAudioConfig'],
'configuration_data2vec_text': [
'DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP',
'Data2VecTextConfig',
'Data2VecTextOnnxConfig',
],
'configuration_data2vec_vision': [
'DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP',
'Data2VecVisionConfig',
'Data2VecVisionOnnxConfig',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_A : Union[str, Any] = [
'DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST',
'Data2VecAudioForAudioFrameClassification',
'Data2VecAudioForCTC',
'Data2VecAudioForSequenceClassification',
'Data2VecAudioForXVector',
'Data2VecAudioModel',
'Data2VecAudioPreTrainedModel',
]
_A : Optional[Any] = [
'DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST',
'Data2VecTextForCausalLM',
'Data2VecTextForMaskedLM',
'Data2VecTextForMultipleChoice',
'Data2VecTextForQuestionAnswering',
'Data2VecTextForSequenceClassification',
'Data2VecTextForTokenClassification',
'Data2VecTextModel',
'Data2VecTextPreTrainedModel',
]
_A : Optional[int] = [
'DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST',
'Data2VecVisionForImageClassification',
'Data2VecVisionForMaskedImageModeling',
'Data2VecVisionForSemanticSegmentation',
'Data2VecVisionModel',
'Data2VecVisionPreTrainedModel',
]
if is_tf_available():
_A : Union[str, Any] = [
'TFData2VecVisionForImageClassification',
'TFData2VecVisionForSemanticSegmentation',
'TFData2VecVisionModel',
'TFData2VecVisionPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig
from .configuration_dataavec_text import (
DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP,
DataaVecTextConfig,
DataaVecTextOnnxConfig,
)
from .configuration_dataavec_vision import (
DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP,
DataaVecVisionConfig,
DataaVecVisionOnnxConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_dataavec_audio import (
DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST,
DataaVecAudioForAudioFrameClassification,
DataaVecAudioForCTC,
DataaVecAudioForSequenceClassification,
DataaVecAudioForXVector,
DataaVecAudioModel,
DataaVecAudioPreTrainedModel,
)
from .modeling_dataavec_text import (
DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
DataaVecTextForCausalLM,
DataaVecTextForMaskedLM,
DataaVecTextForMultipleChoice,
DataaVecTextForQuestionAnswering,
DataaVecTextForSequenceClassification,
DataaVecTextForTokenClassification,
DataaVecTextModel,
DataaVecTextPreTrainedModel,
)
from .modeling_dataavec_vision import (
DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST,
DataaVecVisionForImageClassification,
DataaVecVisionForMaskedImageModeling,
DataaVecVisionForSemanticSegmentation,
DataaVecVisionModel,
DataaVecVisionPreTrainedModel,
)
if is_tf_available():
from .modeling_tf_dataavec_vision import (
TFDataaVecVisionForImageClassification,
TFDataaVecVisionForSemanticSegmentation,
TFDataaVecVisionModel,
TFDataaVecVisionPreTrainedModel,
)
else:
import sys
_A : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 315
|
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_A : Dict = logging.get_logger(__name__)
_A : Union[str, Any] = {
'studio-ousia/luke-base': 'https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json',
'studio-ousia/luke-large': 'https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json',
}
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ):
_UpperCAmelCase : Optional[int] = "luke"
def __init__( self : int , A : Optional[int]=5_0_2_6_7 , A : Any=5_0_0_0_0_0 , A : Tuple=7_6_8 , A : List[Any]=2_5_6 , A : Any=1_2 , A : List[Any]=1_2 , A : Tuple=3_0_7_2 , A : str="gelu" , A : Optional[int]=0.1 , A : Tuple=0.1 , A : List[Any]=5_1_2 , A : Optional[int]=2 , A : Dict=0.02 , A : Union[str, Any]=1e-12 , A : Dict=True , A : Optional[Any]=None , A : Dict=1 , A : str=0 , A : int=2 , **A : Optional[int] , ) ->Optional[int]:
super().__init__(pad_token_id=A , bos_token_id=A , eos_token_id=A , **A )
lowerCamelCase__ : Any = vocab_size
lowerCamelCase__ : Dict = entity_vocab_size
lowerCamelCase__ : List[str] = hidden_size
lowerCamelCase__ : Optional[int] = entity_emb_size
lowerCamelCase__ : Any = num_hidden_layers
lowerCamelCase__ : List[str] = num_attention_heads
lowerCamelCase__ : Any = hidden_act
lowerCamelCase__ : int = intermediate_size
lowerCamelCase__ : Tuple = hidden_dropout_prob
lowerCamelCase__ : Dict = attention_probs_dropout_prob
lowerCamelCase__ : List[str] = max_position_embeddings
lowerCamelCase__ : Any = type_vocab_size
lowerCamelCase__ : str = initializer_range
lowerCamelCase__ : Optional[int] = layer_norm_eps
lowerCamelCase__ : Dict = use_entity_aware_attention
lowerCamelCase__ : Optional[int] = classifier_dropout
| 315
| 1
|
"""simple docstring"""
import collections
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
lowercase_ = logging.get_logger(__name__)
lowercase_ = '▁'
lowercase_ = {'vocab_file': 'prophetnet.tokenizer'}
lowercase_ = {
'vocab_file': {
'microsoft/xprophetnet-large-wiki100-cased': (
'https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/prophetnet.tokenizer'
),
}
}
lowercase_ = {
'microsoft/xprophetnet-large-wiki100-cased': {'do_lower_case': False},
}
lowercase_ = {
'microsoft/xprophetnet-large-wiki100-cased': 512,
}
def lowerCAmelCase ( __UpperCamelCase ):
"""simple docstring"""
__A = collections.OrderedDict()
with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as reader:
__A = reader.readlines()
for index, token in enumerate(__UpperCamelCase ):
__A = token.rstrip('''\n''' )
__A = index
return vocab
class snake_case ( _lowerCAmelCase ):
'''simple docstring'''
A_ : Tuple = VOCAB_FILES_NAMES
A_ : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP
A_ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
A_ : Optional[int] = ["input_ids", "attention_mask"]
def __init__( self : Dict, _lowerCamelCase : str, _lowerCamelCase : Union[str, Any]="[SEP]", _lowerCamelCase : Tuple="[SEP]", _lowerCamelCase : List[Any]="[SEP]", _lowerCamelCase : Tuple="[UNK]", _lowerCamelCase : Union[str, Any]="[PAD]", _lowerCamelCase : List[Any]="[CLS]", _lowerCamelCase : Tuple="[MASK]", _lowerCamelCase : Optional[Dict[str, Any]] = None, **_lowerCamelCase : Optional[Any], ):
'''simple docstring'''
__A = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=_lowerCamelCase, eos_token=_lowerCamelCase, sep_token=_lowerCamelCase, unk_token=_lowerCamelCase, pad_token=_lowerCamelCase, cls_token=_lowerCamelCase, mask_token=_lowerCamelCase, sp_model_kwargs=self.sp_model_kwargs, **_lowerCamelCase, )
try:
import sentencepiece as spm
except ImportError:
logger.warning(
'''You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece'''
''' pip install sentencepiece''' )
raise
__A = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(_lowerCamelCase ) )
__A = vocab_file
# Original fairseq vocab and spm vocab must be "aligned":
# Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
# fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-'
# spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
# put special tokens and [unused] tokens into the vocab
__A = {'''[PAD]''': 0, '''[CLS]''': 1, '''[SEP]''': 2, '''[UNK]''': 3, '''[MASK]''': 4}
for i in range(10 ):
__A = f'[unused{i}]'
__A = 5 + i
# The first "real" token "," has position 15 in the embedding vocab and position 3 in the spm vocab
__A = 12
__A = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
for k in self.fairseq_tokens_to_ids.keys():
self.unique_no_split_tokens.append(_lowerCamelCase )
def __getstate__( self : List[str] ):
'''simple docstring'''
__A = self.__dict__.copy()
__A = None
return state
def __setstate__( self : Dict, _lowerCamelCase : List[Any] ):
'''simple docstring'''
__A = d
try:
import sentencepiece as spm
except ImportError:
logger.warning(
'''You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece'''
''' pip install sentencepiece''' )
raise
# 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 _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None, _lowerCamelCase : bool = False ):
'''simple docstring'''
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 ([0] * len(_lowerCamelCase )) + [1]
return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1]
def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ):
'''simple docstring'''
__A = [self.sep_token_id]
if token_ids_a is None:
return len(token_ids_a + sep ) * [0]
return len(token_ids_a + sep + sep + token_ids_a + sep ) * [0]
@property
def _SCREAMING_SNAKE_CASE ( self : List[str] ):
'''simple docstring'''
return len(self.sp_model ) + self.fairseq_offset
def _SCREAMING_SNAKE_CASE ( self : List[str] ):
'''simple docstring'''
__A = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : str ):
'''simple docstring'''
return self.sp_model.encode(_lowerCamelCase, out_type=_lowerCamelCase )
def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : Optional[Any] ):
'''simple docstring'''
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
__A = self.sp_model.PieceToId(_lowerCamelCase )
# Need to return unknown token if the SP model returned 0
return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : List[str] ):
'''simple docstring'''
if index in self.fairseq_ids_to_tokens:
return self.fairseq_ids_to_tokens[index]
return self.sp_model.IdToPiece(index - self.fairseq_offset )
def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : Dict ):
'''simple docstring'''
__A = ''''''.join(_lowerCamelCase ).replace(_lowerCamelCase, ''' ''' ).strip()
return out_string
def _SCREAMING_SNAKE_CASE ( self : int, _lowerCamelCase : str, _lowerCamelCase : Optional[str] = None ):
'''simple docstring'''
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,)
def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ):
'''simple docstring'''
if token_ids_a is None:
return token_ids_a + [self.sep_token_id]
__A = [self.sep_token_id]
return token_ids_a + sep + token_ids_a + sep
| 215
|
"""simple docstring"""
# Copyright 2021 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.
import argparse
import os
from accelerate.utils import ComputeEnvironment
from .cluster import get_cluster_input
from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401
from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401
from .sagemaker import get_sagemaker_input
lowercase_ = 'Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine'
def lowerCAmelCase ( ):
"""simple docstring"""
__A = _ask_options(
'''In which compute environment are you running?''' , ['''This machine''', '''AWS (Amazon SageMaker)'''] , _convert_compute_environment , )
if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
__A = get_sagemaker_input()
else:
__A = get_cluster_input()
return config
def lowerCAmelCase ( __UpperCamelCase=None ):
"""simple docstring"""
if subparsers is not None:
__A = subparsers.add_parser('''config''' , description=__UpperCamelCase )
else:
__A = argparse.ArgumentParser('''Accelerate config command''' , description=__UpperCamelCase )
parser.add_argument(
'''--config_file''' , default=__UpperCamelCase , help=(
'''The path to use to store the config file. Will default to a file named default_config.yaml in the cache '''
'''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '''
'''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '''
'''with \'huggingface\'.'''
) , )
if subparsers is not None:
parser.set_defaults(func=__UpperCamelCase )
return parser
def lowerCAmelCase ( __UpperCamelCase ):
"""simple docstring"""
__A = get_user_input()
if args.config_file is not None:
__A = args.config_file
else:
if not os.path.isdir(__UpperCamelCase ):
os.makedirs(__UpperCamelCase )
__A = default_yaml_config_file
if config_file.endswith('''.json''' ):
config.to_json_file(__UpperCamelCase )
else:
config.to_yaml_file(__UpperCamelCase )
print(f'accelerate configuration saved at {config_file}' )
def lowerCAmelCase ( ):
"""simple docstring"""
__A = config_command_parser()
__A = parser.parse_args()
config_command(__UpperCamelCase )
if __name__ == "__main__":
main()
| 215
| 1
|
'''simple docstring'''
import warnings
from ...utils import logging
from .image_processing_donut import DonutImageProcessor
UpperCAmelCase_ = logging.get_logger(__name__)
class lowerCAmelCase_ ( lowerCamelCase_ ):
'''simple docstring'''
def __init__( self : List[str] , *_UpperCAmelCase : Optional[Any] , **_UpperCAmelCase : Tuple ):
"""simple docstring"""
warnings.warn(
"""The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"""
""" use DonutImageProcessor instead.""" , _UpperCAmelCase , )
super().__init__(*_UpperCAmelCase , **_UpperCAmelCase )
| 603
|
'''simple docstring'''
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 lowerCAmelCase_ ( lowerCamelCase_ , unittest.TestCase ):
'''simple docstring'''
lowerCAmelCase_ : Any = KandinskyVaaControlnetPipeline
lowerCAmelCase_ : int = ["""image_embeds""", """negative_image_embeds""", """hint"""]
lowerCAmelCase_ : List[str] = ["""image_embeds""", """negative_image_embeds""", """hint"""]
lowerCAmelCase_ : Union[str, Any] = [
"""generator""",
"""height""",
"""width""",
"""latents""",
"""guidance_scale""",
"""num_inference_steps""",
"""return_dict""",
"""guidance_scale""",
"""num_images_per_prompt""",
"""output_type""",
"""return_dict""",
]
lowerCAmelCase_ : List[Any] = False
@property
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ):
"""simple docstring"""
return 32
@property
def SCREAMING_SNAKE_CASE__ ( self : List[Any] ):
"""simple docstring"""
return 32
@property
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ):
"""simple docstring"""
return self.time_input_dim
@property
def SCREAMING_SNAKE_CASE__ ( self : List[str] ):
"""simple docstring"""
return self.time_input_dim * 4
@property
def SCREAMING_SNAKE_CASE__ ( self : List[str] ):
"""simple docstring"""
return 1_00
@property
def SCREAMING_SNAKE_CASE__ ( self : List[str] ):
"""simple docstring"""
torch.manual_seed(0 )
UpperCAmelCase__ = {
"""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,
}
UpperCAmelCase__ = UNetaDConditionModel(**_UpperCAmelCase )
return model
@property
def SCREAMING_SNAKE_CASE__ ( self : Tuple ):
"""simple docstring"""
return {
"block_out_channels": [32, 32, 64, 64],
"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": 12,
"out_channels": 3,
"up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
"vq_embed_dim": 4,
}
@property
def SCREAMING_SNAKE_CASE__ ( self : Any ):
"""simple docstring"""
torch.manual_seed(0 )
UpperCAmelCase__ = VQModel(**self.dummy_movq_kwargs )
return model
def SCREAMING_SNAKE_CASE__ ( self : List[Any] ):
"""simple docstring"""
UpperCAmelCase__ = self.dummy_unet
UpperCAmelCase__ = self.dummy_movq
UpperCAmelCase__ = DDIMScheduler(
num_train_timesteps=10_00 , beta_schedule="""linear""" , beta_start=0.0_0085 , beta_end=0.012 , clip_sample=_UpperCAmelCase , set_alpha_to_one=_UpperCAmelCase , steps_offset=1 , prediction_type="""epsilon""" , thresholding=_UpperCAmelCase , )
UpperCAmelCase__ = {
"""unet""": unet,
"""scheduler""": scheduler,
"""movq""": movq,
}
return components
def SCREAMING_SNAKE_CASE__ ( self : List[str] , _UpperCAmelCase : Any , _UpperCAmelCase : Dict=0 ):
"""simple docstring"""
UpperCAmelCase__ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase )
UpperCAmelCase__ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to(
_UpperCAmelCase )
# create hint
UpperCAmelCase__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase )
if str(_UpperCAmelCase ).startswith("""mps""" ):
UpperCAmelCase__ = torch.manual_seed(_UpperCAmelCase )
else:
UpperCAmelCase__ = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase )
UpperCAmelCase__ = {
"""image_embeds""": image_embeds,
"""negative_image_embeds""": negative_image_embeds,
"""hint""": hint,
"""generator""": generator,
"""height""": 64,
"""width""": 64,
"""guidance_scale""": 4.0,
"""num_inference_steps""": 2,
"""output_type""": """np""",
}
return inputs
def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ):
"""simple docstring"""
UpperCAmelCase__ = """cpu"""
UpperCAmelCase__ = self.get_dummy_components()
UpperCAmelCase__ = self.pipeline_class(**_UpperCAmelCase )
UpperCAmelCase__ = pipe.to(_UpperCAmelCase )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
UpperCAmelCase__ = pipe(**self.get_dummy_inputs(_UpperCAmelCase ) )
UpperCAmelCase__ = output.images
UpperCAmelCase__ = pipe(
**self.get_dummy_inputs(_UpperCAmelCase ) , return_dict=_UpperCAmelCase , )[0]
UpperCAmelCase__ = image[0, -3:, -3:, -1]
UpperCAmelCase__ = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
UpperCAmelCase__ = np.array(
[0.695_9826, 0.86_8279, 0.755_8092, 0.6876_9467, 0.8580_5804, 0.6597_7496, 0.4488_5302, 0.595_9111, 0.425_1595] )
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 lowerCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ):
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def SCREAMING_SNAKE_CASE__ ( self : str ):
"""simple docstring"""
UpperCAmelCase__ = load_numpy(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
"""/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy""" )
UpperCAmelCase__ = load_image(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
"""/kandinskyv22/hint_image_cat.png""" )
UpperCAmelCase__ = torch.from_numpy(np.array(_UpperCAmelCase ) ).float() / 255.0
UpperCAmelCase__ = hint.permute(2 , 0 , 1 ).unsqueeze(0 )
UpperCAmelCase__ = KandinskyVaaPriorPipeline.from_pretrained(
"""kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa )
pipe_prior.to(_UpperCAmelCase )
UpperCAmelCase__ = KandinskyVaaControlnetPipeline.from_pretrained(
"""kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa )
UpperCAmelCase__ = pipeline.to(_UpperCAmelCase )
pipeline.set_progress_bar_config(disable=_UpperCAmelCase )
UpperCAmelCase__ = """A robot, 4k photo"""
UpperCAmelCase__ = torch.Generator(device="""cuda""" ).manual_seed(0 )
UpperCAmelCase__ , UpperCAmelCase__ = pipe_prior(
_UpperCAmelCase , generator=_UpperCAmelCase , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple()
UpperCAmelCase__ = torch.Generator(device="""cuda""" ).manual_seed(0 )
UpperCAmelCase__ = pipeline(
image_embeds=_UpperCAmelCase , negative_image_embeds=_UpperCAmelCase , hint=_UpperCAmelCase , generator=_UpperCAmelCase , num_inference_steps=1_00 , output_type="""np""" , )
UpperCAmelCase__ = output.images[0]
assert image.shape == (5_12, 5_12, 3)
assert_mean_pixel_difference(_UpperCAmelCase , _UpperCAmelCase )
| 603
| 1
|
'''simple docstring'''
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__UpperCAmelCase = {
'''configuration_autoformer''': [
'''AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''AutoformerConfig''',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase = [
'''AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''AutoformerForPrediction''',
'''AutoformerModel''',
'''AutoformerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_autoformer import (
AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
AutoformerConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_autoformer import (
AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
AutoformerForPrediction,
AutoformerModel,
AutoformerPreTrainedModel,
)
else:
import sys
__UpperCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 713
|
'''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__ ( a__ ):
'''simple docstring'''
def __init__( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=None ) -> Dict:
super().__init__(
lowerCamelCase_ , question_encoder_tokenizer=lowerCamelCase_ , generator_tokenizer=lowerCamelCase_ , index=lowerCamelCase_ , init_retrieval=lowerCamelCase_ , )
lowerCAmelCase__ = None
def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ ) -> str:
logger.info('''initializing retrieval''' )
# initializing a separate process group for retrieval as the default
# nccl backend doesn't support gather/scatter operations while gloo
# is too slow to replace nccl for the core gpu communication
if dist.is_initialized():
logger.info('''dist initialized''' )
# needs to be set manually
lowerCAmelCase__ = self._infer_socket_ifname()
# avoid clash with the NCCL port
lowerCAmelCase__ = str(distributed_port + 1 )
lowerCAmelCase__ = dist.new_group(ranks=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 __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
return dist.get_rank(group=self.process_group ) == 0
def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=torch.floataa ) -> Union[str, Any]:
lowerCAmelCase__ = torch.empty(lowerCamelCase_ , dtype=lowerCamelCase_ )
dist.scatter(lowerCamelCase_ , src=0 , scatter_list=lowerCamelCase_ , group=self.process_group )
return target_tensor
def __SCREAMING_SNAKE_CASE ( self ) -> str:
lowerCAmelCase__ = psutil.net_if_addrs()
# a hacky way to deal with varying network interface names
lowerCAmelCase__ = next((addr for addr in addrs if addr.startswith('''e''' )) , lowerCamelCase_ )
return ifname
def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ ) -> Tuple[np.ndarray, List[dict]]:
# single GPU training
if not dist.is_initialized():
lowerCAmelCase__ , lowerCAmelCase__ = self._main_retrieve(lowerCamelCase_ , lowerCamelCase_ )
return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(lowerCamelCase_ )
# distributed training
lowerCAmelCase__ = dist.get_world_size(group=self.process_group )
# gather logic
lowerCAmelCase__ = None
if self._is_main():
lowerCAmelCase__ = [torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(lowerCamelCase_ )]
dist.gather(torch.tensor(lowerCamelCase_ ) , dst=0 , gather_list=lowerCamelCase_ , group=self.process_group )
# scatter logic
lowerCAmelCase__ = question_hidden_states.shape[0]
lowerCAmelCase__ = []
lowerCAmelCase__ = []
if self._is_main():
assert len(lowerCamelCase_ ) == world_size
lowerCAmelCase__ , lowerCAmelCase__ = self._main_retrieve(torch.cat(lowerCamelCase_ ).numpy() , lowerCamelCase_ )
lowerCAmelCase__ , lowerCAmelCase__ = torch.tensor(lowerCamelCase_ ), torch.tensor(lowerCamelCase_ )
lowerCAmelCase__ = self._chunk_tensor(lowerCamelCase_ , lowerCamelCase_ )
lowerCAmelCase__ = self._chunk_tensor(lowerCamelCase_ , lowerCamelCase_ )
lowerCAmelCase__ = self._scattered(lowerCamelCase_ , [n_queries, n_docs] , target_type=torch.intaa )
lowerCAmelCase__ = 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_ )
| 98
| 0
|
def __a ( A__ : str , A__ : str ):
if len(A__ ) != len(A__ ):
raise ValueError("String lengths must match!" )
SCREAMING_SNAKE_CASE = 0
for chara, chara in zip(A__ , A__ ):
if chara != chara:
count += 1
return count
if __name__ == "__main__":
import doctest
doctest.testmod()
| 16
|
"""simple docstring"""
def SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ ) -> list:
lowerCAmelCase__ : List[str] = len(lowercase__ )
lowerCAmelCase__ : Dict = []
for i in range(len(lowercase__ ) - pat_len + 1 ):
lowerCAmelCase__ : Union[str, Any] = True
for j in range(lowercase__ ):
if s[i + j] != pattern[j]:
lowerCAmelCase__ : int = False
break
if match_found:
position.append(lowercase__ )
return position
if __name__ == "__main__":
assert naive_pattern_search("""ABCDEFG""", """DE""") == [3]
print(naive_pattern_search("""ABAAABCDBBABCDDEBCABC""", """ABC"""))
| 453
| 0
|
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
lowerCAmelCase_ : Union[str, Any] = {
'configuration_nezha': ['NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'NezhaConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase_ : int = [
'NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST',
'NezhaForNextSentencePrediction',
'NezhaForMaskedLM',
'NezhaForPreTraining',
'NezhaForMultipleChoice',
'NezhaForQuestionAnswering',
'NezhaForSequenceClassification',
'NezhaForTokenClassification',
'NezhaModel',
'NezhaPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_nezha import (
NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST,
NezhaForMaskedLM,
NezhaForMultipleChoice,
NezhaForNextSentencePrediction,
NezhaForPreTraining,
NezhaForQuestionAnswering,
NezhaForSequenceClassification,
NezhaForTokenClassification,
NezhaModel,
NezhaPreTrainedModel,
)
else:
import sys
lowerCAmelCase_ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 713
|
'''simple docstring'''
from collections import defaultdict
from math import ceil, sqrt
def _lowerCamelCase ( lowercase : int = 100_0000 , lowercase : int = 10 ) -> int:
_a = defaultdict(lowercase )
for outer_width in range(3 , (t_limit // 4) + 2 ):
if outer_width * outer_width > t_limit:
_a = max(
ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 )
else:
_a = 1
hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2
for hole_width in range(lowercase , outer_width - 1 , 2 ):
count[outer_width * outer_width - hole_width * hole_width] += 1
return sum(1 for n in count.values() if 1 <= n <= 10 )
if __name__ == "__main__":
print(f"""{solution() = }""")
| 521
| 0
|
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__lowerCamelCase = {
'''configuration_table_transformer''': [
'''TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''TableTransformerConfig''',
'''TableTransformerOnnxConfig''',
]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCamelCase = [
'''TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TableTransformerForObjectDetection''',
'''TableTransformerModel''',
'''TableTransformerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
TableTransformerConfig,
TableTransformerOnnxConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TableTransformerForObjectDetection,
TableTransformerModel,
TableTransformerPreTrainedModel,
)
else:
import sys
__lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 288
|
'''simple docstring'''
snake_case_ = [
9_9_9,
8_0_0,
7_9_9,
6_0_0,
5_9_9,
5_0_0,
4_0_0,
3_9_9,
3_7_7,
3_5_5,
3_3_3,
3_1_1,
2_8_8,
2_6_6,
2_4_4,
2_2_2,
2_0_0,
1_9_9,
1_7_7,
1_5_5,
1_3_3,
1_1_1,
8_8,
6_6,
4_4,
2_2,
0,
]
snake_case_ = [
9_9_9,
9_7_6,
9_5_2,
9_2_8,
9_0_5,
8_8_2,
8_5_8,
8_5_7,
8_1_0,
7_6_2,
7_1_5,
7_1_4,
5_7_2,
4_2_9,
4_2_8,
2_8_6,
2_8_5,
2_3_8,
1_9_0,
1_4_3,
1_4_2,
1_1_8,
9_5,
7_1,
4_7,
2_4,
0,
]
snake_case_ = [
9_9_9,
9_8_8,
9_7_7,
9_6_6,
9_5_5,
9_4_4,
9_3_3,
9_2_2,
9_1_1,
9_0_0,
8_9_9,
8_7_9,
8_5_9,
8_4_0,
8_2_0,
8_0_0,
7_9_9,
7_6_6,
7_3_3,
7_0_0,
6_9_9,
6_5_0,
6_0_0,
5_9_9,
5_0_0,
4_9_9,
4_0_0,
3_9_9,
3_5_0,
3_0_0,
2_9_9,
2_6_6,
2_3_3,
2_0_0,
1_9_9,
1_7_9,
1_5_9,
1_4_0,
1_2_0,
1_0_0,
9_9,
8_8,
7_7,
6_6,
5_5,
4_4,
3_3,
2_2,
1_1,
0,
]
snake_case_ = [
9_9_9,
9_9_5,
9_9_2,
9_8_9,
9_8_5,
9_8_1,
9_7_8,
9_7_5,
9_7_1,
9_6_7,
9_6_4,
9_6_1,
9_5_7,
9_5_6,
9_5_1,
9_4_7,
9_4_2,
9_3_7,
9_3_3,
9_2_8,
9_2_3,
9_1_9,
9_1_4,
9_1_3,
9_0_8,
9_0_3,
8_9_7,
8_9_2,
8_8_7,
8_8_1,
8_7_6,
8_7_1,
8_7_0,
8_6_4,
8_5_8,
8_5_2,
8_4_6,
8_4_0,
8_3_4,
8_2_8,
8_2_7,
8_2_0,
8_1_3,
8_0_6,
7_9_9,
7_9_2,
7_8_5,
7_8_4,
7_7_7,
7_7_0,
7_6_3,
7_5_6,
7_4_9,
7_4_2,
7_4_1,
7_3_3,
7_2_4,
7_1_6,
7_0_7,
6_9_9,
6_9_8,
6_8_8,
6_7_7,
6_6_6,
6_5_6,
6_5_5,
6_4_5,
6_3_4,
6_2_3,
6_1_3,
6_1_2,
5_9_8,
5_8_4,
5_7_0,
5_6_9,
5_5_5,
5_4_1,
5_2_7,
5_2_6,
5_0_5,
4_8_4,
4_8_3,
4_6_2,
4_4_0,
4_3_9,
3_9_6,
3_9_5,
3_5_2,
3_5_1,
3_0_8,
3_0_7,
2_6_4,
2_6_3,
2_2_0,
2_1_9,
1_7_6,
1_3_2,
8_8,
4_4,
0,
]
snake_case_ = [
9_9_9,
9_9_7,
9_9_5,
9_9_2,
9_9_0,
9_8_8,
9_8_6,
9_8_4,
9_8_1,
9_7_9,
9_7_7,
9_7_5,
9_7_2,
9_7_0,
9_6_8,
9_6_6,
9_6_4,
9_6_1,
9_5_9,
9_5_7,
9_5_6,
9_5_4,
9_5_1,
9_4_9,
9_4_6,
9_4_4,
9_4_1,
9_3_9,
9_3_6,
9_3_4,
9_3_1,
9_2_9,
9_2_6,
9_2_4,
9_2_1,
9_1_9,
9_1_6,
9_1_4,
9_1_3,
9_1_0,
9_0_7,
9_0_5,
9_0_2,
8_9_9,
8_9_6,
8_9_3,
8_9_1,
8_8_8,
8_8_5,
8_8_2,
8_7_9,
8_7_7,
8_7_4,
8_7_1,
8_7_0,
8_6_7,
8_6_4,
8_6_1,
8_5_8,
8_5_5,
8_5_2,
8_4_9,
8_4_6,
8_4_3,
8_4_0,
8_3_7,
8_3_4,
8_3_1,
8_2_8,
8_2_7,
8_2_4,
8_2_1,
8_1_7,
8_1_4,
8_1_1,
8_0_8,
8_0_4,
8_0_1,
7_9_8,
7_9_5,
7_9_1,
7_8_8,
7_8_5,
7_8_4,
7_8_0,
7_7_7,
7_7_4,
7_7_0,
7_6_6,
7_6_3,
7_6_0,
7_5_6,
7_5_2,
7_4_9,
7_4_6,
7_4_2,
7_4_1,
7_3_7,
7_3_3,
7_3_0,
7_2_6,
7_2_2,
7_1_8,
7_1_4,
7_1_0,
7_0_7,
7_0_3,
6_9_9,
6_9_8,
6_9_4,
6_9_0,
6_8_5,
6_8_1,
6_7_7,
6_7_3,
6_6_9,
6_6_4,
6_6_0,
6_5_6,
6_5_5,
6_5_0,
6_4_6,
6_4_1,
6_3_6,
6_3_2,
6_2_7,
6_2_2,
6_1_8,
6_1_3,
6_1_2,
6_0_7,
6_0_2,
5_9_6,
5_9_1,
5_8_6,
5_8_0,
5_7_5,
5_7_0,
5_6_9,
5_6_3,
5_5_7,
5_5_1,
5_4_5,
5_3_9,
5_3_3,
5_2_7,
5_2_6,
5_1_9,
5_1_2,
5_0_5,
4_9_8,
4_9_1,
4_8_4,
4_8_3,
4_7_4,
4_6_6,
4_5_7,
4_4_9,
4_4_0,
4_3_9,
4_2_8,
4_1_8,
4_0_7,
3_9_6,
3_9_5,
3_8_1,
3_6_6,
3_5_2,
3_5_1,
3_3_0,
3_0_8,
3_0_7,
2_8_6,
2_6_4,
2_6_3,
2_4_2,
2_2_0,
2_1_9,
1_7_6,
1_7_5,
1_3_2,
1_3_1,
8_8,
4_4,
0,
]
snake_case_ = [
9_9_9,
9_9_1,
9_8_2,
9_7_4,
9_6_6,
9_5_8,
9_5_0,
9_4_1,
9_3_3,
9_2_5,
9_1_6,
9_0_8,
9_0_0,
8_9_9,
8_7_4,
8_5_0,
8_2_5,
8_0_0,
7_9_9,
7_0_0,
6_0_0,
5_0_0,
4_0_0,
3_0_0,
2_0_0,
1_0_0,
0,
]
snake_case_ = [
9_9_9,
9_9_2,
9_8_5,
9_7_8,
9_7_1,
9_6_4,
9_5_7,
9_4_9,
9_4_2,
9_3_5,
9_2_8,
9_2_1,
9_1_4,
9_0_7,
9_0_0,
8_9_9,
8_7_9,
8_5_9,
8_4_0,
8_2_0,
8_0_0,
7_9_9,
7_6_6,
7_3_3,
7_0_0,
6_9_9,
6_5_0,
6_0_0,
5_9_9,
5_0_0,
4_9_9,
4_0_0,
3_9_9,
3_0_0,
2_9_9,
2_0_0,
1_9_9,
1_0_0,
9_9,
0,
]
snake_case_ = [
9_9_9,
9_9_6,
9_9_2,
9_8_9,
9_8_5,
9_8_2,
9_7_9,
9_7_5,
9_7_2,
9_6_8,
9_6_5,
9_6_1,
9_5_8,
9_5_5,
9_5_1,
9_4_8,
9_4_4,
9_4_1,
9_3_8,
9_3_4,
9_3_1,
9_2_7,
9_2_4,
9_2_0,
9_1_7,
9_1_4,
9_1_0,
9_0_7,
9_0_3,
9_0_0,
8_9_9,
8_9_1,
8_8_4,
8_7_6,
8_6_9,
8_6_1,
8_5_3,
8_4_6,
8_3_8,
8_3_0,
8_2_3,
8_1_5,
8_0_8,
8_0_0,
7_9_9,
7_8_8,
7_7_7,
7_6_6,
7_5_5,
7_4_4,
7_3_3,
7_2_2,
7_1_1,
7_0_0,
6_9_9,
6_8_8,
6_7_7,
6_6_6,
6_5_5,
6_4_4,
6_3_3,
6_2_2,
6_1_1,
6_0_0,
5_9_9,
5_8_5,
5_7_1,
5_5_7,
5_4_2,
5_2_8,
5_1_4,
5_0_0,
4_9_9,
4_8_5,
4_7_1,
4_5_7,
4_4_2,
4_2_8,
4_1_4,
4_0_0,
3_9_9,
3_7_9,
3_5_9,
3_4_0,
3_2_0,
3_0_0,
2_9_9,
2_7_9,
2_5_9,
2_4_0,
2_2_0,
2_0_0,
1_9_9,
1_6_6,
1_3_3,
1_0_0,
9_9,
6_6,
3_3,
0,
]
| 421
| 0
|
'''simple docstring'''
import gc
import unittest
from diffusers import FlaxStableDiffusionInpaintPipeline
from diffusers.utils import is_flax_available, load_image, slow
from diffusers.utils.testing_utils import require_flax
if is_flax_available():
import jax
import jax.numpy as jnp
from flax.jax_utils import replicate
from flax.training.common_utils import shard
@slow
@require_flax
class UpperCamelCase__ ( unittest.TestCase ):
"""simple docstring"""
def _UpperCamelCase ( self ) -> int:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
def _UpperCamelCase ( self ) -> Any:
SCREAMING_SNAKE_CASE_ = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/sd2-inpaint/init_image.png''' )
SCREAMING_SNAKE_CASE_ = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' )
SCREAMING_SNAKE_CASE_ = 'xvjiarui/stable-diffusion-2-inpainting'
SCREAMING_SNAKE_CASE_ = FlaxStableDiffusionInpaintPipeline.from_pretrained(_lowercase , safety_checker=_lowercase )
SCREAMING_SNAKE_CASE_ = 'Face of a yellow cat, high resolution, sitting on a park bench'
SCREAMING_SNAKE_CASE_ = jax.random.PRNGKey(0 )
SCREAMING_SNAKE_CASE_ = 50
SCREAMING_SNAKE_CASE_ = jax.device_count()
SCREAMING_SNAKE_CASE_ = num_samples * [prompt]
SCREAMING_SNAKE_CASE_ = num_samples * [init_image]
SCREAMING_SNAKE_CASE_ = num_samples * [mask_image]
SCREAMING_SNAKE_CASE_ = pipeline.prepare_inputs(_lowercase , _lowercase , _lowercase )
# shard inputs and rng
SCREAMING_SNAKE_CASE_ = replicate(_lowercase )
SCREAMING_SNAKE_CASE_ = jax.random.split(_lowercase , jax.device_count() )
SCREAMING_SNAKE_CASE_ = shard(_lowercase )
SCREAMING_SNAKE_CASE_ = shard(_lowercase )
SCREAMING_SNAKE_CASE_ = shard(_lowercase )
SCREAMING_SNAKE_CASE_ = pipeline(
_lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , jit=_lowercase )
SCREAMING_SNAKE_CASE_ = output.images.reshape(_lowercase , 512 , 512 , 3 )
SCREAMING_SNAKE_CASE_ = images[0, 253:256, 253:256, -1]
SCREAMING_SNAKE_CASE_ = jnp.asarray(jax.device_get(image_slice.flatten() ) )
SCREAMING_SNAKE_CASE_ = jnp.array(
[0.361_1307, 0.3764_9736, 0.375_7408, 0.3821_3953, 0.3929_5167, 0.384_1631, 0.4155_4978, 0.413_7475, 0.421_7084] )
print(F'''output_slice: {output_slice}''' )
assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
| 707
|
from __future__ import annotations
import collections
import tempfile
import unittest
import numpy as np
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import is_tf_available, is_vision_available
from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_tf_bert import TFBertModelTester
from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester
from ..deit.test_modeling_tf_deit import TFDeiTModelTester
from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester
from ..vit.test_modeling_tf_vit import TFViTModelTester
if is_tf_available():
from transformers import (
TFBertModel,
TFCLIPVisionModel,
TFDeiTModel,
TFRobertaModel,
TFVisionTextDualEncoderModel,
TFViTModel,
VisionTextDualEncoderConfig,
)
if is_vision_available():
from PIL import Image
from transformers import VisionTextDualEncoderProcessor
def A__ ( __lowerCamelCase ):
if isinstance(__lowerCamelCase, collections.abc.Iterable ):
return x
return (x, x)
@require_tf
class UpperCamelCase__ :
"""simple docstring"""
def _UpperCamelCase ( self , _A , _A ) -> Optional[Any]:
pass
def _UpperCamelCase ( self ) -> Any:
pass
def _UpperCamelCase ( self ) -> str:
pass
def _UpperCamelCase ( self , _A , _A , _A , _A , _A=None , **_A ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE_ = VisionTextDualEncoderConfig.from_vision_text_configs(_A , _A )
SCREAMING_SNAKE_CASE_ = TFVisionTextDualEncoderModel(_A )
SCREAMING_SNAKE_CASE_ = model(input_ids=_A , pixel_values=_A , attention_mask=_A )
self.assertEqual(output['''text_embeds'''].shape , (input_ids.shape[0], config.projection_dim) )
self.assertEqual(output['''image_embeds'''].shape , (pixel_values.shape[0], config.projection_dim) )
def _UpperCamelCase ( self , _A , _A , _A , _A , _A=None , **_A ) -> Tuple:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.get_vision_text_model(_A , _A )
SCREAMING_SNAKE_CASE_ = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A )
SCREAMING_SNAKE_CASE_ = model(input_ids=_A , pixel_values=_A , attention_mask=_A )
self.assertEqual(output['''text_embeds'''].shape , (input_ids.shape[0], model.config.projection_dim) )
self.assertEqual(output['''image_embeds'''].shape , (pixel_values.shape[0], model.config.projection_dim) )
def _UpperCamelCase ( self , _A , _A , _A , _A , _A=None , **_A ) -> List[Any]:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.get_vision_text_model(_A , _A )
SCREAMING_SNAKE_CASE_ = {'''vision_model''': vision_model, '''text_model''': text_model}
SCREAMING_SNAKE_CASE_ = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**_A )
SCREAMING_SNAKE_CASE_ = model(input_ids=_A , pixel_values=_A , attention_mask=_A )
self.assertEqual(output['''text_embeds'''].shape , (input_ids.shape[0], model.config.projection_dim) )
self.assertEqual(output['''image_embeds'''].shape , (pixel_values.shape[0], model.config.projection_dim) )
def _UpperCamelCase ( self , _A , _A , _A , _A , _A=None , **_A ) -> str:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.get_vision_text_model(_A , _A )
SCREAMING_SNAKE_CASE_ = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A )
SCREAMING_SNAKE_CASE_ = model(input_ids=_A , pixel_values=_A , attention_mask=_A )
SCREAMING_SNAKE_CASE_ = output[0].numpy()
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(_A )
SCREAMING_SNAKE_CASE_ = TFVisionTextDualEncoderModel.from_pretrained(_A )
SCREAMING_SNAKE_CASE_ = model(input_ids=_A , pixel_values=_A , attention_mask=_A )
SCREAMING_SNAKE_CASE_ = after_output[0].numpy()
SCREAMING_SNAKE_CASE_ = np.amax(np.abs(out_a - out_a ) )
self.assertLessEqual(_A , 1E-5 )
def _UpperCamelCase ( self , _A , _A , _A , _A , _A=None , **_A ) -> Optional[Any]:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.get_vision_text_model(_A , _A )
SCREAMING_SNAKE_CASE_ = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A )
SCREAMING_SNAKE_CASE_ = model(
input_ids=_A , pixel_values=_A , attention_mask=_A , output_attentions=_A )
SCREAMING_SNAKE_CASE_ = output.vision_model_output.attentions
self.assertEqual(len(_A ) , vision_config.num_hidden_layers )
# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
SCREAMING_SNAKE_CASE_ = to_atuple(vision_model.config.image_size )
SCREAMING_SNAKE_CASE_ = to_atuple(vision_model.config.patch_size )
SCREAMING_SNAKE_CASE_ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
SCREAMING_SNAKE_CASE_ = num_patches + 1
self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) )
SCREAMING_SNAKE_CASE_ = output.text_model_output.attentions
self.assertEqual(len(_A ) , text_config.num_hidden_layers )
self.assertEqual(
text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , )
def _UpperCamelCase ( self , _A , _A , _A ) -> Optional[Any]:
SCREAMING_SNAKE_CASE_ = np.abs((a - b) ).max()
self.assertLessEqual(_A , _A , F'''Difference between torch and flax is {diff} (>= {tol}).''' )
def _UpperCamelCase ( self ) -> Optional[Any]:
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
self.check_vision_text_dual_encoder_model(**_A )
def _UpperCamelCase ( self ) -> List[Any]:
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
self.check_model_from_pretrained_configs(**_A )
def _UpperCamelCase ( self ) -> Tuple:
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
self.check_vision_text_dual_encoder_from_pretrained(**_A )
def _UpperCamelCase ( self ) -> List[Any]:
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
self.check_save_load(**_A )
def _UpperCamelCase ( self ) -> Any:
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
self.check_vision_text_output_attention(**_A )
@slow
def _UpperCamelCase ( self ) -> List[str]:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.get_pretrained_model_and_inputs()
SCREAMING_SNAKE_CASE_ = model_a(**_A )
SCREAMING_SNAKE_CASE_ = outputs[0].numpy()
with tempfile.TemporaryDirectory() as tmp_dirname:
model_a.save_pretrained(_A )
SCREAMING_SNAKE_CASE_ = TFVisionTextDualEncoderModel.from_pretrained(_A )
SCREAMING_SNAKE_CASE_ = model_a(**_A )
SCREAMING_SNAKE_CASE_ = after_outputs[0].numpy()
SCREAMING_SNAKE_CASE_ = np.amax(np.abs(out_a - out_a ) )
self.assertLessEqual(_A , 1E-5 )
@require_tf
class UpperCamelCase__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
"""simple docstring"""
def _UpperCamelCase ( self ) -> Optional[Any]:
SCREAMING_SNAKE_CASE_ = TFVisionTextDualEncoderModel.from_vision_text_pretrained(
'''hf-internal-testing/tiny-random-vit''' , '''hf-internal-testing/tiny-random-bert''' )
SCREAMING_SNAKE_CASE_ = 13
SCREAMING_SNAKE_CASE_ = floats_tensor(
[
batch_size,
model.vision_model.config.num_channels,
model.vision_model.config.image_size,
model.vision_model.config.image_size,
] )
SCREAMING_SNAKE_CASE_ = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size )
SCREAMING_SNAKE_CASE_ = random_attention_mask([batch_size, 4] )
SCREAMING_SNAKE_CASE_ = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}
return model, inputs
def _UpperCamelCase ( self , _A , _A ) -> List[Any]:
SCREAMING_SNAKE_CASE_ = TFViTModel(_A , name='''vision_model''' )
SCREAMING_SNAKE_CASE_ = TFBertModel(_A , name='''text_model''' )
return vision_model, text_model
def _UpperCamelCase ( self ) -> List[Any]:
SCREAMING_SNAKE_CASE_ = TFViTModelTester(self )
SCREAMING_SNAKE_CASE_ = TFBertModelTester(self )
SCREAMING_SNAKE_CASE_ = vit_model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE_ = bert_model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = vision_config_and_inputs
(
(
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) ,
) = text_config_and_inputs
return {
"text_config": text_config,
"vision_config": vision_config,
"pixel_values": pixel_values,
"attention_mask": input_mask,
"input_ids": input_ids,
"text_token_type_ids": token_type_ids,
"text_sequence_labels": sequence_labels,
"text_token_labels": token_labels,
"text_choice_labels": choice_labels,
}
@require_tf
class UpperCamelCase__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
"""simple docstring"""
def _UpperCamelCase ( self ) -> Union[str, Any]:
# DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's
# just reinitialize it.
SCREAMING_SNAKE_CASE_ = TFVisionTextDualEncoderModel.from_vision_text_pretrained(
'''Rocketknight1/tiny-random-deit-tf''' , '''hf-internal-testing/tiny-random-roberta''' )
SCREAMING_SNAKE_CASE_ = 13
SCREAMING_SNAKE_CASE_ = floats_tensor(
[
batch_size,
model.vision_model.config.num_channels,
model.vision_model.config.image_size,
model.vision_model.config.image_size,
] )
SCREAMING_SNAKE_CASE_ = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size )
SCREAMING_SNAKE_CASE_ = random_attention_mask([batch_size, 4] )
SCREAMING_SNAKE_CASE_ = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}
return model, inputs
def _UpperCamelCase ( self , _A , _A , _A , _A , _A=None , **_A ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.get_vision_text_model(_A , _A )
SCREAMING_SNAKE_CASE_ = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A )
SCREAMING_SNAKE_CASE_ = model(
input_ids=_A , pixel_values=_A , attention_mask=_A , output_attentions=_A )
SCREAMING_SNAKE_CASE_ = output.vision_model_output.attentions
self.assertEqual(len(_A ) , vision_config.num_hidden_layers )
# in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
SCREAMING_SNAKE_CASE_ = to_atuple(vision_model.config.image_size )
SCREAMING_SNAKE_CASE_ = to_atuple(vision_model.config.patch_size )
SCREAMING_SNAKE_CASE_ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
SCREAMING_SNAKE_CASE_ = num_patches + 2
self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) )
SCREAMING_SNAKE_CASE_ = output.text_model_output.attentions
self.assertEqual(len(_A ) , text_config.num_hidden_layers )
self.assertEqual(
text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , )
def _UpperCamelCase ( self , _A , _A ) -> Dict:
SCREAMING_SNAKE_CASE_ = TFDeiTModel(_A , name='''vision_model''' )
SCREAMING_SNAKE_CASE_ = TFRobertaModel(_A , name='''text_model''' )
return vision_model, text_model
def _UpperCamelCase ( self ) -> Optional[int]:
SCREAMING_SNAKE_CASE_ = TFDeiTModelTester(self )
SCREAMING_SNAKE_CASE_ = TFRobertaModelTester(self )
SCREAMING_SNAKE_CASE_ = vit_model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE_ = bert_model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = vision_config_and_inputs
(
(
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) ,
) = text_config_and_inputs
return {
"text_config": text_config,
"vision_config": vision_config,
"pixel_values": pixel_values,
"attention_mask": input_mask,
"input_ids": input_ids,
"text_token_type_ids": token_type_ids,
"text_sequence_labels": sequence_labels,
"text_token_labels": token_labels,
"text_choice_labels": choice_labels,
}
@require_tf
class UpperCamelCase__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
"""simple docstring"""
def _UpperCamelCase ( self ) -> Optional[int]:
SCREAMING_SNAKE_CASE_ = TFVisionTextDualEncoderModel.from_vision_text_pretrained(
'''Rocketknight1/tiny-random-clip-tf''' , '''hf-internal-testing/tiny-random-bert''' )
SCREAMING_SNAKE_CASE_ = 13
SCREAMING_SNAKE_CASE_ = floats_tensor(
[
batch_size,
model.vision_model.config.num_channels,
model.vision_model.config.image_size,
model.vision_model.config.image_size,
] )
SCREAMING_SNAKE_CASE_ = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size )
SCREAMING_SNAKE_CASE_ = random_attention_mask([batch_size, 4] )
SCREAMING_SNAKE_CASE_ = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}
return model, inputs
def _UpperCamelCase ( self , _A , _A ) -> int:
SCREAMING_SNAKE_CASE_ = TFCLIPVisionModel(_A , name='''vision_model''' )
SCREAMING_SNAKE_CASE_ = TFBertModel(_A , name='''text_model''' )
return vision_model, text_model
def _UpperCamelCase ( self ) -> int:
SCREAMING_SNAKE_CASE_ = TFCLIPVisionModelTester(self )
SCREAMING_SNAKE_CASE_ = TFBertModelTester(self )
SCREAMING_SNAKE_CASE_ = clip_model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE_ = bert_model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = vision_config_and_inputs
(
(
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) ,
) = text_config_and_inputs
return {
"text_config": text_config,
"vision_config": vision_config,
"pixel_values": pixel_values,
"attention_mask": input_mask,
"input_ids": input_ids,
"text_token_type_ids": token_type_ids,
"text_sequence_labels": sequence_labels,
"text_token_labels": token_labels,
"text_choice_labels": choice_labels,
}
@require_vision
@require_tf
class UpperCamelCase__ ( unittest.TestCase ):
"""simple docstring"""
@slow
def _UpperCamelCase ( self ) -> int:
SCREAMING_SNAKE_CASE_ = TFVisionTextDualEncoderModel.from_pretrained(
'''clip-italian/clip-italian''' , logit_scale_init_value=1.0 , from_pt=_A )
SCREAMING_SNAKE_CASE_ = VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian''' )
SCREAMING_SNAKE_CASE_ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
SCREAMING_SNAKE_CASE_ = processor(
text=['''una foto di un gatto''', '''una foto di un cane'''] , images=_A , padding=_A , return_tensors='''np''' )
SCREAMING_SNAKE_CASE_ = model(**_A )
# verify the logits
self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) )
self.assertEqual(
outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , )
SCREAMING_SNAKE_CASE_ = np.array([[1.228_4727, 0.310_4122]] )
self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , _A , atol=1E-3 ) )
| 597
| 0
|
'''simple docstring'''
import argparse
import logging
import os
import sys
import numpy as np
import onnxruntime
import torch
from bart_onnx.generation_onnx import BARTBeamSearchGenerator
from bart_onnx.reduce_onnx_size import remove_dup_initializers
import transformers
from transformers import BartForConditionalGeneration, BartTokenizer
logging.basicConfig(
format='%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=os.environ.get('LOGLEVEL', 'INFO').upper(),
stream=sys.stdout,
)
a : Optional[int] = logging.getLogger(__name__)
a : Tuple = {'facebook/bart-base': BartForConditionalGeneration}
a : Any = {'facebook/bart-base': BartTokenizer}
def __magic_name__ ( ) -> Dict:
'''simple docstring'''
snake_case_ = argparse.ArgumentParser(description='''Export Bart model + Beam Search to ONNX graph.''' )
parser.add_argument(
'''--validation_file''', type=__UpperCAmelCase, default=__UpperCAmelCase, help='''A csv or a json file containing the validation data.''' )
parser.add_argument(
'''--max_length''', type=__UpperCAmelCase, default=5, help='''The maximum total input sequence length after tokenization.''', )
parser.add_argument(
'''--num_beams''', type=__UpperCAmelCase, default=__UpperCAmelCase, help=(
'''Number of beams to use for evaluation. This argument will be '''
'''passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.'''
), )
parser.add_argument(
'''--model_name_or_path''', type=__UpperCAmelCase, help='''Path to pretrained model or model identifier from huggingface.co/models.''', required=__UpperCAmelCase, )
parser.add_argument(
'''--config_name''', type=__UpperCAmelCase, default=__UpperCAmelCase, help='''Pretrained config name or path if not the same as model_name''', )
parser.add_argument(
'''--device''', type=__UpperCAmelCase, default='''cpu''', help='''Device where the model will be run''', )
parser.add_argument('''--output_file_path''', type=__UpperCAmelCase, default=__UpperCAmelCase, help='''Where to store the final ONNX file.''' )
snake_case_ = parser.parse_args()
return args
def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase="cpu" ) -> Union[str, Any]:
'''simple docstring'''
snake_case_ = model_dict[model_name].from_pretrained(__UpperCAmelCase ).to(__UpperCAmelCase )
snake_case_ = tokenizer_dict[model_name].from_pretrained(__UpperCAmelCase )
if model_name in ["facebook/bart-base"]:
snake_case_ = 0
snake_case_ = None
snake_case_ = 0
return huggingface_model, tokenizer
def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) -> Dict:
'''simple docstring'''
model.eval()
snake_case_ = None
snake_case_ = torch.jit.script(BARTBeamSearchGenerator(__UpperCAmelCase ) )
with torch.no_grad():
snake_case_ = '''My friends are cool but they eat too many carbs.'''
snake_case_ = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors='''pt''' ).to(model.device )
snake_case_ = model.generate(
inputs['''input_ids'''], attention_mask=inputs['''attention_mask'''], num_beams=__UpperCAmelCase, max_length=__UpperCAmelCase, early_stopping=__UpperCAmelCase, decoder_start_token_id=model.config.decoder_start_token_id, )
torch.onnx.export(
__UpperCAmelCase, (
inputs['''input_ids'''],
inputs['''attention_mask'''],
num_beams,
max_length,
model.config.decoder_start_token_id,
), __UpperCAmelCase, opset_version=14, input_names=['''input_ids''', '''attention_mask''', '''num_beams''', '''max_length''', '''decoder_start_token_id'''], output_names=['''output_ids'''], dynamic_axes={
'''input_ids''': {0: '''batch''', 1: '''seq'''},
'''output_ids''': {0: '''batch''', 1: '''seq_out'''},
}, example_outputs=__UpperCAmelCase, )
logger.info('''Model exported to {}'''.format(__UpperCAmelCase ) )
snake_case_ = remove_dup_initializers(os.path.abspath(__UpperCAmelCase ) )
logger.info('''Deduplicated and optimized model written to {}'''.format(__UpperCAmelCase ) )
snake_case_ = onnxruntime.InferenceSession(__UpperCAmelCase )
snake_case_ = ort_sess.run(
__UpperCAmelCase, {
'''input_ids''': inputs['''input_ids'''].cpu().numpy(),
'''attention_mask''': inputs['''attention_mask'''].cpu().numpy(),
'''num_beams''': np.array(__UpperCAmelCase ),
'''max_length''': np.array(__UpperCAmelCase ),
'''decoder_start_token_id''': np.array(model.config.decoder_start_token_id ),
}, )
np.testing.assert_allclose(summary_ids.cpu().numpy(), ort_out[0], rtol=1e-3, atol=1e-3 )
logger.info('''Model outputs from torch and ONNX Runtime are similar.''' )
logger.info('''Success.''' )
def __magic_name__ ( ) -> List[str]:
'''simple docstring'''
snake_case_ = parse_args()
snake_case_ = 5
snake_case_ = 4
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, )
logger.setLevel(logging.INFO )
transformers.utils.logging.set_verbosity_error()
snake_case_ = torch.device(args.device )
snake_case_ ,snake_case_ = load_model_tokenizer(args.model_name_or_path, __UpperCAmelCase )
if model.config.decoder_start_token_id is None:
raise ValueError('''Make sure that `config.decoder_start_token_id` is correctly defined''' )
model.to(__UpperCAmelCase )
if args.max_length:
snake_case_ = args.max_length
if args.num_beams:
snake_case_ = args.num_beams
if args.output_file_path:
snake_case_ = args.output_file_path
else:
snake_case_ = '''BART.onnx'''
logger.info('''Exporting model to ONNX''' )
export_and_validate_model(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase )
if __name__ == "__main__":
main()
| 640
|
'''simple docstring'''
import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
from accelerate.local_sgd import LocalSGD
########################################################################
# This is a fully working simple example to use Accelerate
# with LocalSGD, which is a method to synchronize model
# parameters every K batches. It is different, but complementary
# to gradient accumulation.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
# - single CPU or single GPU
# - multi GPUS (using PyTorch distributed mode)
# - (multi) TPUs
# - fp16 (mixed-precision) or fp32 (normal precision)
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################
a : str = 16
a : Union[str, Any] = 32
def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase = 16 ) -> Union[str, Any]:
'''simple docstring'''
snake_case_ = AutoTokenizer.from_pretrained('''bert-base-cased''' )
snake_case_ = load_dataset('''glue''', '''mrpc''' )
def tokenize_function(__UpperCAmelCase ):
# max_length=None => use the model max length (it's actually the default)
snake_case_ = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=__UpperCAmelCase, max_length=__UpperCAmelCase )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
snake_case_ = datasets.map(
__UpperCAmelCase, batched=__UpperCAmelCase, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
snake_case_ = tokenized_datasets.rename_column('''label''', '''labels''' )
def collate_fn(__UpperCAmelCase ):
# On TPU it's best to pad everything to the same length or training will be very slow.
snake_case_ = 128 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
snake_case_ = 16
elif accelerator.mixed_precision != "no":
snake_case_ = 8
else:
snake_case_ = None
return tokenizer.pad(
__UpperCAmelCase, padding='''longest''', max_length=__UpperCAmelCase, pad_to_multiple_of=__UpperCAmelCase, return_tensors='''pt''', )
# Instantiate dataloaders.
snake_case_ = DataLoader(
tokenized_datasets['''train'''], shuffle=__UpperCAmelCase, collate_fn=__UpperCAmelCase, batch_size=__UpperCAmelCase )
snake_case_ = DataLoader(
tokenized_datasets['''validation'''], shuffle=__UpperCAmelCase, collate_fn=__UpperCAmelCase, batch_size=__UpperCAmelCase )
return train_dataloader, eval_dataloader
# For testing only
if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
a : Optional[Any] = mocked_dataloaders # noqa: F811
def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> Optional[Any]:
'''simple docstring'''
if os.environ.get('''TESTING_MOCKED_DATALOADERS''', __UpperCAmelCase ) == "1":
snake_case_ = 2
# New Code #
snake_case_ = int(args.gradient_accumulation_steps )
snake_case_ = int(args.local_sgd_steps )
# Initialize accelerator
snake_case_ = Accelerator(
cpu=args.cpu, mixed_precision=args.mixed_precision, gradient_accumulation_steps=__UpperCAmelCase )
if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]:
raise NotImplementedError('''LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)''' )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
snake_case_ = config['''lr''']
snake_case_ = int(config['''num_epochs'''] )
snake_case_ = int(config['''seed'''] )
snake_case_ = int(config['''batch_size'''] )
snake_case_ = evaluate.load('''glue''', '''mrpc''' )
set_seed(__UpperCAmelCase )
snake_case_ ,snake_case_ = get_dataloaders(__UpperCAmelCase, __UpperCAmelCase )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
snake_case_ = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''', return_dict=__UpperCAmelCase )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
snake_case_ = model.to(accelerator.device )
# Instantiate optimizer
snake_case_ = AdamW(params=model.parameters(), lr=__UpperCAmelCase )
# Instantiate scheduler
snake_case_ = get_linear_schedule_with_warmup(
optimizer=__UpperCAmelCase, num_warmup_steps=100, num_training_steps=(len(__UpperCAmelCase ) * num_epochs), )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ = accelerator.prepare(
__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase )
# Now we train the model
for epoch in range(__UpperCAmelCase ):
model.train()
with LocalSGD(
accelerator=__UpperCAmelCase, model=__UpperCAmelCase, local_sgd_steps=__UpperCAmelCase, enabled=local_sgd_steps is not None ) as local_sgd:
for step, batch in enumerate(__UpperCAmelCase ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
# New code #
# We use the new `accumulate` context manager to perform gradient accumulation
# We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests.
with accelerator.accumulate(__UpperCAmelCase ):
snake_case_ = model(**__UpperCAmelCase )
snake_case_ = output.loss
accelerator.backward(__UpperCAmelCase )
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
# LocalSGD-specific line
local_sgd.step()
model.eval()
for step, batch in enumerate(__UpperCAmelCase ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
snake_case_ = model(**__UpperCAmelCase )
snake_case_ = outputs.logits.argmax(dim=-1 )
snake_case_ ,snake_case_ = accelerator.gather_for_metrics((predictions, batch['''labels''']) )
metric.add_batch(
predictions=__UpperCAmelCase, references=__UpperCAmelCase, )
snake_case_ = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(F"epoch {epoch}:", __UpperCAmelCase )
def __magic_name__ ( ) -> str:
'''simple docstring'''
snake_case_ = argparse.ArgumentParser(description='''Simple example of training script.''' )
parser.add_argument(
'''--mixed_precision''', type=__UpperCAmelCase, default=__UpperCAmelCase, choices=['''no''', '''fp16''', '''bf16''', '''fp8'''], help='''Whether to use mixed precision. Choose'''
'''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'''
'''and an Nvidia Ampere GPU.''', )
# New Code #
parser.add_argument(
'''--gradient_accumulation_steps''', type=__UpperCAmelCase, default=1, help='''The number of minibatches to be ran before gradients are accumulated.''', )
parser.add_argument(
'''--local_sgd_steps''', type=__UpperCAmelCase, default=8, help='''Number of local SGD steps or None to disable local SGD''' )
parser.add_argument('''--cpu''', action='''store_true''', help='''If passed, will train on the CPU.''' )
snake_case_ = parser.parse_args()
snake_case_ = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
training_function(__UpperCAmelCase, __UpperCAmelCase )
if __name__ == "__main__":
main()
| 640
| 1
|
import re
from typing import Callable, List, Optional, Union
import tensorflow as tf
try:
from tensorflow.keras.optimizers.legacy import Adam
except ImportError:
from tensorflow.keras.optimizers import Adam
class _a ( tf.keras.optimizers.schedules.LearningRateSchedule ):
'''simple docstring'''
def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 1.0 , __UpperCAmelCase = None , ):
super().__init__()
__A : Dict = initial_learning_rate
__A : int = warmup_steps
__A : Tuple = power
__A : List[Any] = decay_schedule_fn
__A : Union[str, Any] = name
def __call__( self , __UpperCAmelCase ):
with tf.name_scope(self.name or "WarmUp" ) as name:
# Implements polynomial warmup. i.e., if global_step < warmup_steps, the
# learning rate will be `global_step/num_warmup_steps * init_lr`.
__A : str = tf.cast(__UpperCAmelCase , tf.floataa )
__A : List[Any] = tf.cast(self.warmup_steps , tf.floataa )
__A : List[Any] = global_step_float / warmup_steps_float
__A : Optional[Any] = self.initial_learning_rate * tf.math.pow(__UpperCAmelCase , self.power )
return tf.cond(
global_step_float < warmup_steps_float , lambda: warmup_learning_rate , lambda: self.decay_schedule_fn(step - self.warmup_steps ) , name=__UpperCAmelCase , )
def __UpperCAmelCase( self ):
return {
"initial_learning_rate": self.initial_learning_rate,
"decay_schedule_fn": self.decay_schedule_fn,
"warmup_steps": self.warmup_steps,
"power": self.power,
"name": self.name,
}
def lowerCamelCase_ ( _lowercase , _lowercase , _lowercase , _lowercase = 0.0 , _lowercase = 0.9 , _lowercase = 0.9_99 , _lowercase = 1E-8 , _lowercase = None , _lowercase = None , _lowercase = 0.0 , _lowercase = 1.0 , _lowercase = None , ) -> Optional[int]:
__A : List[Any] = tf.keras.optimizers.schedules.PolynomialDecay(
initial_learning_rate=_lowercase , decay_steps=num_train_steps - num_warmup_steps , end_learning_rate=init_lr * min_lr_ratio , power=_lowercase , )
if num_warmup_steps:
__A : List[Any] = WarmUp(
initial_learning_rate=_lowercase , decay_schedule_fn=_lowercase , warmup_steps=_lowercase , )
if weight_decay_rate > 0.0:
__A : Tuple = AdamWeightDecay(
learning_rate=_lowercase , weight_decay_rate=_lowercase , beta_a=_lowercase , beta_a=_lowercase , epsilon=_lowercase , clipnorm=_lowercase , global_clipnorm=_lowercase , exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"] , include_in_weight_decay=_lowercase , )
else:
__A : Union[str, Any] = tf.keras.optimizers.Adam(
learning_rate=_lowercase , beta_a=_lowercase , beta_a=_lowercase , epsilon=_lowercase , clipnorm=_lowercase , global_clipnorm=_lowercase , )
# We return the optimizer and the LR scheduler in order to better track the
# evolution of the LR independently of the optimizer.
return optimizer, lr_schedule
class _a ( lowerCAmelCase__ ):
'''simple docstring'''
def __init__( self , __UpperCAmelCase = 0.0_01 , __UpperCAmelCase = 0.9 , __UpperCAmelCase = 0.9_99 , __UpperCAmelCase = 1e-7 , __UpperCAmelCase = False , __UpperCAmelCase = 0.0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = "AdamWeightDecay" , **__UpperCAmelCase , ):
super().__init__(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase )
__A : int = weight_decay_rate
__A : List[Any] = include_in_weight_decay
__A : Dict = exclude_from_weight_decay
@classmethod
def __UpperCAmelCase( cls , __UpperCAmelCase ):
__A : int = {"WarmUp": WarmUp}
return super(__UpperCAmelCase , cls ).from_config(__UpperCAmelCase , custom_objects=__UpperCAmelCase )
def __UpperCAmelCase( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ):
super(__UpperCAmelCase , self )._prepare_local(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
__A : Optional[int] = tf.constant(
self.weight_decay_rate , name="adam_weight_decay_rate" )
def __UpperCAmelCase( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ):
__A : Any = self._do_use_weight_decay(var.name )
if do_decay:
return var.assign_sub(
learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]["weight_decay_rate"] , use_locking=self._use_locking , )
return tf.no_op()
def __UpperCAmelCase( self , __UpperCAmelCase , __UpperCAmelCase=None , **__UpperCAmelCase ):
__A , __A : List[Any] = list(zip(*__UpperCAmelCase ) )
return super(__UpperCAmelCase , self ).apply_gradients(zip(__UpperCAmelCase , __UpperCAmelCase ) , name=__UpperCAmelCase , **__UpperCAmelCase )
def __UpperCAmelCase( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ):
if apply_state is None:
return self._decayed_lr_t[var_dtype], {}
__A : List[str] = apply_state or {}
__A : Tuple = apply_state.get((var_device, var_dtype) )
if coefficients is None:
__A : Optional[int] = self._fallback_apply_state(__UpperCAmelCase , __UpperCAmelCase )
__A : Tuple = coefficients
return coefficients["lr_t"], {"apply_state": apply_state}
def __UpperCAmelCase( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=None ):
__A , __A : str = self._get_lr(var.device , var.dtype.base_dtype , __UpperCAmelCase )
__A : Optional[int] = self._decay_weights_op(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
with tf.control_dependencies([decay] ):
return super(__UpperCAmelCase , self )._resource_apply_dense(__UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase )
def __UpperCAmelCase( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=None ):
__A , __A : str = self._get_lr(var.device , var.dtype.base_dtype , __UpperCAmelCase )
__A : int = self._decay_weights_op(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
with tf.control_dependencies([decay] ):
return super(__UpperCAmelCase , self )._resource_apply_sparse(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase )
def __UpperCAmelCase( self ):
__A : int = super().get_config()
config.update({"weight_decay_rate": self.weight_decay_rate} )
return config
def __UpperCAmelCase( self , __UpperCAmelCase ):
if self.weight_decay_rate == 0:
return False
if self._include_in_weight_decay:
for r in self._include_in_weight_decay:
if re.search(__UpperCAmelCase , __UpperCAmelCase ) is not None:
return True
if self._exclude_from_weight_decay:
for r in self._exclude_from_weight_decay:
if re.search(__UpperCAmelCase , __UpperCAmelCase ) is not None:
return False
return True
class _a ( lowerCAmelCase__ ):
'''simple docstring'''
def __init__( self ):
__A : List[Any] = []
__A : Union[str, Any] = None
@property
def __UpperCAmelCase( self ):
if self._accum_steps is None:
__A : Dict = tf.Variable(
tf.constant(0 , dtype=tf.intaa ) , trainable=__UpperCAmelCase , synchronization=tf.VariableSynchronization.ON_READ , aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA , )
return self._accum_steps.value()
@property
def __UpperCAmelCase( self ):
if not self._gradients:
raise ValueError("The accumulator should be called first to initialize the gradients" )
return [gradient.value() if gradient is not None else gradient for gradient in self._gradients]
def __call__( self , __UpperCAmelCase ):
if not self._gradients:
__A : int = self.step # Create the step variable.
self._gradients.extend(
[
tf.Variable(
tf.zeros_like(__UpperCAmelCase ) , trainable=__UpperCAmelCase , synchronization=tf.VariableSynchronization.ON_READ , aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA , )
if gradient is not None
else gradient
for gradient in gradients
] )
if len(__UpperCAmelCase ) != len(self._gradients ):
raise ValueError(F"Expected {len(self._gradients )} gradients, but got {len(__UpperCAmelCase )}" )
for accum_gradient, gradient in zip(self._gradients , __UpperCAmelCase ):
if accum_gradient is not None and gradient is not None:
accum_gradient.assign_add(__UpperCAmelCase )
self._accum_steps.assign_add(1 )
def __UpperCAmelCase( self ):
if not self._gradients:
return
self._accum_steps.assign(0 )
for gradient in self._gradients:
if gradient is not None:
gradient.assign(tf.zeros_like(__UpperCAmelCase ) )
| 387
|
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase = logging.get_logger(__name__)
UpperCamelCase = {
'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json',
# See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox
}
class _a ( lowerCAmelCase__ ):
'''simple docstring'''
lowerCamelCase_ : Union[str, Any] = """gpt_neox"""
def __init__( self , __UpperCAmelCase=50_432 , __UpperCAmelCase=6_144 , __UpperCAmelCase=44 , __UpperCAmelCase=64 , __UpperCAmelCase=24_576 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.25 , __UpperCAmelCase=10_000 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase=2_048 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1e-5 , __UpperCAmelCase=True , __UpperCAmelCase=0 , __UpperCAmelCase=2 , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=None , **__UpperCAmelCase , ):
super().__init__(bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase )
__A : Optional[int] = vocab_size
__A : List[Any] = max_position_embeddings
__A : Any = hidden_size
__A : str = num_hidden_layers
__A : List[str] = num_attention_heads
__A : Dict = intermediate_size
__A : List[Any] = hidden_act
__A : Tuple = rotary_pct
__A : Optional[int] = rotary_emb_base
__A : int = attention_dropout
__A : Optional[int] = hidden_dropout
__A : List[Any] = classifier_dropout
__A : Optional[Any] = initializer_range
__A : Optional[int] = layer_norm_eps
__A : str = use_cache
__A : Optional[int] = tie_word_embeddings
__A : Any = use_parallel_residual
__A : List[Any] = rope_scaling
self._rope_scaling_validation()
if self.hidden_size % self.num_attention_heads != 0:
raise ValueError(
"The hidden size is not divisble by the number of attention heads! Make sure to update them!" )
def __UpperCAmelCase( self ):
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , __UpperCAmelCase ) or len(self.rope_scaling ) != 2:
raise ValueError(
"`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
F"got {self.rope_scaling}" )
__A : Dict = self.rope_scaling.get("type" , __UpperCAmelCase )
__A : Dict = self.rope_scaling.get("factor" , __UpperCAmelCase )
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" )
if rope_scaling_factor is None or not isinstance(__UpperCAmelCase , __UpperCAmelCase ) or rope_scaling_factor <= 1.0:
raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}" )
| 387
| 1
|
"""simple docstring"""
import torch
from transformers import CamembertForMaskedLM, CamembertTokenizer
def __magic_name__ ( UpperCamelCase : List[str] , UpperCamelCase : str , UpperCamelCase : List[Any] , UpperCamelCase : List[str]=5 ) -> Optional[Any]:
assert masked_input.count('<mask>' ) == 1
a__ = torch.tensor(tokenizer.encode(__A , add_special_tokens=__A ) ).unsqueeze(0 ) # Batch size 1
a__ = model(__A )[0] # The last hidden-state is the first element of the output tuple
a__ = (input_ids.squeeze() == tokenizer.mask_token_id).nonzero().item()
a__ = logits[0, masked_index, :]
a__ = logits.softmax(dim=0 )
a__ = prob.topk(k=__A , dim=0 )
a__ = ' '.join(
[tokenizer.convert_ids_to_tokens(indices[i].item() ) for i in range(len(__A ) )] )
a__ = tokenizer.mask_token
a__ = []
for index, predicted_token_bpe in enumerate(topk_predicted_token_bpe.split(' ' ) ):
a__ = predicted_token_bpe.replace('\u2581' , ' ' )
if " {0}".format(__A ) in masked_input:
topk_filled_outputs.append(
(
masked_input.replace(' {0}'.format(__A ) , __A ),
values[index].item(),
predicted_token,
) )
else:
topk_filled_outputs.append(
(
masked_input.replace(__A , __A ),
values[index].item(),
predicted_token,
) )
return topk_filled_outputs
a : List[Any] = CamembertTokenizer.from_pretrained('camembert-base')
a : Optional[int] = CamembertForMaskedLM.from_pretrained('camembert-base')
model.eval()
a : Any = 'Le camembert est <mask> :)'
print(fill_mask(masked_input, model, tokenizer, topk=3))
| 273
|
'''simple docstring'''
from collections.abc import Iterator, MutableMapping
from dataclasses import dataclass
from typing import Generic, TypeVar
__UpperCAmelCase = TypeVar("KEY")
__UpperCAmelCase = TypeVar("VAL")
@dataclass(frozen=snake_case , slots=snake_case )
class SCREAMING_SNAKE_CASE ( Generic[KEY, VAL] ):
'''simple docstring'''
__UpperCamelCase = 42
__UpperCamelCase = 42
class SCREAMING_SNAKE_CASE ( _Item ):
'''simple docstring'''
def __init__( self ):
'''simple docstring'''
super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def __bool__( self ):
'''simple docstring'''
return False
__UpperCAmelCase = _DeletedItem()
class SCREAMING_SNAKE_CASE ( MutableMapping[KEY, VAL] ):
'''simple docstring'''
def __init__( self , SCREAMING_SNAKE_CASE__ = 8 , SCREAMING_SNAKE_CASE__ = 0.75 ):
'''simple docstring'''
snake_case: str = initial_block_size
snake_case: list[_Item | None] = [None] * initial_block_size
assert 0.0 < capacity_factor < 1.0
snake_case: List[Any] = capacity_factor
snake_case: int = 0
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
return hash(SCREAMING_SNAKE_CASE__ ) % len(self._buckets )
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
return (ind + 1) % len(self._buckets )
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
snake_case: Tuple = self._buckets[ind]
if not stored:
snake_case: Optional[Any] = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
self._len += 1
return True
elif stored.key == key:
snake_case: List[str] = _Item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
return True
else:
return False
def _UpperCamelCase ( self ):
'''simple docstring'''
snake_case: List[Any] = len(self._buckets ) * self._capacity_factor
return len(self ) >= int(SCREAMING_SNAKE_CASE__ )
def _UpperCamelCase ( self ):
'''simple docstring'''
if len(self._buckets ) <= self._initial_block_size:
return False
snake_case: Union[str, Any] = len(self._buckets ) * self._capacity_factor / 2
return len(self ) < limit
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
snake_case: Optional[Any] = self._buckets
snake_case: Optional[Any] = [None] * new_size
snake_case: Optional[Any] = 0
for item in old_buckets:
if item:
self._add_item(item.key , item.val )
def _UpperCamelCase ( self ):
'''simple docstring'''
self._resize(len(self._buckets ) * 2 )
def _UpperCamelCase ( self ):
'''simple docstring'''
self._resize(len(self._buckets ) // 2 )
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
snake_case: Tuple = self._get_bucket_index(SCREAMING_SNAKE_CASE__ )
for _ in range(len(self._buckets ) ):
yield ind
snake_case: int = self._get_next_ind(SCREAMING_SNAKE_CASE__ )
def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ):
if self._try_set(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
break
def __setitem__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
if self._is_full():
self._size_up()
self._add_item(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def __delitem__( self , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ):
snake_case: List[str] = self._buckets[ind]
if item is None:
raise KeyError(SCREAMING_SNAKE_CASE__ )
if item is _deleted:
continue
if item.key == key:
snake_case: str = _deleted
self._len -= 1
break
if self._is_sparse():
self._size_down()
def __getitem__( self , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
for ind in self._iterate_buckets(SCREAMING_SNAKE_CASE__ ):
snake_case: Union[str, Any] = self._buckets[ind]
if item is None:
break
if item is _deleted:
continue
if item.key == key:
return item.val
raise KeyError(SCREAMING_SNAKE_CASE__ )
def __len__( self ):
'''simple docstring'''
return self._len
def __iter__( self ):
'''simple docstring'''
yield from (item.key for item in self._buckets if item)
def __repr__( self ):
'''simple docstring'''
snake_case: Union[str, Any] = ' ,'.join(
F"""{item.key}: {item.val}""" for item in self._buckets if item )
return F"""HashMap({val_string})"""
| 329
| 0
|
from itertools import product
def A ( __UpperCAmelCase , __UpperCAmelCase ) -> list[int]:
'''simple docstring'''
UpperCAmelCase_ = sides_number
UpperCAmelCase_ = max_face_number * dice_number
UpperCAmelCase_ = [0] * (max_total + 1)
UpperCAmelCase_ = 1
UpperCAmelCase_ = range(__UpperCAmelCase , max_face_number + 1 )
for dice_numbers in product(__UpperCAmelCase , repeat=__UpperCAmelCase ):
UpperCAmelCase_ = sum(__UpperCAmelCase )
totals_frequencies[total] += 1
return totals_frequencies
def A ( ) -> float:
'''simple docstring'''
UpperCAmelCase_ = total_frequency_distribution(
sides_number=4 , dice_number=9 )
UpperCAmelCase_ = total_frequency_distribution(
sides_number=6 , dice_number=6 )
UpperCAmelCase_ = 0
UpperCAmelCase_ = 9
UpperCAmelCase_ = 4 * 9
UpperCAmelCase_ = 6
for peter_total in range(__UpperCAmelCase , max_peter_total + 1 ):
peter_wins_count += peter_totals_frequencies[peter_total] * sum(
colin_totals_frequencies[min_colin_total:peter_total] )
UpperCAmelCase_ = (4**9) * (6**6)
UpperCAmelCase_ = peter_wins_count / total_games_number
UpperCAmelCase_ = round(__UpperCAmelCase , ndigits=7 )
return rounded_peter_win_probability
if __name__ == "__main__":
print(f"{solution() = }")
| 714
|
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 a_ ( _snake_case , unittest.TestCase ):
UpperCamelCase__ : Optional[Any] =DiTPipeline
UpperCamelCase__ : Optional[int] =CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
UpperCamelCase__ : int =PipelineTesterMixin.required_optional_params - {
"latents",
"num_images_per_prompt",
"callback",
"callback_steps",
}
UpperCamelCase__ : List[Any] =CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
UpperCamelCase__ : Dict =False
def __a ( self :List[str]) -> Dict:
torch.manual_seed(0)
UpperCAmelCase_ = 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=_lowercase , activation_fn='''gelu-approximate''' , num_embeds_ada_norm=1000 , norm_type='''ada_norm_zero''' , norm_elementwise_affine=_lowercase , )
UpperCAmelCase_ = AutoencoderKL()
UpperCAmelCase_ = DDIMScheduler()
UpperCAmelCase_ = {'''transformer''': transformer.eval(), '''vae''': vae.eval(), '''scheduler''': scheduler}
return components
def __a ( self :Tuple , _lowercase :str , _lowercase :Union[str, Any]=0) -> List[str]:
if str(_lowercase).startswith('''mps'''):
UpperCAmelCase_ = torch.manual_seed(_lowercase)
else:
UpperCAmelCase_ = torch.Generator(device=_lowercase).manual_seed(_lowercase)
UpperCAmelCase_ = {
'''class_labels''': [1],
'''generator''': generator,
'''num_inference_steps''': 2,
'''output_type''': '''numpy''',
}
return inputs
def __a ( self :Optional[int]) -> List[Any]:
UpperCAmelCase_ = '''cpu'''
UpperCAmelCase_ = self.get_dummy_components()
UpperCAmelCase_ = self.pipeline_class(**_lowercase)
pipe.to(_lowercase)
pipe.set_progress_bar_config(disable=_lowercase)
UpperCAmelCase_ = self.get_dummy_inputs(_lowercase)
UpperCAmelCase_ = pipe(**_lowercase).images
UpperCAmelCase_ = image[0, -3:, -3:, -1]
self.assertEqual(image.shape , (1, 16, 16, 3))
UpperCAmelCase_ = np.array([0.2_946, 0.6_601, 0.4_329, 0.3_296, 0.4_144, 0.5_319, 0.7_273, 0.5_013, 0.4_457])
UpperCAmelCase_ = np.abs(image_slice.flatten() - expected_slice).max()
self.assertLessEqual(_lowercase , 1E-3)
def __a ( self :int) -> Tuple:
self._test_inference_batch_single_identical(relax_max_difference=_lowercase , 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 __a ( self :Dict) -> List[str]:
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3)
@require_torch_gpu
@slow
class a_ ( unittest.TestCase ):
def __a ( self :Tuple) -> Dict:
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __a ( self :Union[str, Any]) -> Dict:
UpperCAmelCase_ = torch.manual_seed(0)
UpperCAmelCase_ = DiTPipeline.from_pretrained('''facebook/DiT-XL-2-256''')
pipe.to('''cuda''')
UpperCAmelCase_ = ['''vase''', '''umbrella''', '''white shark''', '''white wolf''']
UpperCAmelCase_ = pipe.get_label_ids(_lowercase)
UpperCAmelCase_ = pipe(_lowercase , generator=_lowercase , num_inference_steps=40 , output_type='''np''').images
for word, image in zip(_lowercase , _lowercase):
UpperCAmelCase_ = 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 __a ( self :str) -> str:
UpperCAmelCase_ = DiTPipeline.from_pretrained('''facebook/DiT-XL-2-512''')
UpperCAmelCase_ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe.to('''cuda''')
UpperCAmelCase_ = ['''vase''', '''umbrella''']
UpperCAmelCase_ = pipe.get_label_ids(_lowercase)
UpperCAmelCase_ = torch.manual_seed(0)
UpperCAmelCase_ = pipe(_lowercase , generator=_lowercase , num_inference_steps=25 , output_type='''np''').images
for word, image in zip(_lowercase , _lowercase):
UpperCAmelCase_ = 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
| 561
| 0
|
'''simple docstring'''
import collections
import inspect
import unittest
from transformers import SwinvaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel
from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class __magic_name__ :
def __init__( self , snake_case_ , snake_case_=13 , snake_case_=32 , snake_case_=2 , snake_case_=3 , snake_case_=16 , snake_case_=[1, 2, 1] , snake_case_=[2, 2, 4] , snake_case_=2 , snake_case_=2.0 , snake_case_=True , snake_case_=0.0 , snake_case_=0.0 , snake_case_=0.1 , snake_case_="gelu" , snake_case_=False , snake_case_=True , snake_case_=0.02 , snake_case_=1E-5 , snake_case_=True , snake_case_=None , snake_case_=True , snake_case_=10 , snake_case_=8 , ):
lowercase =parent
lowercase =batch_size
lowercase =image_size
lowercase =patch_size
lowercase =num_channels
lowercase =embed_dim
lowercase =depths
lowercase =num_heads
lowercase =window_size
lowercase =mlp_ratio
lowercase =qkv_bias
lowercase =hidden_dropout_prob
lowercase =attention_probs_dropout_prob
lowercase =drop_path_rate
lowercase =hidden_act
lowercase =use_absolute_embeddings
lowercase =patch_norm
lowercase =layer_norm_eps
lowercase =initializer_range
lowercase =is_training
lowercase =scope
lowercase =use_labels
lowercase =type_sequence_label_size
lowercase =encoder_stride
def _A( self ):
lowercase =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowercase =None
if self.use_labels:
lowercase =ids_tensor([self.batch_size] , self.type_sequence_label_size )
lowercase =self.get_config()
return config, pixel_values, labels
def _A( self ):
return SwinvaConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , )
def _A( self , snake_case_ , snake_case_ , snake_case_ ):
lowercase =SwinvaModel(config=snake_case_ )
model.to(snake_case_ )
model.eval()
lowercase =model(snake_case_ )
lowercase =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
lowercase =int(config.embed_dim * 2 ** (len(config.depths ) - 1) )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) )
def _A( self , snake_case_ , snake_case_ , snake_case_ ):
lowercase =SwinvaForMaskedImageModeling(config=snake_case_ )
model.to(snake_case_ )
model.eval()
lowercase =model(snake_case_ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) )
# test greyscale images
lowercase =1
lowercase =SwinvaForMaskedImageModeling(snake_case_ )
model.to(snake_case_ )
model.eval()
lowercase =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
lowercase =model(snake_case_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) )
def _A( self , snake_case_ , snake_case_ , snake_case_ ):
lowercase =self.type_sequence_label_size
lowercase =SwinvaForImageClassification(snake_case_ )
model.to(snake_case_ )
model.eval()
lowercase =model(snake_case_ , labels=snake_case_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def _A( self ):
lowercase =self.prepare_config_and_inputs()
lowercase , lowercase , lowercase =config_and_inputs
lowercase ={'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class __magic_name__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ):
UpperCamelCase__ = (
(SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
)
UpperCamelCase__ = (
{'feature-extraction': SwinvaModel, 'image-classification': SwinvaForImageClassification}
if is_torch_available()
else {}
)
UpperCamelCase__ = False
UpperCamelCase__ = False
UpperCamelCase__ = False
UpperCamelCase__ = False
def _A( self ):
lowercase =SwinvaModelTester(self )
lowercase =ConfigTester(self , config_class=snake_case_ , embed_dim=37 )
def _A( self ):
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def _A( self ):
lowercase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*snake_case_ )
@unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.''' )
def _A( self ):
pass
@unittest.skip(reason='''Swinv2 does not use inputs_embeds''' )
def _A( self ):
pass
def _A( self ):
lowercase , lowercase =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase =model_class(snake_case_ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
lowercase =model.get_output_embeddings()
self.assertTrue(x is None or isinstance(snake_case_ , nn.Linear ) )
def _A( self ):
lowercase , lowercase =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase =model_class(snake_case_ )
lowercase =inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowercase =[*signature.parameters.keys()]
lowercase =['''pixel_values''']
self.assertListEqual(arg_names[:1] , snake_case_ )
def _A( self ):
lowercase , lowercase =self.model_tester.prepare_config_and_inputs_for_common()
lowercase =True
for model_class in self.all_model_classes:
lowercase =True
lowercase =False
lowercase =True
lowercase =model_class(snake_case_ )
model.to(snake_case_ )
model.eval()
with torch.no_grad():
lowercase =model(**self._prepare_for_class(snake_case_ , snake_case_ ) )
lowercase =outputs.attentions
lowercase =len(self.model_tester.depths )
self.assertEqual(len(snake_case_ ) , snake_case_ )
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
lowercase =True
lowercase =config.window_size**2
lowercase =model_class(snake_case_ )
model.to(snake_case_ )
model.eval()
with torch.no_grad():
lowercase =model(**self._prepare_for_class(snake_case_ , snake_case_ ) )
lowercase =outputs.attentions
self.assertEqual(len(snake_case_ ) , snake_case_ )
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , )
lowercase =len(snake_case_ )
# Check attention is always last and order is fine
lowercase =True
lowercase =True
lowercase =model_class(snake_case_ )
model.to(snake_case_ )
model.eval()
with torch.no_grad():
lowercase =model(**self._prepare_for_class(snake_case_ , snake_case_ ) )
if hasattr(self.model_tester , '''num_hidden_states_types''' ):
lowercase =self.model_tester.num_hidden_states_types
else:
# also another +1 for reshaped_hidden_states
lowercase =2
self.assertEqual(out_len + added_hidden_states , len(snake_case_ ) )
lowercase =outputs.attentions
self.assertEqual(len(snake_case_ ) , snake_case_ )
self.assertListEqual(
list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , )
def _A( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ):
lowercase =model_class(snake_case_ )
model.to(snake_case_ )
model.eval()
with torch.no_grad():
lowercase =model(**self._prepare_for_class(snake_case_ , snake_case_ ) )
lowercase =outputs.hidden_states
lowercase =getattr(
self.model_tester , '''expected_num_hidden_layers''' , len(self.model_tester.depths ) + 1 )
self.assertEqual(len(snake_case_ ) , snake_case_ )
# Swinv2 has a different seq_length
lowercase =(
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
lowercase =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , )
lowercase =outputs.reshaped_hidden_states
self.assertEqual(len(snake_case_ ) , snake_case_ )
lowercase , lowercase , lowercase , lowercase =reshaped_hidden_states[0].shape
lowercase =(
reshaped_hidden_states[0].view(snake_case_ , snake_case_ , height * width ).permute(0 , 2 , 1 )
)
self.assertListEqual(
list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , )
def _A( self ):
lowercase , lowercase =self.model_tester.prepare_config_and_inputs_for_common()
lowercase =(
self.model_tester.image_size
if isinstance(self.model_tester.image_size , collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
for model_class in self.all_model_classes:
lowercase =True
self.check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ , snake_case_ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowercase =True
self.check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ , snake_case_ )
def _A( self ):
lowercase , lowercase =self.model_tester.prepare_config_and_inputs_for_common()
lowercase =3
lowercase =(
self.model_tester.image_size
if isinstance(self.model_tester.image_size , collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
lowercase =(
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
lowercase =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
lowercase =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
for model_class in self.all_model_classes:
lowercase =True
self.check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ , (padded_height, padded_width) )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowercase =True
self.check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ , (padded_height, padded_width) )
def _A( self ):
lowercase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*snake_case_ )
def _A( self ):
lowercase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*snake_case_ )
@slow
def _A( self ):
for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowercase =SwinvaModel.from_pretrained(snake_case_ )
self.assertIsNotNone(snake_case_ )
def _A( self ):
lowercase , lowercase =self.model_tester.prepare_config_and_inputs_for_common()
lowercase =_config_zero_init(snake_case_ )
for model_class in self.all_model_classes:
lowercase =model_class(config=snake_case_ )
for name, param in model.named_parameters():
if "embeddings" not in name and "logit_scale" not in name and param.requires_grad:
self.assertIn(
((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , )
@require_vision
@require_torch
class __magic_name__ ( unittest.TestCase ):
@cached_property
def _A( self ):
return (
AutoImageProcessor.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''' )
if is_vision_available()
else None
)
@slow
def _A( self ):
lowercase =SwinvaForImageClassification.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''' ).to(
snake_case_ )
lowercase =self.default_image_processor
lowercase =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
lowercase =image_processor(images=snake_case_ , return_tensors='''pt''' ).to(snake_case_ )
# forward pass
with torch.no_grad():
lowercase =model(**snake_case_ )
# verify the logits
lowercase =torch.Size((1, 10_00) )
self.assertEqual(outputs.logits.shape , snake_case_ )
lowercase =torch.tensor([-0.39_47, -0.43_06, 0.00_26] ).to(snake_case_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case_ , atol=1E-4 ) )
| 72
|
"""simple docstring"""
import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List
import git
import torch
from torch.utils.data import Dataset
from transformers import BartTokenizer, RagTokenizer, TaTokenizer
def snake_case_ ( A_ : Tuple, A_ : List[str], A_ : Optional[Any], A_ : Dict, A_ : Dict=True, A_ : int="pt" ):
'''simple docstring'''
_lowerCamelCase : str = {'''add_prefix_space''': True} if isinstance(A_, A_ ) and not line.startswith(''' ''' ) else {}
_lowerCamelCase : Union[str, Any] = padding_side
return tokenizer(
[line], max_length=A_, padding='''max_length''' if pad_to_max_length else None, truncation=A_, return_tensors=A_, add_special_tokens=A_, **A_, )
def snake_case_ ( A_ : Any, A_ : Optional[int], A_ : List[Any]=None, ):
'''simple docstring'''
_lowerCamelCase : Optional[int] = input_ids.ne(A_ ).any(dim=0 )
if attention_mask is None:
return input_ids[:, keep_column_mask]
else:
return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
class __snake_case ( _lowercase):
def __init__( self : Tuple , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Tuple="train" , __lowerCAmelCase : List[str]=None , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Any=None , __lowerCAmelCase : Union[str, Any]="" , ):
"""simple docstring"""
super().__init__()
_lowerCamelCase : Optional[int] = Path(__lowerCAmelCase ).joinpath(type_path + '''.source''' )
_lowerCamelCase : List[str] = Path(__lowerCAmelCase ).joinpath(type_path + '''.target''' )
_lowerCamelCase : List[Any] = self.get_char_lens(self.src_file )
_lowerCamelCase : Optional[int] = max_source_length
_lowerCamelCase : Optional[Any] = max_target_length
assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}'''
_lowerCamelCase : List[Any] = tokenizer
_lowerCamelCase : List[Any] = prefix
if n_obs is not None:
_lowerCamelCase : List[str] = self.src_lens[:n_obs]
_lowerCamelCase : int = src_lang
_lowerCamelCase : Union[str, Any] = tgt_lang
def __len__( self : int ):
"""simple docstring"""
return len(self.src_lens )
def __getitem__( self : Dict , __lowerCAmelCase : Optional[Any] ):
"""simple docstring"""
_lowerCamelCase : str = index + 1 # linecache starts at 1
_lowerCamelCase : Union[str, Any] = self.prefix + linecache.getline(str(self.src_file ) , __lowerCAmelCase ).rstrip('''\n''' )
_lowerCamelCase : Optional[Any] = linecache.getline(str(self.tgt_file ) , __lowerCAmelCase ).rstrip('''\n''' )
assert source_line, f'''empty source line for index {index}'''
assert tgt_line, f'''empty tgt line for index {index}'''
# Need to add eos token manually for T5
if isinstance(self.tokenizer , __lowerCAmelCase ):
source_line += self.tokenizer.eos_token
tgt_line += self.tokenizer.eos_token
# Pad source and target to the right
_lowerCamelCase : Optional[int] = (
self.tokenizer.question_encoder if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer
)
_lowerCamelCase : Union[str, Any] = self.tokenizer.generator if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer
_lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_source_length , '''right''' )
_lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_target_length , '''right''' )
_lowerCamelCase : Optional[Any] = source_inputs['''input_ids'''].squeeze()
_lowerCamelCase : Union[str, Any] = target_inputs['''input_ids'''].squeeze()
_lowerCamelCase : Any = source_inputs['''attention_mask'''].squeeze()
return {
"input_ids": source_ids,
"attention_mask": src_mask,
"decoder_input_ids": target_ids,
}
@staticmethod
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : str ):
"""simple docstring"""
return [len(__lowerCAmelCase ) for x in Path(__lowerCAmelCase ).open().readlines()]
def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Any ):
"""simple docstring"""
_lowerCamelCase : List[Any] = torch.stack([x['''input_ids'''] for x in batch] )
_lowerCamelCase : Tuple = torch.stack([x['''attention_mask'''] for x in batch] )
_lowerCamelCase : Union[str, Any] = torch.stack([x['''decoder_input_ids'''] for x in batch] )
_lowerCamelCase : Tuple = (
self.tokenizer.generator.pad_token_id
if isinstance(self.tokenizer , __lowerCAmelCase )
else self.tokenizer.pad_token_id
)
_lowerCamelCase : Tuple = (
self.tokenizer.question_encoder.pad_token_id
if isinstance(self.tokenizer , __lowerCAmelCase )
else self.tokenizer.pad_token_id
)
_lowerCamelCase : Union[str, Any] = trim_batch(__lowerCAmelCase , __lowerCAmelCase )
_lowerCamelCase , _lowerCamelCase : List[str] = trim_batch(__lowerCAmelCase , __lowerCAmelCase , attention_mask=__lowerCAmelCase )
_lowerCamelCase : Optional[int] = {
'''input_ids''': source_ids,
'''attention_mask''': source_mask,
'''decoder_input_ids''': y,
}
return batch
lowerCAmelCase__ = getLogger(__name__)
def snake_case_ ( A_ : List[List] ):
'''simple docstring'''
return list(itertools.chain.from_iterable(A_ ) )
def snake_case_ ( A_ : str ):
'''simple docstring'''
_lowerCamelCase : Dict = get_git_info()
save_json(A_, os.path.join(A_, '''git_log.json''' ) )
def snake_case_ ( A_ : str, A_ : Union[str, Any], A_ : int=4, **A_ : Optional[int] ):
'''simple docstring'''
with open(A_, '''w''' ) as f:
json.dump(A_, A_, indent=A_, **A_ )
def snake_case_ ( A_ : Any ):
'''simple docstring'''
with open(A_ ) as f:
return json.load(A_ )
def snake_case_ ( ):
'''simple docstring'''
_lowerCamelCase : List[str] = git.Repo(search_parent_directories=A_ )
_lowerCamelCase : str = {
'''repo_id''': str(A_ ),
'''repo_sha''': str(repo.head.object.hexsha ),
'''repo_branch''': str(repo.active_branch ),
'''hostname''': str(socket.gethostname() ),
}
return repo_infos
def snake_case_ ( A_ : Callable, A_ : Iterable ):
'''simple docstring'''
return list(map(A_, A_ ) )
def snake_case_ ( A_ : str, A_ : Tuple ):
'''simple docstring'''
with open(A_, '''wb''' ) as f:
return pickle.dump(A_, A_ )
def snake_case_ ( A_ : List[str] ):
'''simple docstring'''
def remove_articles(A_ : str ):
return re.sub(R'''\b(a|an|the)\b''', ''' ''', A_ )
def white_space_fix(A_ : Any ):
return " ".join(text.split() )
def remove_punc(A_ : List[Any] ):
_lowerCamelCase : Any = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(A_ : Optional[int] ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(A_ ) ) ) )
def snake_case_ ( A_ : int, A_ : List[Any] ):
'''simple docstring'''
_lowerCamelCase : str = normalize_answer(A_ ).split()
_lowerCamelCase : int = normalize_answer(A_ ).split()
_lowerCamelCase : str = Counter(A_ ) & Counter(A_ )
_lowerCamelCase : Any = sum(common.values() )
if num_same == 0:
return 0
_lowerCamelCase : int = 1.0 * num_same / len(A_ )
_lowerCamelCase : str = 1.0 * num_same / len(A_ )
_lowerCamelCase : List[Any] = (2 * precision * recall) / (precision + recall)
return fa
def snake_case_ ( A_ : Dict, A_ : str ):
'''simple docstring'''
return normalize_answer(A_ ) == normalize_answer(A_ )
def snake_case_ ( A_ : List[str], A_ : List[str] ):
'''simple docstring'''
assert len(A_ ) == len(A_ )
_lowerCamelCase : Optional[Any] = 0
for hypo, pred in zip(A_, A_ ):
em += exact_match_score(A_, A_ )
if len(A_ ) > 0:
em /= len(A_ )
return {"em": em}
def snake_case_ ( A_ : Optional[int] ):
'''simple docstring'''
return model_prefix.startswith('''rag''' )
def snake_case_ ( A_ : Dict, A_ : int, A_ : List[Any] ):
'''simple docstring'''
_lowerCamelCase : Dict = {p: p for p in extra_params}
# T5 models don't have `dropout` param, they have `dropout_rate` instead
_lowerCamelCase : Tuple = '''dropout_rate'''
for p in extra_params:
if getattr(A_, A_, A_ ):
if not hasattr(A_, A_ ) and not hasattr(A_, equivalent_param[p] ):
logger.info('''config doesn\'t have a `{}` attribute'''.format(A_ ) )
delattr(A_, A_ )
continue
_lowerCamelCase : Union[str, Any] = p if hasattr(A_, A_ ) else equivalent_param[p]
setattr(A_, A_, getattr(A_, A_ ) )
delattr(A_, A_ )
return hparams, config
| 83
| 0
|
import copy
import json
import os
import tempfile
from transformers import is_torch_available
from .test_configuration_utils import config_common_kwargs
class lowercase__ ( _UpperCAmelCase ):
def __init__( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase=None , **__UpperCAmelCase )-> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase__ = parent
lowerCAmelCase__ = config_class
lowerCAmelCase__ = has_text_modality
lowerCAmelCase__ = kwargs
lowerCAmelCase__ = common_properties
def UpperCAmelCase ( self )-> int:
'''simple docstring'''
lowerCAmelCase__ = self.config_class(**self.inputs_dict )
lowerCAmelCase__ = (
["hidden_size", "num_attention_heads", "num_hidden_layers"]
if self.common_properties is None
else self.common_properties
)
# Add common fields for text models
if self.has_text_modality:
common_properties.extend(["vocab_size"] )
# Test that config has the common properties as getters
for prop in common_properties:
self.parent.assertTrue(hasattr(__UpperCAmelCase , __UpperCAmelCase ) , msg=F"`{prop}` does not exist" )
# Test that config has the common properties as setter
for idx, name in enumerate(__UpperCAmelCase ):
try:
setattr(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
self.parent.assertEqual(
getattr(__UpperCAmelCase , __UpperCAmelCase ) , __UpperCAmelCase , msg=F"`{name} value {idx} expected, but was {getattr(__UpperCAmelCase , __UpperCAmelCase )}" )
except NotImplementedError:
# Some models might not be able to implement setters for common_properties
# In that case, a NotImplementedError is raised
pass
# Test if config class can be called with Config(prop_name=..)
for idx, name in enumerate(__UpperCAmelCase ):
try:
lowerCAmelCase__ = self.config_class(**{name: idx} )
self.parent.assertEqual(
getattr(__UpperCAmelCase , __UpperCAmelCase ) , __UpperCAmelCase , msg=F"`{name} value {idx} expected, but was {getattr(__UpperCAmelCase , __UpperCAmelCase )}" )
except NotImplementedError:
# Some models might not be able to implement setters for common_properties
# In that case, a NotImplementedError is raised
pass
def UpperCAmelCase ( self )-> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase__ = self.config_class(**self.inputs_dict )
lowerCAmelCase__ = json.loads(config.to_json_string() )
for key, value in self.inputs_dict.items():
self.parent.assertEqual(obj[key] , __UpperCAmelCase )
def UpperCAmelCase ( self )-> str:
'''simple docstring'''
lowerCAmelCase__ = self.config_class(**self.inputs_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
lowerCAmelCase__ = os.path.join(__UpperCAmelCase , "config.json" )
config_first.to_json_file(__UpperCAmelCase )
lowerCAmelCase__ = self.config_class.from_json_file(__UpperCAmelCase )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def UpperCAmelCase ( self )-> List[Any]:
'''simple docstring'''
lowerCAmelCase__ = self.config_class(**self.inputs_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
config_first.save_pretrained(__UpperCAmelCase )
lowerCAmelCase__ = self.config_class.from_pretrained(__UpperCAmelCase )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def UpperCAmelCase ( self )-> List[str]:
'''simple docstring'''
lowerCAmelCase__ = self.config_class(**self.inputs_dict )
lowerCAmelCase__ = "test"
with tempfile.TemporaryDirectory() as tmpdirname:
lowerCAmelCase__ = os.path.join(__UpperCAmelCase , __UpperCAmelCase )
config_first.save_pretrained(__UpperCAmelCase )
lowerCAmelCase__ = self.config_class.from_pretrained(__UpperCAmelCase , subfolder=__UpperCAmelCase )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def UpperCAmelCase ( self )-> str:
'''simple docstring'''
lowerCAmelCase__ = self.config_class(**self.inputs_dict , num_labels=5 )
self.parent.assertEqual(len(config.idalabel ) , 5 )
self.parent.assertEqual(len(config.labelaid ) , 5 )
lowerCAmelCase__ = 3
self.parent.assertEqual(len(config.idalabel ) , 3 )
self.parent.assertEqual(len(config.labelaid ) , 3 )
def UpperCAmelCase ( self )-> List[Any]:
'''simple docstring'''
if self.config_class.is_composition:
return
lowerCAmelCase__ = self.config_class()
self.parent.assertIsNotNone(__UpperCAmelCase )
def UpperCAmelCase ( self )-> Optional[Any]:
'''simple docstring'''
lowerCAmelCase__ = copy.deepcopy(__UpperCAmelCase )
lowerCAmelCase__ = self.config_class(**__UpperCAmelCase )
lowerCAmelCase__ = []
for key, value in config_common_kwargs.items():
if key == "torch_dtype":
if not is_torch_available():
continue
else:
import torch
if config.torch_dtype != torch.floataa:
wrong_values.append(("torch_dtype", config.torch_dtype, torch.floataa) )
elif getattr(__UpperCAmelCase , __UpperCAmelCase ) != value:
wrong_values.append((key, getattr(__UpperCAmelCase , __UpperCAmelCase ), value) )
if len(__UpperCAmelCase ) > 0:
lowerCAmelCase__ = "\n".join([F"- {v[0]}: got {v[1]} instead of {v[2]}" for v in wrong_values] )
raise ValueError(F"The following keys were not properly set in the config:\n{errors}" )
def UpperCAmelCase ( self )-> str:
'''simple docstring'''
self.create_and_test_config_common_properties()
self.create_and_test_config_to_json_string()
self.create_and_test_config_to_json_file()
self.create_and_test_config_from_and_save_pretrained()
self.create_and_test_config_from_and_save_pretrained_subfolder()
self.create_and_test_config_with_num_labels()
self.check_config_can_be_init_without_params()
self.check_config_arguments_init()
| 115
|
import unittest
from transformers import AutoTokenizer, NystromformerConfig, is_torch_available
from transformers.testing_utils import 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 (
NystromformerForMaskedLM,
NystromformerForMultipleChoice,
NystromformerForQuestionAnswering,
NystromformerForSequenceClassification,
NystromformerForTokenClassification,
NystromformerModel,
)
from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST
class lowercase__ :
def __init__( self , __UpperCAmelCase , __UpperCAmelCase=13 , __UpperCAmelCase=7 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=99 , __UpperCAmelCase=32 , __UpperCAmelCase=5 , __UpperCAmelCase=4 , __UpperCAmelCase=37 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=512 , __UpperCAmelCase=16 , __UpperCAmelCase=2 , __UpperCAmelCase=0.02 , __UpperCAmelCase=3 , __UpperCAmelCase=4 , __UpperCAmelCase=None , )-> Any:
'''simple docstring'''
lowerCAmelCase__ = parent
lowerCAmelCase__ = batch_size
lowerCAmelCase__ = seq_length
lowerCAmelCase__ = is_training
lowerCAmelCase__ = use_input_mask
lowerCAmelCase__ = use_token_type_ids
lowerCAmelCase__ = use_labels
lowerCAmelCase__ = vocab_size
lowerCAmelCase__ = hidden_size
lowerCAmelCase__ = num_hidden_layers
lowerCAmelCase__ = num_attention_heads
lowerCAmelCase__ = intermediate_size
lowerCAmelCase__ = hidden_act
lowerCAmelCase__ = hidden_dropout_prob
lowerCAmelCase__ = attention_probs_dropout_prob
lowerCAmelCase__ = max_position_embeddings
lowerCAmelCase__ = type_vocab_size
lowerCAmelCase__ = type_sequence_label_size
lowerCAmelCase__ = initializer_range
lowerCAmelCase__ = num_labels
lowerCAmelCase__ = num_choices
lowerCAmelCase__ = scope
def UpperCAmelCase ( self )-> Optional[Any]:
'''simple docstring'''
lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
lowerCAmelCase__ = None
if self.use_input_mask:
lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] )
lowerCAmelCase__ = None
if self.use_token_type_ids:
lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
lowerCAmelCase__ = None
lowerCAmelCase__ = None
lowerCAmelCase__ = None
if self.use_labels:
lowerCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices )
lowerCAmelCase__ = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def UpperCAmelCase ( self )-> Optional[Any]:
'''simple docstring'''
return NystromformerConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__UpperCAmelCase , initializer_range=self.initializer_range , )
def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )-> int:
'''simple docstring'''
lowerCAmelCase__ = NystromformerModel(config=__UpperCAmelCase )
model.to(__UpperCAmelCase )
model.eval()
lowerCAmelCase__ = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase )
lowerCAmelCase__ = model(__UpperCAmelCase , token_type_ids=__UpperCAmelCase )
lowerCAmelCase__ = model(__UpperCAmelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )-> str:
'''simple docstring'''
lowerCAmelCase__ = NystromformerForMaskedLM(config=__UpperCAmelCase )
model.to(__UpperCAmelCase )
model.eval()
lowerCAmelCase__ = 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 UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )-> Any:
'''simple docstring'''
lowerCAmelCase__ = NystromformerForQuestionAnswering(config=__UpperCAmelCase )
model.to(__UpperCAmelCase )
model.eval()
lowerCAmelCase__ = 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 UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )-> Dict:
'''simple docstring'''
lowerCAmelCase__ = self.num_labels
lowerCAmelCase__ = NystromformerForSequenceClassification(__UpperCAmelCase )
model.to(__UpperCAmelCase )
model.eval()
lowerCAmelCase__ = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )-> str:
'''simple docstring'''
lowerCAmelCase__ = self.num_labels
lowerCAmelCase__ = NystromformerForTokenClassification(config=__UpperCAmelCase )
model.to(__UpperCAmelCase )
model.eval()
lowerCAmelCase__ = 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 UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )-> Optional[int]:
'''simple docstring'''
lowerCAmelCase__ = self.num_choices
lowerCAmelCase__ = NystromformerForMultipleChoice(config=__UpperCAmelCase )
model.to(__UpperCAmelCase )
model.eval()
lowerCAmelCase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
lowerCAmelCase__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
lowerCAmelCase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
lowerCAmelCase__ = model(
__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def UpperCAmelCase ( self )-> Any:
'''simple docstring'''
lowerCAmelCase__ = self.prepare_config_and_inputs()
(
(
lowerCAmelCase__
) , (
lowerCAmelCase__
) , (
lowerCAmelCase__
) , (
lowerCAmelCase__
) , (
lowerCAmelCase__
) , (
lowerCAmelCase__
) , (
lowerCAmelCase__
) ,
) = config_and_inputs
lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class lowercase__ ( _UpperCAmelCase, _UpperCAmelCase, unittest.TestCase ):
a_ =(
(
NystromformerModel,
NystromformerForMaskedLM,
NystromformerForMultipleChoice,
NystromformerForQuestionAnswering,
NystromformerForSequenceClassification,
NystromformerForTokenClassification,
)
if is_torch_available()
else ()
)
a_ =(
{
"""feature-extraction""": NystromformerModel,
"""fill-mask""": NystromformerForMaskedLM,
"""question-answering""": NystromformerForQuestionAnswering,
"""text-classification""": NystromformerForSequenceClassification,
"""token-classification""": NystromformerForTokenClassification,
"""zero-shot""": NystromformerForSequenceClassification,
}
if is_torch_available()
else {}
)
a_ =False
a_ =False
def UpperCAmelCase ( self )-> int:
'''simple docstring'''
lowerCAmelCase__ = NystromformerModelTester(self )
lowerCAmelCase__ = ConfigTester(self , config_class=__UpperCAmelCase , hidden_size=37 )
def UpperCAmelCase ( self )-> Dict:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self )-> List[Any]:
'''simple docstring'''
lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__UpperCAmelCase )
def UpperCAmelCase ( self )-> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
lowerCAmelCase__ = type
self.model_tester.create_and_check_model(*__UpperCAmelCase )
def UpperCAmelCase ( self )-> List[Any]:
'''simple docstring'''
lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*__UpperCAmelCase )
def UpperCAmelCase ( self )-> Optional[int]:
'''simple docstring'''
lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*__UpperCAmelCase )
def UpperCAmelCase ( self )-> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*__UpperCAmelCase )
def UpperCAmelCase ( self )-> int:
'''simple docstring'''
lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*__UpperCAmelCase )
def UpperCAmelCase ( self )-> Any:
'''simple docstring'''
lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase )
@slow
def UpperCAmelCase ( self )-> Optional[int]:
'''simple docstring'''
for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCAmelCase__ = NystromformerModel.from_pretrained(__UpperCAmelCase )
self.assertIsNotNone(__UpperCAmelCase )
@require_torch
class lowercase__ ( unittest.TestCase ):
@slow
def UpperCAmelCase ( self )-> Dict:
'''simple docstring'''
lowerCAmelCase__ = NystromformerModel.from_pretrained("uw-madison/nystromformer-512" )
lowerCAmelCase__ = torch.tensor([[0, 1, 2, 3, 4, 5]] )
with torch.no_grad():
lowerCAmelCase__ = model(__UpperCAmelCase )[0]
lowerCAmelCase__ = torch.Size((1, 6, 768) )
self.assertEqual(output.shape , __UpperCAmelCase )
lowerCAmelCase__ = torch.tensor(
[[[-0.4_532, -0.0_936, 0.5_137], [-0.2_676, 0.0_628, 0.6_186], [-0.3_629, -0.1_726, 0.4_716]]] )
self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4 ) )
@slow
def UpperCAmelCase ( self )-> Any:
'''simple docstring'''
lowerCAmelCase__ = "the [MASK] of Belgium is Brussels"
lowerCAmelCase__ = AutoTokenizer.from_pretrained("uw-madison/nystromformer-512" )
lowerCAmelCase__ = NystromformerForMaskedLM.from_pretrained("uw-madison/nystromformer-512" )
lowerCAmelCase__ = tokenizer(__UpperCAmelCase , return_tensors="pt" )
with torch.no_grad():
lowerCAmelCase__ = model(encoding.input_ids ).logits
lowerCAmelCase__ = token_logits[:, 2, :].argmax(-1 )[0]
self.assertEqual(tokenizer.decode(__UpperCAmelCase ) , "capital" )
| 115
| 1
|
"""simple docstring"""
import inspect
import math
import tempfile
import unittest
import numpy as np
from transformers import ViTMAEConfig
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 ViTMAEForPreTraining, ViTMAEModel
from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class lowerCamelCase :
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=30 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , 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_=10 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=0.6 , SCREAMING_SNAKE_CASE_=None , ):
UpperCamelCase : Union[str, Any] = parent
UpperCamelCase : Optional[Any] = batch_size
UpperCamelCase : List[Any] = image_size
UpperCamelCase : List[Any] = patch_size
UpperCamelCase : List[str] = num_channels
UpperCamelCase : Dict = is_training
UpperCamelCase : int = use_labels
UpperCamelCase : str = hidden_size
UpperCamelCase : Union[str, Any] = num_hidden_layers
UpperCamelCase : Optional[int] = num_attention_heads
UpperCamelCase : List[str] = intermediate_size
UpperCamelCase : Dict = hidden_act
UpperCamelCase : Any = hidden_dropout_prob
UpperCamelCase : Dict = attention_probs_dropout_prob
UpperCamelCase : Optional[int] = type_sequence_label_size
UpperCamelCase : Optional[int] = initializer_range
UpperCamelCase : Union[str, Any] = mask_ratio
UpperCamelCase : Union[str, Any] = scope
# in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
# (we add 1 for the [CLS] token)
UpperCamelCase : int = (image_size // patch_size) ** 2
UpperCamelCase : Tuple = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) )
def a_ ( self ):
UpperCamelCase : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCamelCase : List[str] = None
if self.use_labels:
UpperCamelCase : int = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCamelCase : Tuple = self.get_config()
return config, pixel_values, labels
def a_ ( self ):
return ViTMAEConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , )
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : Optional[int] = ViTMAEModel(config=SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : int = ViTMAEForPreTraining(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_ )
UpperCamelCase : Optional[int] = (self.image_size // self.patch_size) ** 2
UpperCamelCase : Optional[Any] = self.patch_size**2 * self.num_channels
self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) )
# test greyscale images
UpperCamelCase : List[Any] = 1
UpperCamelCase : Optional[Any] = ViTMAEForPreTraining(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ )
UpperCamelCase : Union[str, Any] = self.patch_size**2
self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) )
def a_ ( self ):
UpperCamelCase : Union[str, Any] = self.prepare_config_and_inputs()
UpperCamelCase , UpperCamelCase , UpperCamelCase : Tuple = config_and_inputs
UpperCamelCase : List[str] = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_torch
class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ):
lowercase : Any = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else ()
lowercase : List[str] = {'feature-extraction': ViTMAEModel} if is_torch_available() else {}
lowercase : List[Any] = False
lowercase : int = False
lowercase : int = False
lowercase : Tuple = False
def a_ ( self ):
UpperCamelCase : Any = ViTMAEModelTester(self )
UpperCamelCase : Optional[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 )
def a_ ( self ):
self.config_tester.run_common_tests()
@unittest.skip(reason="""ViTMAE does not use inputs_embeds""" )
def a_ ( self ):
pass
def a_ ( self ):
UpperCamelCase , UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase : Union[str, Any] = model_class(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
UpperCamelCase : int = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) )
def a_ ( self ):
UpperCamelCase , UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase : Any = model_class(SCREAMING_SNAKE_CASE_ )
UpperCamelCase : Optional[Any] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCamelCase : Optional[Any] = [*signature.parameters.keys()]
UpperCamelCase : Optional[int] = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ )
def a_ ( self ):
UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ )
def a_ ( self ):
UpperCamelCase : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*SCREAMING_SNAKE_CASE_ )
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
# make masks reproducible
np.random.seed(2 )
UpperCamelCase : Optional[Any] = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 )
UpperCamelCase : Optional[int] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
UpperCamelCase : Optional[int] = torch.from_numpy(SCREAMING_SNAKE_CASE_ )
# Add `noise` argument.
# PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
UpperCamelCase : str = pt_noise
super().check_pt_tf_models(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def a_ ( self ):
UpperCamelCase , UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase : str = model_class(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
# make random mask reproducible
torch.manual_seed(2 )
with torch.no_grad():
UpperCamelCase : List[Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
UpperCamelCase : List[Any] = outputs[0].cpu().numpy()
UpperCamelCase : Union[str, Any] = 0
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(SCREAMING_SNAKE_CASE_ )
UpperCamelCase : Tuple = model_class.from_pretrained(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
# make random mask reproducible
torch.manual_seed(2 )
with torch.no_grad():
UpperCamelCase : Optional[int] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
# Make sure we don't have nans
UpperCamelCase : str = after_outputs[0].cpu().numpy()
UpperCamelCase : List[Any] = 0
UpperCamelCase : Any = np.amax(np.abs(out_a - out_a ) )
self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1e-5 )
@unittest.skip(
reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
to get deterministic results.""" )
def a_ ( self ):
pass
@unittest.skip(
reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
to get deterministic results.""" )
def a_ ( self ):
pass
@unittest.skip(
reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
to get deterministic results.""" )
def a_ ( self ):
pass
@unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" )
def a_ ( self ):
pass
@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" )
def a_ ( self ):
pass
@slow
def a_ ( self ):
for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCamelCase : Optional[Any] = ViTMAEModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
def A_ ( ):
'''simple docstring'''
UpperCamelCase : int = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
return image
@require_torch
@require_vision
class lowerCamelCase ( unittest.TestCase ):
@cached_property
def a_ ( self ):
return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None
@slow
def a_ ( self ):
# make random mask reproducible across the PT and TF model
np.random.seed(2 )
UpperCamelCase : Any = ViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ).to(SCREAMING_SNAKE_CASE_ )
UpperCamelCase : Tuple = self.default_image_processor
UpperCamelCase : Tuple = prepare_img()
UpperCamelCase : Optional[Any] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ )
# prepare a noise vector that will be also used for testing the TF model
# (this way we can ensure that the PT and TF models operate on the same inputs)
UpperCamelCase : Dict = ViTMAEConfig()
UpperCamelCase : List[str] = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 )
UpperCamelCase : Dict = np.random.uniform(size=(1, num_patches) )
# forward pass
with torch.no_grad():
UpperCamelCase : Any = model(**SCREAMING_SNAKE_CASE_ , noise=torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ ) )
# verify the logits
UpperCamelCase : Dict = torch.Size((1, 196, 768) )
self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ )
UpperCamelCase : Union[str, Any] = torch.tensor(
[[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] )
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(SCREAMING_SNAKE_CASE_ ) , atol=1e-4 ) )
| 499
|
"""simple docstring"""
import math
import random
def A_ ( snake_case_ : float ,snake_case_ : bool = False ):
'''simple docstring'''
if deriv:
return value * (1 - value)
return 1 / (1 + math.exp(-value ))
# Initial Value
__A : int = 0.02
def A_ ( snake_case_ : int ,snake_case_ : int ):
'''simple docstring'''
UpperCamelCase : List[str] = float(2 * (random.randint(1 ,1_0_0 )) - 1 )
for _ in range(snake_case_ ):
# Forward propagation
UpperCamelCase : Any = sigmoid_function(INITIAL_VALUE * weight )
# How much did we miss?
UpperCamelCase : Tuple = (expected / 1_0_0) - layer_a
# Error delta
UpperCamelCase : List[str] = layer_1_error * sigmoid_function(snake_case_ ,snake_case_ )
# Update weight
weight += INITIAL_VALUE * layer_1_delta
return layer_a * 1_0_0
if __name__ == "__main__":
import doctest
doctest.testmod()
__A : Dict = int(input('''Expected value: '''))
__A : List[Any] = int(input('''Number of propagations: '''))
print(forward_propagation(expected, number_propagations))
| 499
| 1
|
def lowerCAmelCase_ ( A_):
if not isinstance(A_ ,A_):
UpperCamelCase__: List[str] = F"Input value of [number={number}] must be an integer"
raise TypeError(A_)
if number < 0:
return False
UpperCamelCase__: str = number * number
while number > 0:
if number % 10 != number_square % 10:
return False
number //= 10
number_square //= 10
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
| 716
|
def lowerCAmelCase_ ( A_):
UpperCamelCase__: Union[str, Any] = ""
for ch in key:
if ch == " " or ch not in key_no_dups and ch.isalpha():
key_no_dups += ch
return key_no_dups
def lowerCAmelCase_ ( A_):
UpperCamelCase__: Any = [chr(i + 65) for i in range(26)]
# Remove duplicate characters from key
UpperCamelCase__: Dict = remove_duplicates(key.upper())
UpperCamelCase__: Optional[int] = len(A_)
# First fill cipher with key characters
UpperCamelCase__: Any = {alphabet[i]: char for i, char in enumerate(A_)}
# Then map remaining characters in alphabet to
# the alphabet from the beginning
for i in range(len(A_) ,26):
UpperCamelCase__: List[Any] = alphabet[i - offset]
# Ensure we are not mapping letters to letters previously mapped
while char in key:
offset -= 1
UpperCamelCase__: Any = alphabet[i - offset]
UpperCamelCase__: Tuple = char
return cipher_alphabet
def lowerCAmelCase_ ( A_ ,A_):
return "".join(cipher_map.get(A_ ,A_) for ch in message.upper())
def lowerCAmelCase_ ( A_ ,A_):
UpperCamelCase__: int = {v: k for k, v in cipher_map.items()}
return "".join(rev_cipher_map.get(A_ ,A_) for ch in message.upper())
def lowerCAmelCase_ ( ):
UpperCamelCase__: Union[str, Any] = input("Enter message to encode or decode: ").strip()
UpperCamelCase__: Union[str, Any] = input("Enter keyword: ").strip()
UpperCamelCase__: int = input("Encipher or decipher? E/D:").strip()[0].lower()
try:
UpperCamelCase__: Optional[Any] = {"e": encipher, "d": decipher}[option]
except KeyError:
raise KeyError("invalid input option")
UpperCamelCase__: Optional[Any] = create_cipher_map(A_)
print(func(A_ ,A_))
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 221
| 0
|
'''simple docstring'''
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import GLPNImageProcessor
class a__( unittest.TestCase ):
def __init__( self : Any , __snake_case : int , __snake_case : Tuple=7 , __snake_case : List[Any]=3 , __snake_case : Optional[int]=18 , __snake_case : List[str]=30 , __snake_case : Optional[int]=4_00 , __snake_case : Optional[int]=True , __snake_case : Union[str, Any]=32 , __snake_case : str=True , ):
a : str = parent
a : List[Any] = batch_size
a : List[str] = num_channels
a : Tuple = image_size
a : Tuple = min_resolution
a : Any = max_resolution
a : Any = do_resize
a : Dict = size_divisor
a : List[Any] = do_rescale
def lowercase_ ( self : Optional[int] ):
return {
"do_resize": self.do_resize,
"size_divisor": self.size_divisor,
"do_rescale": self.do_rescale,
}
@require_torch
@require_vision
class a__( lowerCamelCase__ , unittest.TestCase ):
lowercase__ = GLPNImageProcessor if is_vision_available() else None
def lowercase_ ( self : Tuple ):
a : Any = GLPNImageProcessingTester(self )
@property
def lowercase_ ( self : Optional[Any] ):
return self.image_processor_tester.prepare_image_processor_dict()
def lowercase_ ( self : Union[str, Any] ):
a : int = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__snake_case , 'do_resize' ) )
self.assertTrue(hasattr(__snake_case , 'size_divisor' ) )
self.assertTrue(hasattr(__snake_case , 'resample' ) )
self.assertTrue(hasattr(__snake_case , 'do_rescale' ) )
def lowercase_ ( self : Optional[int] ):
pass
def lowercase_ ( self : Union[str, Any] ):
# Initialize image_processing
a : Tuple = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
a : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case )
for image in image_inputs:
self.assertIsInstance(__snake_case , Image.Image )
# Test not batched input (GLPNImageProcessor doesn't support batching)
a : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
def lowercase_ ( self : List[str] ):
# Initialize image_processing
a : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
a : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , numpify=__snake_case )
for image in image_inputs:
self.assertIsInstance(__snake_case , np.ndarray )
# Test not batched input (GLPNImageProcessor doesn't support batching)
a : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
def lowercase_ ( self : str ):
# Initialize image_processing
a : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
a : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , torchify=__snake_case )
for image in image_inputs:
self.assertIsInstance(__snake_case , torch.Tensor )
# Test not batched input (GLPNImageProcessor doesn't support batching)
a : Optional[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
| 526
|
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
lowerCAmelCase: List[str] = logging.get_logger(__name__)
lowerCAmelCase: int = {
'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/config.json',
'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/config.json',
'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/config.json',
'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/config.json',
'bert-base-multilingual-uncased': 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json',
'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json',
'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/config.json',
'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/config.json',
'bert-large-uncased-whole-word-masking': (
'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json'
),
'bert-large-cased-whole-word-masking': (
'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json'
),
'bert-large-uncased-whole-word-masking-finetuned-squad': (
'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json'
),
'bert-large-cased-whole-word-masking-finetuned-squad': (
'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json'
),
'bert-base-cased-finetuned-mrpc': 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json',
'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json',
'bert-base-german-dbmdz-uncased': 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json',
'cl-tohoku/bert-base-japanese': 'https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json',
'cl-tohoku/bert-base-japanese-whole-word-masking': (
'https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json'
),
'cl-tohoku/bert-base-japanese-char': (
'https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json'
),
'cl-tohoku/bert-base-japanese-char-whole-word-masking': (
'https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json'
),
'TurkuNLP/bert-base-finnish-cased-v1': (
'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json'
),
'TurkuNLP/bert-base-finnish-uncased-v1': (
'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json'
),
'wietsedv/bert-base-dutch-cased': 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json',
# See all BERT models at https://huggingface.co/models?filter=bert
}
class a__( lowerCamelCase__ ):
lowercase__ = """bert"""
def __init__( self : List[str] , __snake_case : Optional[Any]=3_05_22 , __snake_case : Any=7_68 , __snake_case : str=12 , __snake_case : Optional[int]=12 , __snake_case : Tuple=30_72 , __snake_case : Optional[Any]="gelu" , __snake_case : Dict=0.1 , __snake_case : Optional[int]=0.1 , __snake_case : List[Any]=5_12 , __snake_case : Optional[Any]=2 , __snake_case : Optional[Any]=0.02 , __snake_case : List[str]=1e-1_2 , __snake_case : Dict=0 , __snake_case : List[str]="absolute" , __snake_case : List[Any]=True , __snake_case : List[str]=None , **__snake_case : Any , ):
super().__init__(pad_token_id=__snake_case , **__snake_case )
a : str = vocab_size
a : List[Any] = hidden_size
a : Union[str, Any] = num_hidden_layers
a : List[Any] = num_attention_heads
a : str = hidden_act
a : str = intermediate_size
a : Tuple = hidden_dropout_prob
a : Union[str, Any] = attention_probs_dropout_prob
a : List[Any] = max_position_embeddings
a : Union[str, Any] = type_vocab_size
a : List[Any] = initializer_range
a : Dict = layer_norm_eps
a : Any = position_embedding_type
a : List[str] = use_cache
a : List[str] = classifier_dropout
class a__( lowerCamelCase__ ):
@property
def lowercase_ ( self : List[str] ):
if self.task == "multiple-choice":
a : Tuple = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
a : List[Any] = {0: 'batch', 1: 'sequence'}
return OrderedDict(
[
('input_ids', dynamic_axis),
('attention_mask', dynamic_axis),
('token_type_ids', dynamic_axis),
] )
| 526
| 1
|
from itertools import permutations
def __lowerCAmelCase ( __lowerCamelCase : tuple ) -> bool:
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
__lowerCAmelCase =[7, 11, 13, 17]
for i, test in enumerate(__lowerCamelCase ):
if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0:
return False
return True
def __lowerCAmelCase ( __lowerCamelCase : int = 10 ) -> int:
return sum(
int("""""".join(map(__lowerCamelCase , __lowerCamelCase ) ) )
for num in permutations(range(__lowerCamelCase ) )
if is_substring_divisible(__lowerCamelCase ) )
if __name__ == "__main__":
print(F"{solution() = }")
| 710
|
import os
import tempfile
from functools import partial
from unittest import TestCase
from unittest.mock import patch
import numpy as np
import pytest
from datasets.arrow_dataset import Dataset
from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex
from .utils import require_elasticsearch, require_faiss
lowercase_ = pytest.mark.integration
@require_faiss
class __a ( SCREAMING_SNAKE_CASE ):
def UpperCamelCase ( self : Optional[int])-> List[Any]:
__lowerCAmelCase =Dataset.from_dict({"""filename""": ["""my_name-train""" + """_""" + str(snake_case_) for x in np.arange(30).tolist()]})
return dset
def UpperCamelCase ( self : Optional[Any])-> str:
import faiss
__lowerCAmelCase =self._create_dummy_dataset()
__lowerCAmelCase =dset.map(
lambda snake_case_ , snake_case_: {"vecs": i * np.ones(5 , dtype=np.floataa)} , with_indices=snake_case_ , keep_in_memory=snake_case_)
__lowerCAmelCase =dset.add_faiss_index("""vecs""" , batch_size=1_00 , metric_type=faiss.METRIC_INNER_PRODUCT)
__lowerCAmelCase , __lowerCAmelCase =dset.get_nearest_examples("""vecs""" , np.ones(5 , dtype=np.floataa))
self.assertEqual(examples["""filename"""][0] , """my_name-train_29""")
dset.drop_index("""vecs""")
def UpperCamelCase ( self : Tuple)-> int:
import faiss
__lowerCAmelCase =self._create_dummy_dataset()
dset.add_faiss_index_from_external_arrays(
external_arrays=np.ones((30, 5)) * np.arange(30).reshape(-1 , 1) , index_name="""vecs""" , batch_size=1_00 , metric_type=faiss.METRIC_INNER_PRODUCT , )
__lowerCAmelCase , __lowerCAmelCase =dset.get_nearest_examples("""vecs""" , np.ones(5 , dtype=np.floataa))
self.assertEqual(examples["""filename"""][0] , """my_name-train_29""")
def UpperCamelCase ( self : int)-> List[str]:
import faiss
__lowerCAmelCase =self._create_dummy_dataset()
dset.add_faiss_index_from_external_arrays(
external_arrays=np.ones((30, 5)) * np.arange(30).reshape(-1 , 1) , index_name="""vecs""" , metric_type=faiss.METRIC_INNER_PRODUCT , )
# Setting delete=False and unlinking manually is not pretty... but it is required on Windows to
# ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue.
# see https://bugs.python.org/issue14243 and
# https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515
with tempfile.NamedTemporaryFile(delete=snake_case_) as tmp_file:
dset.save_faiss_index("""vecs""" , tmp_file.name)
dset.load_faiss_index("""vecs2""" , tmp_file.name)
os.unlink(tmp_file.name)
__lowerCAmelCase , __lowerCAmelCase =dset.get_nearest_examples("""vecs2""" , np.ones(5 , dtype=np.floataa))
self.assertEqual(examples["""filename"""][0] , """my_name-train_29""")
def UpperCamelCase ( self : Any)-> Optional[int]:
__lowerCAmelCase =self._create_dummy_dataset()
dset.add_faiss_index_from_external_arrays(
external_arrays=np.ones((30, 5)) * np.arange(30).reshape(-1 , 1) , index_name="""vecs""")
dset.drop_index("""vecs""")
self.assertRaises(snake_case_ , partial(dset.get_nearest_examples , """vecs2""" , np.ones(5 , dtype=np.floataa)))
def UpperCamelCase ( self : Optional[int])-> List[str]:
from elasticsearch import Elasticsearch
__lowerCAmelCase =self._create_dummy_dataset()
with patch("""elasticsearch.Elasticsearch.search""") as mocked_search, patch(
"""elasticsearch.client.IndicesClient.create""") as mocked_index_create, patch("""elasticsearch.helpers.streaming_bulk""") as mocked_bulk:
__lowerCAmelCase ={"""acknowledged""": True}
mocked_bulk.return_value([(True, None)] * 30)
__lowerCAmelCase ={"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 29}]}}
__lowerCAmelCase =Elasticsearch()
dset.add_elasticsearch_index("""filename""" , es_client=snake_case_)
__lowerCAmelCase , __lowerCAmelCase =dset.get_nearest_examples("""filename""" , """my_name-train_29""")
self.assertEqual(examples["""filename"""][0] , """my_name-train_29""")
@require_faiss
class __a ( SCREAMING_SNAKE_CASE ):
def UpperCamelCase ( self : Dict)-> int:
import faiss
__lowerCAmelCase =FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT)
# add vectors
index.add_vectors(np.eye(5 , dtype=np.floataa))
self.assertIsNotNone(index.faiss_index)
self.assertEqual(index.faiss_index.ntotal , 5)
index.add_vectors(np.zeros((5, 5) , dtype=np.floataa))
self.assertEqual(index.faiss_index.ntotal , 10)
# single query
__lowerCAmelCase =np.zeros(5 , dtype=np.floataa)
__lowerCAmelCase =1
__lowerCAmelCase , __lowerCAmelCase =index.search(snake_case_)
self.assertRaises(snake_case_ , index.search , query.reshape(-1 , 1))
self.assertGreater(scores[0] , 0)
self.assertEqual(indices[0] , 1)
# batched queries
__lowerCAmelCase =np.eye(5 , dtype=np.floataa)[::-1]
__lowerCAmelCase , __lowerCAmelCase =index.search_batch(snake_case_)
self.assertRaises(snake_case_ , index.search_batch , queries[0])
__lowerCAmelCase =[scores[0] for scores in total_scores]
__lowerCAmelCase =[indices[0] for indices in total_indices]
self.assertGreater(np.min(snake_case_) , 0)
self.assertListEqual([4, 3, 2, 1, 0] , snake_case_)
def UpperCamelCase ( self : Optional[Any])-> str:
import faiss
__lowerCAmelCase =FaissIndex(string_factory="""Flat""")
index.add_vectors(np.eye(5 , dtype=np.floataa))
self.assertIsInstance(index.faiss_index , faiss.IndexFlat)
__lowerCAmelCase =FaissIndex(string_factory="""LSH""")
index.add_vectors(np.eye(5 , dtype=np.floataa))
self.assertIsInstance(index.faiss_index , faiss.IndexLSH)
with self.assertRaises(snake_case_):
__lowerCAmelCase =FaissIndex(string_factory="""Flat""" , custom_index=faiss.IndexFlat(5))
def UpperCamelCase ( self : List[str])-> Any:
import faiss
__lowerCAmelCase =faiss.IndexFlat(5)
__lowerCAmelCase =FaissIndex(custom_index=snake_case_)
index.add_vectors(np.eye(5 , dtype=np.floataa))
self.assertIsInstance(index.faiss_index , faiss.IndexFlat)
def UpperCamelCase ( self : str)-> Union[str, Any]:
import faiss
__lowerCAmelCase =FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT)
index.add_vectors(np.eye(5 , dtype=np.floataa))
# Setting delete=False and unlinking manually is not pretty... but it is required on Windows to
# ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue.
# see https://bugs.python.org/issue14243 and
# https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515
with tempfile.NamedTemporaryFile(delete=snake_case_) as tmp_file:
index.save(tmp_file.name)
__lowerCAmelCase =FaissIndex.load(tmp_file.name)
os.unlink(tmp_file.name)
__lowerCAmelCase =np.zeros(5 , dtype=np.floataa)
__lowerCAmelCase =1
__lowerCAmelCase , __lowerCAmelCase =index.search(snake_case_)
self.assertGreater(scores[0] , 0)
self.assertEqual(indices[0] , 1)
@require_faiss
def __lowerCAmelCase ( __lowerCamelCase : Optional[Any] ) -> List[str]:
import faiss
__lowerCAmelCase =FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT )
index.add_vectors(np.eye(5 , dtype=np.floataa ) )
__lowerCAmelCase ="""index.faiss"""
__lowerCAmelCase =f"""mock://{index_name}"""
index.save(__lowerCamelCase , storage_options=mockfs.storage_options )
__lowerCAmelCase =FaissIndex.load(__lowerCamelCase , storage_options=mockfs.storage_options )
__lowerCAmelCase =np.zeros(5 , dtype=np.floataa )
__lowerCAmelCase =1
__lowerCAmelCase , __lowerCAmelCase =index.search(__lowerCamelCase )
assert scores[0] > 0
assert indices[0] == 1
@require_elasticsearch
class __a ( SCREAMING_SNAKE_CASE ):
def UpperCamelCase ( self : List[str])-> Optional[int]:
from elasticsearch import Elasticsearch
with patch("""elasticsearch.Elasticsearch.search""") as mocked_search, patch(
"""elasticsearch.client.IndicesClient.create""") as mocked_index_create, patch("""elasticsearch.helpers.streaming_bulk""") as mocked_bulk:
__lowerCAmelCase =Elasticsearch()
__lowerCAmelCase ={"""acknowledged""": True}
__lowerCAmelCase =ElasticSearchIndex(es_client=snake_case_)
mocked_bulk.return_value([(True, None)] * 3)
index.add_documents(["""foo""", """bar""", """foobar"""])
# single query
__lowerCAmelCase ="""foo"""
__lowerCAmelCase ={"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 0}]}}
__lowerCAmelCase , __lowerCAmelCase =index.search(snake_case_)
self.assertEqual(scores[0] , 1)
self.assertEqual(indices[0] , 0)
# single query with timeout
__lowerCAmelCase ="""foo"""
__lowerCAmelCase ={"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 0}]}}
__lowerCAmelCase , __lowerCAmelCase =index.search(snake_case_ , request_timeout=30)
self.assertEqual(scores[0] , 1)
self.assertEqual(indices[0] , 0)
# batched queries
__lowerCAmelCase =["""foo""", """bar""", """foobar"""]
__lowerCAmelCase ={"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 1}]}}
__lowerCAmelCase , __lowerCAmelCase =index.search_batch(snake_case_)
__lowerCAmelCase =[scores[0] for scores in total_scores]
__lowerCAmelCase =[indices[0] for indices in total_indices]
self.assertGreater(np.min(snake_case_) , 0)
self.assertListEqual([1, 1, 1] , snake_case_)
# batched queries with timeout
__lowerCAmelCase =["""foo""", """bar""", """foobar"""]
__lowerCAmelCase ={"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 1}]}}
__lowerCAmelCase , __lowerCAmelCase =index.search_batch(snake_case_ , request_timeout=30)
__lowerCAmelCase =[scores[0] for scores in total_scores]
__lowerCAmelCase =[indices[0] for indices in total_indices]
self.assertGreater(np.min(snake_case_) , 0)
self.assertListEqual([1, 1, 1] , snake_case_)
| 456
| 0
|
'''simple docstring'''
from __future__ import annotations
from cmath import sqrt
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> tuple[complex, complex]:
if a == 0:
raise ValueError("Coefficient 'a' must not be zero." )
__snake_case = b * b - 4 * a * c
__snake_case = (-b + sqrt(lowercase__ )) / (2 * a)
__snake_case = (-b - sqrt(lowercase__ )) / (2 * a)
return (
root_a.real if not root_a.imag else root_a,
root_a.real if not root_a.imag else root_a,
)
def __UpperCAmelCase ( ) -> Tuple:
__snake_case = quadratic_roots(a=5 , b=6 , c=1 )
print(F'''The solutions are: {solutiona} and {solutiona}''' )
if __name__ == "__main__":
main()
| 69
|
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_big_bird import BigBirdTokenizer
else:
__UpperCAmelCase = None
__UpperCAmelCase = logging.get_logger(__name__)
__UpperCAmelCase = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'}
__UpperCAmelCase = {
'vocab_file': {
'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model',
'google/bigbird-roberta-large': (
'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model'
),
'google/bigbird-base-trivia-itc': (
'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model'
),
},
'tokenizer_file': {
'google/bigbird-roberta-base': (
'https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json'
),
'google/bigbird-roberta-large': (
'https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json'
),
'google/bigbird-base-trivia-itc': (
'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json'
),
},
}
__UpperCAmelCase = {
'google/bigbird-roberta-base': 40_96,
'google/bigbird-roberta-large': 40_96,
'google/bigbird-base-trivia-itc': 40_96,
}
__UpperCAmelCase = '▁'
class __a ( __UpperCamelCase ):
__snake_case : int = VOCAB_FILES_NAMES
__snake_case : int = PRETRAINED_VOCAB_FILES_MAP
__snake_case : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__snake_case : Optional[Any] = BigBirdTokenizer
__snake_case : Any = ["""input_ids""", """attention_mask"""]
__snake_case : List[int] = []
def __init__( self : str , UpperCAmelCase : Dict=None , UpperCAmelCase : Optional[int]=None , UpperCAmelCase : List[Any]="<unk>" , UpperCAmelCase : Optional[int]="<s>" , UpperCAmelCase : List[str]="</s>" , UpperCAmelCase : List[Any]="<pad>" , UpperCAmelCase : str="[SEP]" , UpperCAmelCase : str="[MASK]" , UpperCAmelCase : Any="[CLS]" , **UpperCAmelCase : List[str] , ):
lowerCAmelCase_ : int = AddedToken(UpperCAmelCase , lstrip=UpperCAmelCase , rstrip=UpperCAmelCase ) if isinstance(UpperCAmelCase , UpperCAmelCase ) else bos_token
lowerCAmelCase_ : Optional[int] = AddedToken(UpperCAmelCase , lstrip=UpperCAmelCase , rstrip=UpperCAmelCase ) if isinstance(UpperCAmelCase , UpperCAmelCase ) else eos_token
lowerCAmelCase_ : int = AddedToken(UpperCAmelCase , lstrip=UpperCAmelCase , rstrip=UpperCAmelCase ) if isinstance(UpperCAmelCase , UpperCAmelCase ) else unk_token
lowerCAmelCase_ : str = AddedToken(UpperCAmelCase , lstrip=UpperCAmelCase , rstrip=UpperCAmelCase ) if isinstance(UpperCAmelCase , UpperCAmelCase ) else pad_token
lowerCAmelCase_ : Tuple = AddedToken(UpperCAmelCase , lstrip=UpperCAmelCase , rstrip=UpperCAmelCase ) if isinstance(UpperCAmelCase , UpperCAmelCase ) else cls_token
lowerCAmelCase_ : Tuple = AddedToken(UpperCAmelCase , lstrip=UpperCAmelCase , rstrip=UpperCAmelCase ) if isinstance(UpperCAmelCase , UpperCAmelCase ) else sep_token
# Mask token behave like a normal word, i.e. include the space before it
lowerCAmelCase_ : List[Any] = AddedToken(UpperCAmelCase , lstrip=UpperCAmelCase , rstrip=UpperCAmelCase ) if isinstance(UpperCAmelCase , UpperCAmelCase ) else mask_token
super().__init__(
UpperCAmelCase , tokenizer_file=UpperCAmelCase , bos_token=UpperCAmelCase , eos_token=UpperCAmelCase , unk_token=UpperCAmelCase , sep_token=UpperCAmelCase , pad_token=UpperCAmelCase , cls_token=UpperCAmelCase , mask_token=UpperCAmelCase , **UpperCAmelCase , )
lowerCAmelCase_ : Union[str, Any] = vocab_file
lowerCAmelCase_ : Union[str, Any] = False if not self.vocab_file else True
def A ( self : Optional[Any] , UpperCAmelCase : List[int] , UpperCAmelCase : Optional[List[int]] = None ):
lowerCAmelCase_ : Tuple = [self.sep_token_id]
lowerCAmelCase_ : Optional[Any] = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def A ( self : Tuple , UpperCAmelCase : List[int] , UpperCAmelCase : Optional[List[int]] = None , UpperCAmelCase : bool = False ):
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
"""You should not supply a second sequence if the provided sequence of """
"""ids is already formatted with special tokens for the model.""" )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is None:
return [1] + ([0] * len(UpperCAmelCase )) + [1]
return [1] + ([0] * len(UpperCAmelCase )) + [1] + ([0] * len(UpperCAmelCase )) + [1]
def A ( self : Union[str, Any] , UpperCAmelCase : List[int] , UpperCAmelCase : Optional[List[int]] = None ):
lowerCAmelCase_ : Optional[Any] = [self.sep_token_id]
lowerCAmelCase_ : Any = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def A ( self : Dict , UpperCAmelCase : str , UpperCAmelCase : Optional[str] = None ):
if not self.can_save_slow_tokenizer:
raise ValueError(
"""Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
"""tokenizer.""" )
if not os.path.isdir(UpperCAmelCase ):
logger.error(F'Vocabulary path ({save_directory}) should be a directory' )
return
lowerCAmelCase_ : 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 ):
copyfile(self.vocab_file , UpperCAmelCase )
return (out_vocab_file,)
| 600
| 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 A_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[Any]:
"""simple docstring"""
__A : Any = checkpoints.load_tax_checkpoint(__SCREAMING_SNAKE_CASE )
__A : Optional[Any] = flatten_dict(__SCREAMING_SNAKE_CASE )
return flax_params
def A_ ( __SCREAMING_SNAKE_CASE : int ) -> str:
"""simple docstring"""
__A : Any = {}
__A : str = {
"""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""",
}
__A : List[str] = {
"""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
__A : Optional[Any] = """.""".join(key[1:] )
# rename the key
for old, new in CONVERSION_MAPPING.items():
__A : Optional[int] = new_key.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
if "decoder" in new_key:
for old, new in DECODER_CONVERSION_MAPPING.items():
__A : Optional[Any] = new_key.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
if "layers" in new_key and "decoder" not in new_key:
# use regex to replace the layer number
__A : List[Any] = re.sub(R"""layers_(\d+)""" , R"""layer.\1""" , __SCREAMING_SNAKE_CASE )
__A : Tuple = new_key.replace("""encoder""" , """encoder.encoder""" )
elif "layers" in new_key and "decoder" in new_key:
# use regex to replace the layer number
__A : Union[str, Any] = re.sub(R"""layers_(\d+)""" , R"""layer.\1""" , __SCREAMING_SNAKE_CASE )
__A : Optional[Any] = flax_dict[key]
__A : Optional[Any] = {}
# convert converted_dict into torch format
for key in converted_dict.keys():
if ("embed_tokens" not in key) and ("embedder" not in key):
__A : Tuple = torch.from_numpy(converted_dict[key].T )
else:
__A : Dict = torch.from_numpy(converted_dict[key] )
return converted_torch_dict
def A_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[Any]=False , __SCREAMING_SNAKE_CASE : List[str]=False ) -> str:
"""simple docstring"""
__A : Any = get_flax_param(__SCREAMING_SNAKE_CASE )
if not use_large:
__A : List[Any] = PixaStructVisionConfig()
__A : Tuple = PixaStructTextConfig()
else:
__A : Any = PixaStructVisionConfig(
hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 )
__A : Any = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 )
__A : Dict = PixaStructConfig(
vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=__SCREAMING_SNAKE_CASE )
__A : Tuple = PixaStructForConditionalGeneration(__SCREAMING_SNAKE_CASE )
__A : Optional[int] = rename_and_convert_flax_params(__SCREAMING_SNAKE_CASE )
model.load_state_dict(__SCREAMING_SNAKE_CASE )
__A : Dict = AutoTokenizer.from_pretrained("""ybelkada/test-pix2struct-tokenizer""" )
__A : Union[str, Any] = PixaStructImageProcessor()
__A : Dict = PixaStructProcessor(image_processor=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE )
if use_large:
__A : List[Any] = 4096
__A : Optional[Any] = True
# mkdir if needed
os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE )
model.save_pretrained(__SCREAMING_SNAKE_CASE )
processor.save_pretrained(__SCREAMING_SNAKE_CASE )
print("""Model saved in {}""".format(__SCREAMING_SNAKE_CASE ) )
if __name__ == "__main__":
A__ : Dict =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__ : str =parser.parse_args()
convert_pixastruct_original_pytorch_checkpoint_to_hf(
args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large
)
| 499
|
'''simple docstring'''
from typing import Union
from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging
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_VISUAL_QUESTION_ANSWERING_MAPPING
A__ : Any =logging.get_logger(__name__)
@add_end_docstrings(_SCREAMING_SNAKE_CASE )
class __A ( _SCREAMING_SNAKE_CASE ):
def __init__( self : Union[str, Any] , *lowerCamelCase : int , **lowerCamelCase : Optional[int] ):
"""simple docstring"""
super().__init__(*lowerCamelCase , **lowerCamelCase )
self.check_model_type(lowerCamelCase )
def lowercase_( self : Any , lowerCamelCase : Dict=None , lowerCamelCase : Union[str, Any]=None , lowerCamelCase : int=None , **lowerCamelCase : int ):
"""simple docstring"""
__A , __A : Tuple = {}, {}
if padding is not None:
__A : Any = padding
if truncation is not None:
__A : Optional[Any] = truncation
if top_k is not None:
__A : List[str] = top_k
return preprocess_params, {}, postprocess_params
def __call__( self : Any , lowerCamelCase : Union["Image.Image", str] , lowerCamelCase : str = None , **lowerCamelCase : Tuple ):
"""simple docstring"""
if isinstance(lowerCamelCase , (Image.Image, str) ) and isinstance(lowerCamelCase , lowerCamelCase ):
__A : Tuple = {"""image""": image, """question""": question}
else:
__A : List[Any] = image
__A : Any = super().__call__(lowerCamelCase , **lowerCamelCase )
return results
def lowercase_( self : int , lowerCamelCase : Optional[int] , lowerCamelCase : Dict=False , lowerCamelCase : str=False ):
"""simple docstring"""
__A : List[str] = load_image(inputs["""image"""] )
__A : Optional[Any] = self.tokenizer(
inputs["""question"""] , return_tensors=self.framework , padding=lowerCamelCase , truncation=lowerCamelCase )
__A : Union[str, Any] = self.image_processor(images=lowerCamelCase , return_tensors=self.framework )
model_inputs.update(lowerCamelCase )
return model_inputs
def lowercase_( self : List[str] , lowerCamelCase : Tuple ):
"""simple docstring"""
__A : List[str] = self.model(**lowerCamelCase )
return model_outputs
def lowercase_( self : str , lowerCamelCase : Optional[Any] , lowerCamelCase : List[Any]=5 ):
"""simple docstring"""
if top_k > self.model.config.num_labels:
__A : str = self.model.config.num_labels
if self.framework == "pt":
__A : Optional[Any] = model_outputs.logits.sigmoid()[0]
__A , __A : int = probs.topk(lowerCamelCase )
else:
raise ValueError(f"Unsupported framework: {self.framework}" )
__A : Optional[Any] = scores.tolist()
__A : Dict = ids.tolist()
return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(lowerCamelCase , lowerCamelCase )]
| 499
| 1
|
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
_A: Optional[Any] = {"""configuration_yolos""": ["""YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """YolosConfig""", """YolosOnnxConfig"""]}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_A: Optional[Any] = ["""YolosFeatureExtractor"""]
_A: Union[str, Any] = ["""YolosImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_A: List[Any] = [
"""YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""YolosForObjectDetection""",
"""YolosModel""",
"""YolosPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_yolos import YolosFeatureExtractor
from .image_processing_yolos import YolosImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_yolos import (
YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST,
YolosForObjectDetection,
YolosModel,
YolosPreTrainedModel,
)
else:
import sys
_A: Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 126
|
'''simple docstring'''
import warnings
from typing import Dict
import numpy as np
from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline
if is_tf_available():
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
def _lowerCAmelCase ( _lowerCAmelCase )-> Optional[Any]:
return 1.0 / (1.0 + np.exp(-_outputs ))
def _lowerCAmelCase ( _lowerCAmelCase )-> str:
__UpperCAmelCase = np.max(_outputs , axis=-1 , keepdims=_lowerCAmelCase )
__UpperCAmelCase = np.exp(_outputs - maxes )
return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_lowerCAmelCase )
class UpperCAmelCase ( UpperCAmelCase_ ):
_A : List[str] = """sigmoid"""
_A : Optional[Any] = """softmax"""
_A : Optional[int] = """none"""
@add_end_docstrings(
UpperCAmelCase_ , R"""
return_all_scores (`bool`, *optional*, defaults to `False`):
Whether to return all prediction scores or just the one of the predicted class.
function_to_apply (`str`, *optional*, defaults to `\"default\"`):
The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:
- `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model
has several labels, will apply the softmax function on the output.
- `\"sigmoid\"`: Applies the sigmoid function on the output.
- `\"softmax\"`: Applies the softmax function on the output.
- `\"none\"`: Does not apply any function on the output.
""" , )
class UpperCAmelCase ( UpperCAmelCase_ ):
_A : Dict = False
_A : Optional[int] = ClassificationFunction.NONE
def __init__( self , **__A ):
super().__init__(**__A )
self.check_model_type(
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
if self.framework == 'tf'
else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING )
def __lowerCamelCase ( self , __A=None , __A=None , __A="" , **__A ):
# Using "" as default argument because we're going to use `top_k=None` in user code to declare
# "No top_k"
__UpperCAmelCase = tokenizer_kwargs
__UpperCAmelCase = {}
if hasattr(self.model.config , 'return_all_scores' ) and return_all_scores is None:
__UpperCAmelCase = self.model.config.return_all_scores
if isinstance(__A , __A ) or top_k is None:
__UpperCAmelCase = top_k
__UpperCAmelCase = False
elif return_all_scores is not None:
warnings.warn(
'`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of'
' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , __A , )
if return_all_scores:
__UpperCAmelCase = None
else:
__UpperCAmelCase = 1
if isinstance(__A , __A ):
__UpperCAmelCase = ClassificationFunction[function_to_apply.upper()]
if function_to_apply is not None:
__UpperCAmelCase = function_to_apply
return preprocess_params, {}, postprocess_params
def __call__( self , *__A , **__A ):
__UpperCAmelCase = super().__call__(*__A , **__A )
# TODO try and retrieve it in a nicer way from _sanitize_parameters.
__UpperCAmelCase = 'top_k' not in kwargs
if isinstance(args[0] , __A ) and _legacy:
# This pipeline is odd, and return a list when single item is run
return [result]
else:
return result
def __lowerCamelCase ( self , __A , **__A ):
__UpperCAmelCase = self.framework
if isinstance(__A , __A ):
return self.tokenizer(**__A , return_tensors=__A , **__A )
elif isinstance(__A , __A ) and len(__A ) == 1 and isinstance(inputs[0] , __A ) and len(inputs[0] ) == 2:
# It used to be valid to use a list of list of list for text pairs, keeping this path for BC
return self.tokenizer(
text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=__A , **__A )
elif isinstance(__A , __A ):
# This is likely an invalid usage of the pipeline attempting to pass text pairs.
raise ValueError(
'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'
' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' )
return self.tokenizer(__A , return_tensors=__A , **__A )
def __lowerCamelCase ( self , __A ):
return self.model(**__A )
def __lowerCamelCase ( self , __A , __A=None , __A=1 , __A=True ):
# `_legacy` is used to determine if we're running the naked pipeline and in backward
# compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
# the more natural result containing the list.
# Default value before `set_parameters`
if function_to_apply is None:
if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
__UpperCAmelCase = ClassificationFunction.SIGMOID
elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
__UpperCAmelCase = ClassificationFunction.SOFTMAX
elif hasattr(self.model.config , 'function_to_apply' ) and function_to_apply is None:
__UpperCAmelCase = self.model.config.function_to_apply
else:
__UpperCAmelCase = ClassificationFunction.NONE
__UpperCAmelCase = model_outputs['logits'][0]
__UpperCAmelCase = outputs.numpy()
if function_to_apply == ClassificationFunction.SIGMOID:
__UpperCAmelCase = sigmoid(__A )
elif function_to_apply == ClassificationFunction.SOFTMAX:
__UpperCAmelCase = softmax(__A )
elif function_to_apply == ClassificationFunction.NONE:
__UpperCAmelCase = outputs
else:
raise ValueError(f'Unrecognized `function_to_apply` argument: {function_to_apply}' )
if top_k == 1 and _legacy:
return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}
__UpperCAmelCase = [
{'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__A )
]
if not _legacy:
dict_scores.sort(key=lambda __A : x["score"] , reverse=__A )
if top_k is not None:
__UpperCAmelCase = dict_scores[:top_k]
return dict_scores
| 126
| 1
|
'''simple docstring'''
import sacrebleu as scb
from packaging import version
from sacrebleu import TER
import datasets
_lowerCAmelCase :List[str] = """\
@inproceedings{snover-etal-2006-study,
title = \"A Study of Translation Edit Rate with Targeted Human Annotation\",
author = \"Snover, Matthew and
Dorr, Bonnie and
Schwartz, Rich and
Micciulla, Linnea and
Makhoul, John\",
booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\",
month = aug # \" 8-12\",
year = \"2006\",
address = \"Cambridge, Massachusetts, USA\",
publisher = \"Association for Machine Translation in the Americas\",
url = \"https://aclanthology.org/2006.amta-papers.25\",
pages = \"223--231\",
}
@inproceedings{post-2018-call,
title = \"A Call for Clarity in Reporting {BLEU} Scores\",
author = \"Post, Matt\",
booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",
month = oct,
year = \"2018\",
address = \"Belgium, Brussels\",
publisher = \"Association for Computational Linguistics\",
url = \"https://www.aclweb.org/anthology/W18-6319\",
pages = \"186--191\",
}
"""
_lowerCAmelCase :Dict = """\
TER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a
hypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu
(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found
here: https://github.com/jhclark/tercom.
The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534
See the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.
"""
_lowerCAmelCase :Optional[Any] = """
Produces TER scores alongside the number of edits and reference length.
Args:
predictions (list of str): The system stream (a sequence of segments).
references (list of list of str): A list of one or more reference streams (each a sequence of segments).
normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,
as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.
Only applies if `normalized = True`. Defaults to `False`.
case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.
Returns:
'score' (float): TER score (num_edits / sum_ref_lengths * 100)
'num_edits' (int): The cumulative number of edits
'ref_length' (float): The cumulative average reference length
Examples:
Example 1:
>>> predictions = [\"does this sentence match??\",
... \"what about this sentence?\",
... \"What did the TER metric user say to the developer?\"]
>>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],
... [\"Your jokes are...\", \"...TERrible\"]]
>>> ter = datasets.load_metric(\"ter\")
>>> results = ter.compute(predictions=predictions,
... references=references,
... case_sensitive=True)
>>> print(results)
{'score': 150.0, 'num_edits': 15, 'ref_length': 10.0}
Example 2:
>>> predictions = [\"does this sentence match??\",
... \"what about this sentence?\"]
>>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
>>> ter = datasets.load_metric(\"ter\")
>>> results = ter.compute(predictions=predictions,
... references=references,
... case_sensitive=True)
>>> print(results)
{'score': 62.5, 'num_edits': 5, 'ref_length': 8.0}
Example 3:
>>> predictions = [\"does this sentence match??\",
... \"what about this sentence?\"]
>>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
>>> ter = datasets.load_metric(\"ter\")
>>> results = ter.compute(predictions=predictions,
... references=references,
... normalized=True,
... case_sensitive=True)
>>> print(results)
{'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5}
Example 4:
>>> predictions = [\"does this sentence match??\",
... \"what about this sentence?\"]
>>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
>>> ter = datasets.load_metric(\"ter\")
>>> results = ter.compute(predictions=predictions,
... references=references,
... ignore_punct=True,
... case_sensitive=False)
>>> print(results)
{'score': 0.0, 'num_edits': 0, 'ref_length': 8.0}
Example 5:
>>> predictions = [\"does this sentence match??\",
... \"what about this sentence?\",
... \"What did the TER metric user say to the developer?\"]
>>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],
... [\"Your jokes are...\", \"...TERrible\"]]
>>> ter = datasets.load_metric(\"ter\")
>>> results = ter.compute(predictions=predictions,
... references=references,
... ignore_punct=True,
... case_sensitive=False)
>>> print(results)
{'score': 100.0, 'num_edits': 10, 'ref_length': 10.0}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class UpperCAmelCase ( datasets.Metric ):
'''simple docstring'''
def _UpperCamelCase ( self ) -> Optional[int]:
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='http://www.cs.umd.edu/~snover/tercom/' , 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#ter'] , reference_urls=[
'https://github.com/jhclark/tercom',
] , )
def _UpperCamelCase ( self , lowercase__ , lowercase__ , lowercase__ = False , lowercase__ = False , lowercase__ = False , lowercase__ = False , ) -> List[Any]:
SCREAMING_SNAKE_CASE : List[str] = len(references[0] )
if any(len(lowercase__ ) != references_per_prediction for refs in references ):
raise ValueError('Sacrebleu requires the same number of references for each prediction' )
SCREAMING_SNAKE_CASE : List[str] = [[refs[i] for refs in references] for i in range(lowercase__ )]
SCREAMING_SNAKE_CASE : List[Any] = TER(
normalized=lowercase__ , no_punct=lowercase__ , asian_support=lowercase__ , case_sensitive=lowercase__ , )
SCREAMING_SNAKE_CASE : int = sb_ter.corpus_score(lowercase__ , lowercase__ )
return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
| 179
|
'''simple docstring'''
import warnings
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
_lowerCAmelCase :str = logging.get_logger(__name__)
_lowerCAmelCase :Optional[int] = {
"""nvidia/segformer-b0-finetuned-ade-512-512""": (
"""https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json"""
),
# See all SegFormer models at https://huggingface.co/models?filter=segformer
}
class UpperCAmelCase ( _SCREAMING_SNAKE_CASE ):
'''simple docstring'''
snake_case__ : Optional[int] = "segformer"
def __init__( self , lowercase__=3 , lowercase__=4 , lowercase__=[2, 2, 2, 2] , lowercase__=[8, 4, 2, 1] , lowercase__=[32, 64, 160, 256] , lowercase__=[7, 3, 3, 3] , lowercase__=[4, 2, 2, 2] , lowercase__=[1, 2, 5, 8] , lowercase__=[4, 4, 4, 4] , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.1 , lowercase__=0.0_2 , lowercase__=0.1 , lowercase__=1E-6 , lowercase__=256 , lowercase__=255 , **lowercase__ , ) -> Union[str, Any]:
super().__init__(**lowercase__ )
if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
warnings.warn(
'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be'
' removed, as the behaviour will default to that of reshape_last_stage = True.' , lowercase__ , )
SCREAMING_SNAKE_CASE : int = num_channels
SCREAMING_SNAKE_CASE : int = num_encoder_blocks
SCREAMING_SNAKE_CASE : List[Any] = depths
SCREAMING_SNAKE_CASE : Union[str, Any] = sr_ratios
SCREAMING_SNAKE_CASE : List[Any] = hidden_sizes
SCREAMING_SNAKE_CASE : Union[str, Any] = patch_sizes
SCREAMING_SNAKE_CASE : int = strides
SCREAMING_SNAKE_CASE : Tuple = mlp_ratios
SCREAMING_SNAKE_CASE : List[str] = num_attention_heads
SCREAMING_SNAKE_CASE : List[str] = hidden_act
SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob
SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE : Tuple = classifier_dropout_prob
SCREAMING_SNAKE_CASE : Any = initializer_range
SCREAMING_SNAKE_CASE : Optional[int] = drop_path_rate
SCREAMING_SNAKE_CASE : int = layer_norm_eps
SCREAMING_SNAKE_CASE : Any = decoder_hidden_size
SCREAMING_SNAKE_CASE : List[str] = kwargs.get('reshape_last_stage' , lowercase__ )
SCREAMING_SNAKE_CASE : Optional[Any] = semantic_loss_ignore_index
class UpperCAmelCase ( _SCREAMING_SNAKE_CASE ):
'''simple docstring'''
snake_case__ : Tuple = version.parse("1.11" )
@property
def _UpperCamelCase ( self ) -> Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
] )
@property
def _UpperCamelCase ( self ) -> float:
return 1E-4
@property
def _UpperCamelCase ( self ) -> int:
return 12
| 179
| 1
|
'''simple docstring'''
import inspect
import unittest
from transformers import DecisionTransformerConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import DecisionTransformerModel
from transformers.models.decision_transformer.modeling_decision_transformer import (
DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
class lowerCAmelCase__ :
"""simple docstring"""
def __init__( self : int , A__ : Optional[Any] , A__ : Optional[int]=1_3 , A__ : int=7 , A__ : int=6 , A__ : List[Any]=1_7 , A__ : Tuple=2_3 , A__ : int=1_1 , A__ : Union[str, Any]=True , ) -> Tuple:
'''simple docstring'''
a__ : List[str] = parent
a__ : Dict = batch_size
a__ : List[Any] = seq_length
a__ : Any = act_dim
a__ : Dict = state_dim
a__ : Any = hidden_size
a__ : List[Any] = max_length
a__ : Optional[Any] = is_training
def __lowerCAmelCase ( self : Optional[Any] ) -> List[str]:
'''simple docstring'''
a__ : Union[str, Any] = floats_tensor((self.batch_size, self.seq_length, self.state_dim) )
a__ : Any = floats_tensor((self.batch_size, self.seq_length, self.act_dim) )
a__ : Tuple = floats_tensor((self.batch_size, self.seq_length, 1) )
a__ : Optional[int] = floats_tensor((self.batch_size, self.seq_length, 1) )
a__ : Optional[Any] = ids_tensor((self.batch_size, self.seq_length) , vocab_size=1_0_0_0 )
a__ : List[str] = random_attention_mask((self.batch_size, self.seq_length) )
a__ : Any = self.get_config()
return (
config,
states,
actions,
rewards,
returns_to_go,
timesteps,
attention_mask,
)
def __lowerCAmelCase ( self : Optional[int] ) -> Tuple:
'''simple docstring'''
return DecisionTransformerConfig(
batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , )
def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , A__ : Optional[int] , A__ : Tuple , A__ : List[str] , A__ : str , A__ : List[str] , A__ : Any , ) -> str:
'''simple docstring'''
a__ : Dict = DecisionTransformerModel(config=A__ )
model.to(A__ )
model.eval()
a__ : List[str] = model(A__ , A__ , A__ , A__ , A__ , A__ )
self.parent.assertEqual(result.state_preds.shape , states.shape )
self.parent.assertEqual(result.action_preds.shape , actions.shape )
self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape )
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions
def __lowerCAmelCase ( self : Union[str, Any] ) -> List[Any]:
'''simple docstring'''
a__ : Any = self.prepare_config_and_inputs()
(
(
a__
) , (
a__
) , (
a__
) , (
a__
) , (
a__
) , (
a__
) , (
a__
) ,
) : List[Any] = config_and_inputs
a__ : Tuple = {
'''states''': states,
'''actions''': actions,
'''rewards''': rewards,
'''returns_to_go''': returns_to_go,
'''timesteps''': timesteps,
'''attention_mask''': attention_mask,
}
return config, inputs_dict
@require_torch
class lowerCAmelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ):
"""simple docstring"""
__UpperCamelCase = (DecisionTransformerModel,) if is_torch_available() else ()
__UpperCamelCase = ()
__UpperCamelCase = {"feature-extraction": DecisionTransformerModel} if is_torch_available() else {}
# Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids
__UpperCamelCase = False
# Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features
__UpperCamelCase = False
__UpperCamelCase = False
__UpperCamelCase = False
__UpperCamelCase = False
__UpperCamelCase = False
__UpperCamelCase = False
__UpperCamelCase = False
__UpperCamelCase = False
__UpperCamelCase = False
def __lowerCAmelCase ( self : List[Any] ) -> List[Any]:
'''simple docstring'''
a__ : Tuple = DecisionTransformerModelTester(self )
a__ : List[str] = ConfigTester(self , config_class=A__ , hidden_size=3_7 )
def __lowerCAmelCase ( self : int ) -> Dict:
'''simple docstring'''
self.config_tester.run_common_tests()
def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]:
'''simple docstring'''
a__ : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*A__ )
@slow
def __lowerCAmelCase ( self : str ) -> int:
'''simple docstring'''
for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
a__ : Tuple = DecisionTransformerModel.from_pretrained(A__ )
self.assertIsNotNone(A__ )
def __lowerCAmelCase ( self : Tuple ) -> int:
'''simple docstring'''
a__ , a__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a__ : List[Any] = model_class(A__ )
a__ : List[str] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
a__ : Optional[int] = [*signature.parameters.keys()]
a__ : Tuple = [
'''states''',
'''actions''',
'''rewards''',
'''returns_to_go''',
'''timesteps''',
'''attention_mask''',
]
self.assertListEqual(arg_names[: len(A__ )] , A__ )
@require_torch
class lowerCAmelCase__ ( unittest.TestCase ):
"""simple docstring"""
@slow
def __lowerCAmelCase ( self : List[Any] ) -> Optional[Any]:
'''simple docstring'''
a__ : Any = 2 # number of steps of autoregressive prediction we will perform
a__ : List[Any] = 1_0 # defined by the RL environment, may be normalized
a__ : Any = DecisionTransformerModel.from_pretrained('''edbeeching/decision-transformer-gym-hopper-expert''' )
a__ : Dict = model.to(A__ )
a__ : Tuple = model.config
torch.manual_seed(0 )
a__ : Union[str, Any] = torch.randn(1 , 1 , config.state_dim ).to(device=A__ , dtype=torch.floataa ) # env.reset()
a__ : Dict = torch.tensor(
[[0.242_793, -0.28_693_074, 0.8_742_613], [0.67_815_274, -0.08_101_085, -0.12_952_147]] , device=A__ )
a__ : Tuple = torch.tensor(A__ , device=A__ , dtype=torch.floataa ).reshape(1 , 1 , 1 )
a__ : Dict = state
a__ : List[str] = torch.zeros(1 , 0 , config.act_dim , device=A__ , dtype=torch.floataa )
a__ : str = torch.zeros(1 , 0 , device=A__ , dtype=torch.floataa )
a__ : List[Any] = torch.tensor(0 , device=A__ , dtype=torch.long ).reshape(1 , 1 )
for step in range(A__ ):
a__ : List[str] = torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=A__ )] , dim=1 )
a__ : Optional[int] = torch.cat([rewards, torch.zeros(1 , 1 , device=A__ )] , dim=1 )
a__ : int = torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device )
with torch.no_grad():
a__ , a__ , a__ : Optional[Any] = model(
states=A__ , actions=A__ , rewards=A__ , returns_to_go=A__ , timesteps=A__ , attention_mask=A__ , return_dict=A__ , )
self.assertEqual(action_pred.shape , actions.shape )
self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1E-4 ) )
a__ , a__ , a__ , a__ : int = ( # env.step(action)
torch.randn(1 , 1 , config.state_dim ).to(device=A__ , dtype=torch.floataa ),
1.0,
False,
{},
)
a__ : int = action_pred[0, -1]
a__ : Optional[Any] = torch.cat([states, state] , dim=1 )
a__ : Optional[Any] = returns_to_go[0, -1] - reward
a__ : Optional[int] = torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 )
a__ : Union[str, Any] = torch.cat(
[timesteps, torch.ones((1, 1) , device=A__ , dtype=torch.long ) * (step + 1)] , dim=1 )
| 688
|
'''simple docstring'''
import json
import sys
import tempfile
import unittest
from pathlib import Path
import transformers
from transformers import (
CONFIG_MAPPING,
IMAGE_PROCESSOR_MAPPING,
AutoConfig,
AutoImageProcessor,
CLIPConfig,
CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER
sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))
from test_module.custom_configuration import CustomConfig # noqa E402
from test_module.custom_image_processing import CustomImageProcessor # noqa E402
class lowerCAmelCase__ ( unittest.TestCase ):
"""simple docstring"""
def __lowerCAmelCase ( self : Optional[int] ) -> int:
'''simple docstring'''
a__ : int = 0
def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple:
'''simple docstring'''
a__ : Optional[int] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' )
self.assertIsInstance(A__ , A__ )
def __lowerCAmelCase ( self : Dict ) -> int:
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmpdirname:
a__ : List[Any] = Path(A__ ) / '''preprocessor_config.json'''
a__ : List[Any] = Path(A__ ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) )
a__ : Any = AutoImageProcessor.from_pretrained(A__ )
self.assertIsInstance(A__ , A__ )
def __lowerCAmelCase ( self : str ) -> Union[str, Any]:
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmpdirname:
a__ : int = Path(A__ ) / '''preprocessor_config.json'''
a__ : Optional[Any] = Path(A__ ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) )
a__ : Tuple = AutoImageProcessor.from_pretrained(A__ )
self.assertIsInstance(A__ , A__ )
def __lowerCAmelCase ( self : List[Any] ) -> List[Any]:
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmpdirname:
a__ : Dict = CLIPConfig()
# Create a dummy config file with image_proceesor_type
a__ : int = Path(A__ ) / '''preprocessor_config.json'''
a__ : Optional[int] = Path(A__ ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) )
# remove image_processor_type to make sure config.json alone is enough to load image processor locally
a__ : List[Any] = AutoImageProcessor.from_pretrained(A__ ).to_dict()
config_dict.pop('''image_processor_type''' )
a__ : Union[str, Any] = CLIPImageProcessor(**A__ )
# save in new folder
model_config.save_pretrained(A__ )
config.save_pretrained(A__ )
a__ : Union[str, Any] = AutoImageProcessor.from_pretrained(A__ )
# make sure private variable is not incorrectly saved
a__ : Optional[Any] = json.loads(config.to_json_string() )
self.assertTrue('''_processor_class''' not in dict_as_saved )
self.assertIsInstance(A__ , A__ )
def __lowerCAmelCase ( self : str ) -> List[Any]:
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmpdirname:
a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , )
a__ : Any = AutoImageProcessor.from_pretrained(A__ )
self.assertIsInstance(A__ , A__ )
def __lowerCAmelCase ( self : str ) -> Optional[Any]:
'''simple docstring'''
with self.assertRaisesRegex(
A__ , '''clip-base is not a local folder and is not a valid model identifier''' ):
a__ : str = AutoImageProcessor.from_pretrained('''clip-base''' )
def __lowerCAmelCase ( self : Optional[Any] ) -> int:
'''simple docstring'''
with self.assertRaisesRegex(
A__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ):
a__ : Tuple = AutoImageProcessor.from_pretrained(A__ , revision='''aaaaaa''' )
def __lowerCAmelCase ( self : str ) -> List[Any]:
'''simple docstring'''
with self.assertRaisesRegex(
A__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ):
a__ : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' )
def __lowerCAmelCase ( self : List[Any] ) -> Tuple:
'''simple docstring'''
with self.assertRaises(A__ ):
a__ : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' )
# If remote code is disabled, we can't load this config.
with self.assertRaises(A__ ):
a__ : Tuple = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ )
a__ : Tuple = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
# Test image processor can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(A__ )
a__ : str = AutoImageProcessor.from_pretrained(A__ , trust_remote_code=A__ )
self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' )
def __lowerCAmelCase ( self : List[Any] ) -> Dict:
'''simple docstring'''
try:
AutoConfig.register('''custom''' , A__ )
AutoImageProcessor.register(A__ , A__ )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(A__ ):
AutoImageProcessor.register(A__ , A__ )
with tempfile.TemporaryDirectory() as tmpdirname:
a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json'''
a__ : List[str] = Path(A__ ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) )
a__ : Tuple = CustomImageProcessor.from_pretrained(A__ )
# Now that the config is registered, it can be used as any other config with the auto-API
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(A__ )
a__ : Tuple = AutoImageProcessor.from_pretrained(A__ )
self.assertIsInstance(A__ , A__ )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
def __lowerCAmelCase ( self : List[Any] ) -> List[str]:
'''simple docstring'''
class lowerCAmelCase__ ( lowerCAmelCase_ ):
"""simple docstring"""
__UpperCamelCase = True
try:
AutoConfig.register('''custom''' , A__ )
AutoImageProcessor.register(A__ , A__ )
# If remote code is not set, the default is to use local
a__ : Dict = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(image_processor.is_local )
# If remote code is disabled, we load the local one.
a__ : Optional[Any] = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(image_processor.is_local )
# If remote is enabled, we load from the Hub
a__ : Optional[int] = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(not hasattr(A__ , '''is_local''' ) )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
| 688
| 1
|
"""simple docstring"""
import argparse
from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta
from transformers.utils import logging
logging.set_verbosity_info()
def snake_case_ ( A_ : List[Any], A_ : str, A_ : List[str] ):
'''simple docstring'''
_lowerCamelCase : Optional[int] = TaConfig.from_json_file(A_ )
print(F'''Building PyTorch model from configuration: {config}''' )
_lowerCamelCase : Dict = 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__ = 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__ = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
| 598
|
"""simple docstring"""
import json
import unittest
import numpy as np
from huggingface_hub import hf_hub_download
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from transformers import OneFormerImageProcessor
from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle
from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput
if is_vision_available():
from PIL import Image
def snake_case_ ( A_ : Union[str, Any], A_ : Optional[Any]="shi-labs/oneformer_demo" ):
'''simple docstring'''
with open(hf_hub_download(A_, A_, repo_type='''dataset''' ), '''r''' ) as f:
_lowerCamelCase : Tuple = json.load(A_ )
_lowerCamelCase : int = {}
_lowerCamelCase : Dict = []
_lowerCamelCase : Optional[Any] = []
for key, info in class_info.items():
_lowerCamelCase : Optional[int] = info['''name''']
class_names.append(info['''name'''] )
if info["isthing"]:
thing_ids.append(int(A_ ) )
_lowerCamelCase : List[Any] = thing_ids
_lowerCamelCase : Any = class_names
return metadata
class __snake_case ( unittest.TestCase):
def __init__( self : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Any=7 , __lowerCAmelCase : Any=3 , __lowerCAmelCase : Tuple=3_0 , __lowerCAmelCase : Optional[int]=4_0_0 , __lowerCAmelCase : Dict=None , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : Dict=True , __lowerCAmelCase : Tuple=[0.5, 0.5, 0.5] , __lowerCAmelCase : List[Any]=[0.5, 0.5, 0.5] , __lowerCAmelCase : Union[str, Any]=1_0 , __lowerCAmelCase : str=False , __lowerCAmelCase : int=2_5_5 , __lowerCAmelCase : Dict="shi-labs/oneformer_demo" , __lowerCAmelCase : str="ade20k_panoptic.json" , __lowerCAmelCase : Dict=1_0 , ):
"""simple docstring"""
_lowerCamelCase : List[str] = parent
_lowerCamelCase : int = batch_size
_lowerCamelCase : List[str] = num_channels
_lowerCamelCase : int = min_resolution
_lowerCamelCase : Tuple = max_resolution
_lowerCamelCase : Dict = do_resize
_lowerCamelCase : Dict = {'''shortest_edge''': 3_2, '''longest_edge''': 1_3_3_3} if size is None else size
_lowerCamelCase : List[str] = do_normalize
_lowerCamelCase : Optional[Any] = image_mean
_lowerCamelCase : Optional[int] = image_std
_lowerCamelCase : Any = class_info_file
_lowerCamelCase : Any = prepare_metadata(__lowerCAmelCase , __lowerCAmelCase )
_lowerCamelCase : Tuple = num_text
_lowerCamelCase : int = repo_path
# for the post_process_functions
_lowerCamelCase : int = 2
_lowerCamelCase : Union[str, Any] = 1_0
_lowerCamelCase : str = 1_0
_lowerCamelCase : Union[str, Any] = 3
_lowerCamelCase : List[Any] = 4
_lowerCamelCase : str = num_labels
_lowerCamelCase : Any = do_reduce_labels
_lowerCamelCase : Tuple = ignore_index
def SCREAMING_SNAKE_CASE ( self : Dict ):
"""simple docstring"""
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"num_labels": self.num_labels,
"do_reduce_labels": self.do_reduce_labels,
"ignore_index": self.ignore_index,
"class_info_file": self.class_info_file,
"metadata": self.metadata,
"num_text": self.num_text,
}
def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : Optional[int]=False ):
"""simple docstring"""
if not batched:
_lowerCamelCase : Tuple = image_inputs[0]
if isinstance(__lowerCAmelCase , Image.Image ):
_lowerCamelCase , _lowerCamelCase : List[str] = image.size
else:
_lowerCamelCase , _lowerCamelCase : int = image.shape[1], image.shape[2]
if w < h:
_lowerCamelCase : Any = int(self.size['''shortest_edge'''] * h / w )
_lowerCamelCase : Union[str, Any] = self.size['''shortest_edge''']
elif w > h:
_lowerCamelCase : Union[str, Any] = self.size['''shortest_edge''']
_lowerCamelCase : Dict = int(self.size['''shortest_edge'''] * w / h )
else:
_lowerCamelCase : int = self.size['''shortest_edge''']
_lowerCamelCase : Optional[Any] = self.size['''shortest_edge''']
else:
_lowerCamelCase : Optional[Any] = []
for image in image_inputs:
_lowerCamelCase , _lowerCamelCase : str = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
_lowerCamelCase : Tuple = max(__lowerCAmelCase , key=lambda __lowerCAmelCase : item[0] )[0]
_lowerCamelCase : Optional[int] = max(__lowerCAmelCase , key=lambda __lowerCAmelCase : item[1] )[1]
return expected_height, expected_width
def SCREAMING_SNAKE_CASE ( self : Tuple ):
"""simple docstring"""
return OneFormerForUniversalSegmentationOutput(
# +1 for null class
class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1) ) , masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width) ) , )
@require_torch
@require_vision
class __snake_case ( _lowercase , unittest.TestCase):
snake_case__ : List[str] = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None
# only for test_image_processing_common.test_image_proc_to_json_string
snake_case__ : List[str] = image_processing_class
def SCREAMING_SNAKE_CASE ( self : str ):
"""simple docstring"""
_lowerCamelCase : Dict = OneFormerImageProcessorTester(self )
@property
def SCREAMING_SNAKE_CASE ( self : Any ):
"""simple docstring"""
return self.image_processing_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE ( self : str ):
"""simple docstring"""
_lowerCamelCase : Tuple = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__lowerCAmelCase , '''image_mean''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''image_std''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''do_normalize''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''do_resize''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''size''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''ignore_index''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''class_info_file''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''num_text''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''repo_path''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''metadata''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''do_reduce_labels''' ) )
def SCREAMING_SNAKE_CASE ( self : Tuple ):
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE ( self : Tuple ):
"""simple docstring"""
_lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_lowerCamelCase : str = prepare_image_inputs(self.image_processing_tester , equal_resolution=__lowerCAmelCase )
for image in image_inputs:
self.assertIsInstance(__lowerCAmelCase , Image.Image )
# Test not batched input
_lowerCamelCase : Optional[int] = image_processor(image_inputs[0] , ['''semantic'''] , return_tensors='''pt''' ).pixel_values
_lowerCamelCase , _lowerCamelCase : Any = self.image_processing_tester.get_expected_values(__lowerCAmelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , )
# Test batched
_lowerCamelCase , _lowerCamelCase : Dict = self.image_processing_tester.get_expected_values(__lowerCAmelCase , batched=__lowerCAmelCase )
_lowerCamelCase : int = image_processor(
__lowerCAmelCase , ['''semantic'''] * len(__lowerCAmelCase ) , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processing_tester.batch_size,
self.image_processing_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE ( self : str ):
"""simple docstring"""
_lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_lowerCamelCase : Any = prepare_image_inputs(self.image_processing_tester , equal_resolution=__lowerCAmelCase , numpify=__lowerCAmelCase )
for image in image_inputs:
self.assertIsInstance(__lowerCAmelCase , np.ndarray )
# Test not batched input
_lowerCamelCase : Optional[int] = image_processor(image_inputs[0] , ['''semantic'''] , return_tensors='''pt''' ).pixel_values
_lowerCamelCase , _lowerCamelCase : Optional[Any] = self.image_processing_tester.get_expected_values(__lowerCAmelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , )
# Test batched
_lowerCamelCase , _lowerCamelCase : Tuple = self.image_processing_tester.get_expected_values(__lowerCAmelCase , batched=__lowerCAmelCase )
_lowerCamelCase : List[Any] = image_processor(
__lowerCAmelCase , ['''semantic'''] * len(__lowerCAmelCase ) , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processing_tester.batch_size,
self.image_processing_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE ( self : Dict ):
"""simple docstring"""
_lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_lowerCamelCase : Union[str, Any] = prepare_image_inputs(self.image_processing_tester , equal_resolution=__lowerCAmelCase , torchify=__lowerCAmelCase )
for image in image_inputs:
self.assertIsInstance(__lowerCAmelCase , torch.Tensor )
# Test not batched input
_lowerCamelCase : Union[str, Any] = image_processor(image_inputs[0] , ['''semantic'''] , return_tensors='''pt''' ).pixel_values
_lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.image_processing_tester.get_expected_values(__lowerCAmelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , )
# Test batched
_lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.image_processing_tester.get_expected_values(__lowerCAmelCase , batched=__lowerCAmelCase )
_lowerCamelCase : int = image_processor(
__lowerCAmelCase , ['''semantic'''] * len(__lowerCAmelCase ) , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processing_tester.batch_size,
self.image_processing_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : Dict=False , __lowerCAmelCase : Union[str, Any]=False , __lowerCAmelCase : Optional[Any]="np" ):
"""simple docstring"""
_lowerCamelCase : Any = self.image_processing_class(**self.image_processor_dict )
# prepare image and target
_lowerCamelCase : Optional[Any] = self.image_processing_tester.num_labels
_lowerCamelCase : List[str] = None
_lowerCamelCase : Dict = None
_lowerCamelCase : Any = prepare_image_inputs(self.image_processing_tester , equal_resolution=__lowerCAmelCase )
if with_segmentation_maps:
_lowerCamelCase : int = num_labels
if is_instance_map:
_lowerCamelCase : List[Any] = list(range(__lowerCAmelCase ) ) * 2
_lowerCamelCase : Dict = dict(enumerate(__lowerCAmelCase ) )
_lowerCamelCase : Optional[int] = [
np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs
]
if segmentation_type == "pil":
_lowerCamelCase : str = [Image.fromarray(__lowerCAmelCase ) for annotation in annotations]
_lowerCamelCase : List[str] = image_processor(
__lowerCAmelCase , ['''semantic'''] * len(__lowerCAmelCase ) , __lowerCAmelCase , return_tensors='''pt''' , instance_id_to_semantic_id=__lowerCAmelCase , pad_and_return_pixel_mask=__lowerCAmelCase , )
return inputs
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ):
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE ( self : int ):
"""simple docstring"""
def common(__lowerCAmelCase : List[str]=False , __lowerCAmelCase : List[str]=None ):
_lowerCamelCase : Dict = self.comm_get_image_processor_inputs(
with_segmentation_maps=__lowerCAmelCase , is_instance_map=__lowerCAmelCase , segmentation_type=__lowerCAmelCase )
_lowerCamelCase : Optional[Any] = inputs['''mask_labels''']
_lowerCamelCase : Union[str, Any] = inputs['''class_labels''']
_lowerCamelCase : Dict = inputs['''pixel_values''']
_lowerCamelCase : int = inputs['''text_inputs''']
# check the batch_size
for mask_label, class_label, text_input in zip(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ):
self.assertEqual(mask_label.shape[0] , class_label.shape[0] )
# this ensure padding has happened
self.assertEqual(mask_label.shape[1:] , pixel_values.shape[2:] )
self.assertEqual(len(__lowerCAmelCase ) , self.image_processing_tester.num_text )
common()
common(is_instance_map=__lowerCAmelCase )
common(is_instance_map=__lowerCAmelCase , segmentation_type='''pil''' )
common(is_instance_map=__lowerCAmelCase , segmentation_type='''pil''' )
def SCREAMING_SNAKE_CASE ( self : Any ):
"""simple docstring"""
_lowerCamelCase : Optional[int] = np.zeros((2_0, 5_0) )
_lowerCamelCase : Tuple = 1
_lowerCamelCase : Tuple = 1
_lowerCamelCase : Tuple = 1
_lowerCamelCase : int = binary_mask_to_rle(__lowerCAmelCase )
self.assertEqual(len(__lowerCAmelCase ) , 4 )
self.assertEqual(rle[0] , 2_1 )
self.assertEqual(rle[1] , 4_5 )
def SCREAMING_SNAKE_CASE ( self : List[Any] ):
"""simple docstring"""
_lowerCamelCase : List[Any] = self.image_processing_class(
num_labels=self.image_processing_tester.num_classes , max_seq_length=7_7 , task_seq_length=7_7 , class_info_file='''ade20k_panoptic.json''' , num_text=self.image_processing_tester.num_text , repo_path='''shi-labs/oneformer_demo''' , )
_lowerCamelCase : Any = self.image_processing_tester.get_fake_oneformer_outputs()
_lowerCamelCase : int = fature_extractor.post_process_semantic_segmentation(__lowerCAmelCase )
self.assertEqual(len(__lowerCAmelCase ) , self.image_processing_tester.batch_size )
self.assertEqual(
segmentation[0].shape , (
self.image_processing_tester.height,
self.image_processing_tester.width,
) , )
_lowerCamelCase : Any = [(1, 4) for i in range(self.image_processing_tester.batch_size )]
_lowerCamelCase : Dict = fature_extractor.post_process_semantic_segmentation(__lowerCAmelCase , target_sizes=__lowerCAmelCase )
self.assertEqual(segmentation[0].shape , target_sizes[0] )
def SCREAMING_SNAKE_CASE ( self : Tuple ):
"""simple docstring"""
_lowerCamelCase : Union[str, Any] = self.image_processing_class(
num_labels=self.image_processing_tester.num_classes , max_seq_length=7_7 , task_seq_length=7_7 , class_info_file='''ade20k_panoptic.json''' , num_text=self.image_processing_tester.num_text , repo_path='''shi-labs/oneformer_demo''' , )
_lowerCamelCase : List[Any] = self.image_processing_tester.get_fake_oneformer_outputs()
_lowerCamelCase : Optional[Any] = image_processor.post_process_instance_segmentation(__lowerCAmelCase , threshold=0 )
self.assertTrue(len(__lowerCAmelCase ) == self.image_processing_tester.batch_size )
for el in segmentation:
self.assertTrue('''segmentation''' in el )
self.assertTrue('''segments_info''' in el )
self.assertEqual(type(el['''segments_info'''] ) , __lowerCAmelCase )
self.assertEqual(
el['''segmentation'''].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
def SCREAMING_SNAKE_CASE ( self : Tuple ):
"""simple docstring"""
_lowerCamelCase : Dict = self.image_processing_class(
num_labels=self.image_processing_tester.num_classes , max_seq_length=7_7 , task_seq_length=7_7 , class_info_file='''ade20k_panoptic.json''' , num_text=self.image_processing_tester.num_text , repo_path='''shi-labs/oneformer_demo''' , )
_lowerCamelCase : Union[str, Any] = self.image_processing_tester.get_fake_oneformer_outputs()
_lowerCamelCase : Optional[Any] = image_processor.post_process_panoptic_segmentation(__lowerCAmelCase , threshold=0 )
self.assertTrue(len(__lowerCAmelCase ) == self.image_processing_tester.batch_size )
for el in segmentation:
self.assertTrue('''segmentation''' in el )
self.assertTrue('''segments_info''' in el )
self.assertEqual(type(el['''segments_info'''] ) , __lowerCAmelCase )
self.assertEqual(
el['''segmentation'''].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
| 598
| 1
|
'''simple docstring'''
import os
import re
import shutil
import sys
import tempfile
import unittest
import black
__SCREAMING_SNAKE_CASE : int = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, """utils"""))
import check_copies # noqa: E402
# This is the reference code that will be used in the tests.
# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.
__SCREAMING_SNAKE_CASE : str = """ def __init__(self, config):
super().__init__()
self.transform = BertPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
self.decoder.bias = self.bias
def forward(self, hidden_states):
hidden_states = self.transform(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
"""
class lowerCamelCase_ (unittest.TestCase ):
'''simple docstring'''
def _A ( self : Tuple ):
_UpperCAmelCase : Optional[int] = tempfile.mkdtemp()
os.makedirs(os.path.join(self.transformer_dir , "models/bert/" ) )
_UpperCAmelCase : List[Any] = self.transformer_dir
shutil.copy(
os.path.join(A , "src/transformers/models/bert/modeling_bert.py" ) , os.path.join(self.transformer_dir , "models/bert/modeling_bert.py" ) , )
def _A ( self : str ):
_UpperCAmelCase : str = "src/transformers"
shutil.rmtree(self.transformer_dir )
def _A ( self : Tuple , A : List[Any] , A : Optional[Any] , A : Any , A : Union[str, Any]=None ):
_UpperCAmelCase : Any = comment + F"""\nclass {class_name}(nn.Module):\n""" + class_code
if overwrite_result is not None:
_UpperCAmelCase : str = comment + F"""\nclass {class_name}(nn.Module):\n""" + overwrite_result
_UpperCAmelCase : Dict = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 )
_UpperCAmelCase : Union[str, Any] = black.format_str(A , mode=A )
_UpperCAmelCase : Tuple = os.path.join(self.transformer_dir , "new_code.py" )
with open(A , "w" , newline="\n" ) as f:
f.write(A )
if overwrite_result is None:
self.assertTrue(len(check_copies.is_copy_consistent(A ) ) == 0 )
else:
check_copies.is_copy_consistent(f.name , overwrite=A )
with open(A , "r" ) as f:
self.assertTrue(f.read() , A )
def _A ( self : Union[str, Any] ):
_UpperCAmelCase : Optional[Any] = check_copies.find_code_in_transformers("models.bert.modeling_bert.BertLMPredictionHead" )
self.assertEqual(A , A )
def _A ( self : List[str] ):
# Base copy consistency
self.check_copy_consistency(
"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead" , "BertLMPredictionHead" , REFERENCE_CODE + "\n" , )
# With no empty line at the end
self.check_copy_consistency(
"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead" , "BertLMPredictionHead" , A , )
# Copy consistency with rename
self.check_copy_consistency(
"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel" , "TestModelLMPredictionHead" , re.sub("Bert" , "TestModel" , A ) , )
# Copy consistency with a really long name
_UpperCAmelCase : Any = "TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason"
self.check_copy_consistency(
F"""# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}""" , F"""{long_class_name}LMPredictionHead""" , re.sub("Bert" , A , A ) , )
# Copy consistency with overwrite
self.check_copy_consistency(
"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel" , "TestModelLMPredictionHead" , A , overwrite_result=re.sub("Bert" , "TestModel" , A ) , )
def _A ( self : Union[str, Any] ):
_UpperCAmelCase : Optional[Any] = check_copies.LOCALIZED_READMES["README_zh-hans.md"]
_UpperCAmelCase : Any = (
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"
" Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"
" Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"
" Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1."
" **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),"
" released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"
" lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same"
" method has been applied to compress GPT2 into"
" [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"
" [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"
" Multilingual BERT into"
" [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"
" version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**"
" (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders"
" as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang"
" Luong, Quoc V. Le, Christopher D. Manning."
)
_UpperCAmelCase : Any = (
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
" Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
" Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
" Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
)
_UpperCAmelCase : Optional[Any] = (
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
" Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
" Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
" Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1."
" **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文"
" [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"
" lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same"
" method has been applied to compress GPT2 into"
" [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"
" [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"
" Multilingual BERT into"
" [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"
" version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自"
" Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather"
" than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,"
" Christopher D. Manning 发布。\n"
)
_UpperCAmelCase , _UpperCAmelCase : Any = check_copies.convert_to_localized_md(
A , A , localized_readme["format_model_list"] )
self.assertFalse(A )
self.assertEqual(A , A )
_UpperCAmelCase , _UpperCAmelCase : Optional[int] = check_copies.convert_to_localized_md(
A , A , localized_readme["format_model_list"] )
# Check whether the number of models is equal to README.md after conversion.
self.assertTrue(A )
_UpperCAmelCase : int = (
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"
" Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"
" Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"
" Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut."
)
_UpperCAmelCase : Union[str, Any] = (
"1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and"
" the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
" Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
" Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
)
_UpperCAmelCase : Optional[int] = (
"1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
" Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
" Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
" Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
)
_UpperCAmelCase , _UpperCAmelCase : List[Any] = check_copies.convert_to_localized_md(
A , A , localized_readme["format_model_list"] )
# Check if the model link is synchronized.
self.assertEqual(A , A )
| 244
|
'''simple docstring'''
from __future__ import annotations
import json
import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent
__SCREAMING_SNAKE_CASE : Optional[int] = {"""UserAgent""": UserAgent().random}
def UpperCamelCase_ ( _UpperCAmelCase : Dict ) -> dict:
"""simple docstring"""
_UpperCAmelCase : List[Any] = script.contents[0]
_UpperCAmelCase : List[Any] = json.loads(data[data.find("{\"config\"" ) : -1] )
return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]
class lowerCamelCase_ :
'''simple docstring'''
def __init__( self : List[str] , A : List[Any] ):
_UpperCAmelCase : int = F"""https://www.instagram.com/{username}/"""
_UpperCAmelCase : Tuple = self.get_json()
def _A ( self : str ):
_UpperCAmelCase : Optional[Any] = requests.get(self.url , headers=A ).text
_UpperCAmelCase : Union[str, Any] = BeautifulSoup(A , "html.parser" ).find_all("script" )
try:
return extract_user_profile(scripts[4] )
except (json.decoder.JSONDecodeError, KeyError):
return extract_user_profile(scripts[3] )
def __repr__( self : Tuple ):
return F"""{self.__class__.__name__}('{self.username}')"""
def __str__( self : int ):
return F"""{self.fullname} ({self.username}) is {self.biography}"""
@property
def _A ( self : List[str] ):
return self.user_data["username"]
@property
def _A ( self : Dict ):
return self.user_data["full_name"]
@property
def _A ( self : Tuple ):
return self.user_data["biography"]
@property
def _A ( self : Tuple ):
return self.user_data["business_email"]
@property
def _A ( self : str ):
return self.user_data["external_url"]
@property
def _A ( self : Union[str, Any] ):
return self.user_data["edge_followed_by"]["count"]
@property
def _A ( self : List[Any] ):
return self.user_data["edge_follow"]["count"]
@property
def _A ( self : int ):
return self.user_data["edge_owner_to_timeline_media"]["count"]
@property
def _A ( self : Optional[Any] ):
return self.user_data["profile_pic_url_hd"]
@property
def _A ( self : str ):
return self.user_data["is_verified"]
@property
def _A ( self : Tuple ):
return self.user_data["is_private"]
def UpperCamelCase_ ( _UpperCAmelCase : str = "github" ) -> None:
"""simple docstring"""
import os
if os.environ.get("CI" ):
return # test failing on GitHub Actions
_UpperCAmelCase : List[Any] = InstagramUser(_UpperCAmelCase )
assert instagram_user.user_data
assert isinstance(instagram_user.user_data , _UpperCAmelCase )
assert instagram_user.username == username
if username != "github":
return
assert instagram_user.fullname == "GitHub"
assert instagram_user.biography == "Built for developers."
assert instagram_user.number_of_posts > 150
assert instagram_user.number_of_followers > 120_000
assert instagram_user.number_of_followings > 15
assert instagram_user.email == "support@github.com"
assert instagram_user.website == "https://github.com/readme"
assert instagram_user.profile_picture_url.startswith("https://instagram." )
assert instagram_user.is_verified is True
assert instagram_user.is_private is False
if __name__ == "__main__":
import doctest
doctest.testmod()
__SCREAMING_SNAKE_CASE : Any = InstagramUser("""github""")
print(instagram_user)
print(F'{instagram_user.number_of_posts = }')
print(F'{instagram_user.number_of_followers = }')
print(F'{instagram_user.number_of_followings = }')
print(F'{instagram_user.email = }')
print(F'{instagram_user.website = }')
print(F'{instagram_user.profile_picture_url = }')
print(F'{instagram_user.is_verified = }')
print(F'{instagram_user.is_private = }')
| 244
| 1
|
'''simple docstring'''
from decimal import Decimal, getcontext
from math import ceil, factorial
def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> str:
'''simple docstring'''
if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
raise TypeError("Undefined for non-integers" )
elif precision < 1:
raise ValueError("Undefined for non-natural numbers" )
UpperCAmelCase_ = precision
UpperCAmelCase_ = ceil(precision / 14 )
UpperCAmelCase_ = 42_68_80 * Decimal(1_00_05 ).sqrt()
UpperCAmelCase_ = 1
UpperCAmelCase_ = 13_59_14_09
UpperCAmelCase_ = Decimal(_SCREAMING_SNAKE_CASE )
for k in range(1 , _SCREAMING_SNAKE_CASE ):
UpperCAmelCase_ = factorial(6 * k ) // (factorial(3 * k ) * factorial(_SCREAMING_SNAKE_CASE ) ** 3)
linear_term += 5_45_14_01_34
exponential_term *= -26_25_37_41_26_40_76_80_00
partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term
return str(constant_term / partial_sum )[:-1]
if __name__ == "__main__":
SCREAMING_SNAKE_CASE_: Optional[Any] =50
print(f"The first {n} digits of pi is: {pi(n)}")
| 701
|
'''simple docstring'''
import warnings
from typing import List, Optional, Union
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class __A ( UpperCamelCase__ ):
a__ : Tuple = ["""image_processor""", """tokenizer"""]
a__ : int = """FlavaImageProcessor"""
a__ : Dict = ("""BertTokenizer""", """BertTokenizerFast""")
def __init__(self : int , __a : Any=None , __a : List[str]=None , **__a : 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." , __a , )
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__(__a , __a )
UpperCAmelCase_ = self.image_processor
def __call__(self : Tuple , __a : Optional[ImageInput] = None , __a : Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None , __a : bool = True , __a : Union[bool, str, PaddingStrategy] = False , __a : Union[bool, str, TruncationStrategy] = False , __a : Optional[int] = None , __a : int = 0 , __a : Optional[int] = None , __a : Optional[bool] = None , __a : Optional[bool] = None , __a : Optional[bool] = None , __a : Optional[bool] = None , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = True , __a : Optional[Union[str, TensorType]] = None , **__a : Optional[Any] , ):
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:
UpperCAmelCase_ = self.tokenizer(
text=__a , add_special_tokens=__a , padding=__a , truncation=__a , max_length=__a , stride=__a , pad_to_multiple_of=__a , return_token_type_ids=__a , return_attention_mask=__a , return_overflowing_tokens=__a , return_special_tokens_mask=__a , return_offsets_mapping=__a , return_length=__a , verbose=__a , return_tensors=__a , **__a , )
if images is not None:
UpperCAmelCase_ = self.image_processor(
__a , return_image_mask=__a , return_codebook_pixels=__a , return_tensors=__a , **__a , )
if text is not None and images is not None:
encoding.update(__a )
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**__a ) , tensor_type=__a )
def _lowercase (self : Optional[int] , *__a : str , **__a : Any ):
return self.tokenizer.batch_decode(*__a , **__a )
def _lowercase (self : Dict , *__a : int , **__a : Optional[Any] ):
return self.tokenizer.decode(*__a , **__a )
@property
def _lowercase (self : int ):
UpperCAmelCase_ = self.tokenizer.model_input_names
UpperCAmelCase_ = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
@property
def _lowercase (self : Any ):
warnings.warn(
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , __a , )
return self.image_processor_class
@property
def _lowercase (self : Optional[int] ):
warnings.warn(
"`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , __a , )
return self.image_processor
| 415
| 0
|
"""simple docstring"""
import logging
from transformers import PretrainedConfig
UpperCAmelCase : Dict = logging.getLogger(__name__)
UpperCAmelCase : List[Any] = {
'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json',
}
class lowerCamelCase__ ( A ):
"""simple docstring"""
__a = """bertabs"""
def __init__( self : Any , UpperCamelCase : int=30_522 , UpperCamelCase : Union[str, Any]=512 , UpperCamelCase : Optional[int]=6 , UpperCamelCase : Any=512 , UpperCamelCase : str=8 , UpperCamelCase : Any=512 , UpperCamelCase : Any=0.2 , UpperCamelCase : List[str]=6 , UpperCamelCase : int=768 , UpperCamelCase : List[str]=8 , UpperCamelCase : Tuple=2_048 , UpperCamelCase : List[str]=0.2 , **UpperCamelCase : Union[str, Any] , ):
'''simple docstring'''
super().__init__(**UpperCamelCase )
__UpperCAmelCase : List[str] = vocab_size
__UpperCAmelCase : Tuple = max_pos
__UpperCAmelCase : Dict = enc_layers
__UpperCAmelCase : Union[str, Any] = enc_hidden_size
__UpperCAmelCase : Optional[int] = enc_heads
__UpperCAmelCase : Optional[Any] = enc_ff_size
__UpperCAmelCase : Tuple = enc_dropout
__UpperCAmelCase : List[str] = dec_layers
__UpperCAmelCase : Dict = dec_hidden_size
__UpperCAmelCase : Optional[Any] = dec_heads
__UpperCAmelCase : Any = dec_ff_size
__UpperCAmelCase : Union[str, Any] = dec_dropout
| 139
|
"""simple docstring"""
from argparse import ArgumentParser
from .env import EnvironmentCommand
def lowerCamelCase ( ) -> Optional[int]:
'''simple docstring'''
__UpperCAmelCase : Any = ArgumentParser("""Diffusers CLI tool""" , usage="""diffusers-cli <command> [<args>]""" )
__UpperCAmelCase : Any = parser.add_subparsers(help="""diffusers-cli command helpers""" )
# Register commands
EnvironmentCommand.register_subcommand(_UpperCamelCase )
# Let's go
__UpperCAmelCase : int = parser.parse_args()
if not hasattr(_UpperCamelCase , """func""" ):
parser.print_help()
exit(1 )
# Run
__UpperCAmelCase : List[str] = args.func(_UpperCamelCase )
service.run()
if __name__ == "__main__":
main()
| 139
| 1
|
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 __SCREAMING_SNAKE_CASE ( unittest.TestCase):
def UpperCAmelCase__ ( self : Tuple ):
_UpperCAmelCase = tempfile.mkdtemp()
# fmt: off
_UpperCAmelCase = ["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
_UpperCAmelCase = dict(zip(__UpperCamelCase , range(len(__UpperCamelCase ) ) ) )
_UpperCAmelCase = ["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""]
_UpperCAmelCase = {"unk_token": "<unk>"}
_UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
_UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as fp:
fp.write(json.dumps(__UpperCamelCase ) + "\n" )
with open(self.merges_file , "w" , encoding="utf-8" ) as fp:
fp.write("\n".join(__UpperCamelCase ) )
_UpperCAmelCase = {
"do_resize": True,
"size": 20,
"do_center_crop": True,
"crop_size": 18,
"do_normalize": True,
"image_mean": [0.48145466, 0.4578275, 0.40821073],
"image_std": [0.26862954, 0.26130258, 0.27577711],
}
_UpperCAmelCase = os.path.join(self.tmpdirname , __UpperCamelCase )
with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp:
json.dump(__UpperCamelCase , __UpperCamelCase )
def UpperCAmelCase__ ( self : str , **__UpperCamelCase : Optional[int] ):
return CLIPTokenizer.from_pretrained(self.tmpdirname , **__UpperCamelCase )
def UpperCAmelCase__ ( self : int , **__UpperCamelCase : Union[str, Any] ):
return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__UpperCamelCase )
def UpperCAmelCase__ ( self : List[Any] , **__UpperCamelCase : int ):
return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__UpperCamelCase )
def UpperCAmelCase__ ( self : List[str] ):
shutil.rmtree(self.tmpdirname )
def UpperCAmelCase__ ( self : Optional[int] ):
_UpperCAmelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
_UpperCAmelCase = [Image.fromarray(np.moveaxis(__UpperCamelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def UpperCAmelCase__ ( self : Optional[Any] ):
_UpperCAmelCase = self.get_tokenizer()
_UpperCAmelCase = self.get_rust_tokenizer()
_UpperCAmelCase = self.get_image_processor()
_UpperCAmelCase = CLIPProcessor(tokenizer=__UpperCamelCase , image_processor=__UpperCamelCase )
processor_slow.save_pretrained(self.tmpdirname )
_UpperCAmelCase = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__UpperCamelCase )
_UpperCAmelCase = CLIPProcessor(tokenizer=__UpperCamelCase , image_processor=__UpperCamelCase )
processor_fast.save_pretrained(self.tmpdirname )
_UpperCAmelCase = 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 , __UpperCamelCase )
self.assertIsInstance(processor_fast.tokenizer , __UpperCamelCase )
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 , __UpperCamelCase )
self.assertIsInstance(processor_fast.image_processor , __UpperCamelCase )
def UpperCAmelCase__ ( self : Optional[Any] ):
_UpperCAmelCase = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
_UpperCAmelCase = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" )
_UpperCAmelCase = self.get_image_processor(do_normalize=__UpperCamelCase , padding_value=1.0 )
_UpperCAmelCase = CLIPProcessor.from_pretrained(
self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=__UpperCamelCase , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , __UpperCamelCase )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , __UpperCamelCase )
def UpperCAmelCase__ ( self : Optional[Any] ):
_UpperCAmelCase = self.get_image_processor()
_UpperCAmelCase = self.get_tokenizer()
_UpperCAmelCase = CLIPProcessor(tokenizer=__UpperCamelCase , image_processor=__UpperCamelCase )
_UpperCAmelCase = self.prepare_image_inputs()
_UpperCAmelCase = image_processor(__UpperCamelCase , return_tensors="np" )
_UpperCAmelCase = processor(images=__UpperCamelCase , return_tensors="np" )
for key in input_image_proc.keys():
self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 )
def UpperCAmelCase__ ( self : Union[str, Any] ):
_UpperCAmelCase = self.get_image_processor()
_UpperCAmelCase = self.get_tokenizer()
_UpperCAmelCase = CLIPProcessor(tokenizer=__UpperCamelCase , image_processor=__UpperCamelCase )
_UpperCAmelCase = "lower newer"
_UpperCAmelCase = processor(text=__UpperCamelCase )
_UpperCAmelCase = tokenizer(__UpperCamelCase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def UpperCAmelCase__ ( self : Any ):
_UpperCAmelCase = self.get_image_processor()
_UpperCAmelCase = self.get_tokenizer()
_UpperCAmelCase = CLIPProcessor(tokenizer=__UpperCamelCase , image_processor=__UpperCamelCase )
_UpperCAmelCase = "lower newer"
_UpperCAmelCase = self.prepare_image_inputs()
_UpperCAmelCase = processor(text=__UpperCamelCase , images=__UpperCamelCase )
self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask", "pixel_values"] )
# test if it raises when no input is passed
with pytest.raises(__UpperCamelCase ):
processor()
def UpperCAmelCase__ ( self : Union[str, Any] ):
_UpperCAmelCase = self.get_image_processor()
_UpperCAmelCase = self.get_tokenizer()
_UpperCAmelCase = CLIPProcessor(tokenizer=__UpperCamelCase , image_processor=__UpperCamelCase )
_UpperCAmelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
_UpperCAmelCase = processor.batch_decode(__UpperCamelCase )
_UpperCAmelCase = tokenizer.batch_decode(__UpperCamelCase )
self.assertListEqual(__UpperCamelCase , __UpperCamelCase )
def UpperCAmelCase__ ( self : Optional[Any] ):
_UpperCAmelCase = self.get_image_processor()
_UpperCAmelCase = self.get_tokenizer()
_UpperCAmelCase = CLIPProcessor(tokenizer=__UpperCamelCase , image_processor=__UpperCamelCase )
_UpperCAmelCase = "lower newer"
_UpperCAmelCase = self.prepare_image_inputs()
_UpperCAmelCase = processor(text=__UpperCamelCase , images=__UpperCamelCase )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 129
|
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__lowerCAmelCase = {
"configuration_time_series_transformer": [
"TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
"TimeSeriesTransformerConfig",
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase = [
"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
__lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 129
| 1
|
import os
from collections import deque
import torch
from torch.utils.data import Dataset
class a ( _A ):
'''simple docstring'''
def __init__( self : str , __snake_case : Any="" , __snake_case : Dict="train" ):
assert os.path.isdir(__snake_case )
UpperCAmelCase_ = []
UpperCAmelCase_ = os.listdir(__snake_case )
for story_filename in story_filenames_list:
if "summary" in story_filename:
continue
UpperCAmelCase_ = os.path.join(__snake_case , __snake_case )
if not os.path.isfile(__snake_case ):
continue
self.documents.append(__snake_case )
def __len__( self : List[str] ):
return len(self.documents )
def __getitem__( self : Optional[Any] , __snake_case : Union[str, Any] ):
UpperCAmelCase_ = self.documents[idx]
UpperCAmelCase_ = document_path.split('''/''' )[-1]
with open(__snake_case , encoding='''utf-8''' ) as source:
UpperCAmelCase_ = source.read()
UpperCAmelCase_ , UpperCAmelCase_ = process_story(__snake_case )
return document_name, story_lines, summary_lines
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : str ) -> List[str]:
UpperCAmelCase_ = list(filter(lambda __UpperCamelCase : len(__UpperCamelCase ) != 0 , [line.strip() for line in raw_story.split('''\n''' )] ) )
# for some unknown reason some lines miss a period, add it
UpperCAmelCase_ = [_add_missing_period(__UpperCamelCase ) for line in nonempty_lines]
# gather article lines
UpperCAmelCase_ = []
UpperCAmelCase_ = deque(__UpperCamelCase )
while True:
try:
UpperCAmelCase_ = lines.popleft()
if element.startswith('''@highlight''' ):
break
story_lines.append(__UpperCamelCase )
except IndexError:
# if "@highlight" is absent from the file we pop
# all elements until there is None, raising an exception.
return story_lines, []
# gather summary lines
UpperCAmelCase_ = list(filter(lambda __UpperCamelCase : not t.startswith('''@highlight''' ) , __UpperCamelCase ) )
return story_lines, summary_lines
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Optional[Any] ) -> List[str]:
UpperCAmelCase_ = ['''.''', '''!''', '''?''', '''...''', '''\'''', '''`''', '''"''', '''\u2019''', '''\u2019''', ''')''']
if line.startswith('''@highlight''' ):
return line
if line[-1] in END_TOKENS:
return line
return line + "."
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : str , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Any ) -> List[Any]:
if len(__UpperCamelCase ) > block_size:
return sequence[:block_size]
else:
sequence.extend([pad_token_id] * (block_size - len(__UpperCamelCase )) )
return sequence
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Any , __UpperCamelCase : Optional[int] ) -> List[Any]:
UpperCAmelCase_ = torch.ones_like(__UpperCamelCase )
UpperCAmelCase_ = sequence == pad_token_id
UpperCAmelCase_ = 0
return mask
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Dict , __UpperCamelCase : Union[str, Any] ) -> Dict:
UpperCAmelCase_ = [tokenizer.encode(__UpperCamelCase ) for line in story_lines]
UpperCAmelCase_ = [token for sentence in story_lines_token_ids for token in sentence]
UpperCAmelCase_ = [tokenizer.encode(__UpperCamelCase ) for line in summary_lines]
UpperCAmelCase_ = [token for sentence in summary_lines_token_ids for token in sentence]
return story_token_ids, summary_token_ids
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Optional[Any] , __UpperCamelCase : List[Any] ) -> int:
UpperCAmelCase_ = []
for sequence in batch:
UpperCAmelCase_ = -1
UpperCAmelCase_ = []
for s in sequence:
if s == separator_token_id:
sentence_num += 1
embeddings.append(sentence_num % 2 )
batch_embeddings.append(__UpperCamelCase )
return torch.tensor(__UpperCamelCase )
| 144
|
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import numpy as np
import torch
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, randn_tensor
from .scheduling_utils import SchedulerMixin
@dataclass
class a ( _A ):
'''simple docstring'''
lowerCAmelCase : torch.FloatTensor
lowerCAmelCase : torch.FloatTensor
lowerCAmelCase : Optional[torch.FloatTensor] = None
class a ( _A , _A ):
'''simple docstring'''
lowerCAmelCase : Dict = 2
@register_to_config
def __init__( self : int , __snake_case : float = 0.02 , __snake_case : float = 1_00 , __snake_case : float = 1.007 , __snake_case : float = 80 , __snake_case : float = 0.05 , __snake_case : float = 50 , ):
# standard deviation of the initial noise distribution
UpperCAmelCase_ = sigma_max
# setable values
UpperCAmelCase_ = None
UpperCAmelCase_ = None
UpperCAmelCase_ = None # sigma(t_i)
def lowerCamelCase_ ( self : Tuple , __snake_case : torch.FloatTensor , __snake_case : Optional[int] = None ):
return sample
def lowerCamelCase_ ( self : List[Any] , __snake_case : int , __snake_case : Union[str, torch.device] = None ):
UpperCAmelCase_ = num_inference_steps
UpperCAmelCase_ = np.arange(0 , self.num_inference_steps )[::-1].copy()
UpperCAmelCase_ = torch.from_numpy(__snake_case ).to(__snake_case )
UpperCAmelCase_ = [
(
self.config.sigma_max**2
* (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1))
)
for i in self.timesteps
]
UpperCAmelCase_ = torch.tensor(__snake_case , dtype=torch.floataa , device=__snake_case )
def lowerCamelCase_ ( self : Optional[int] , __snake_case : torch.FloatTensor , __snake_case : float , __snake_case : Optional[torch.Generator] = None ):
if self.config.s_min <= sigma <= self.config.s_max:
UpperCAmelCase_ = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 )
else:
UpperCAmelCase_ = 0
# sample eps ~ N(0, S_noise^2 * I)
UpperCAmelCase_ = self.config.s_noise * randn_tensor(sample.shape , generator=__snake_case ).to(sample.device )
UpperCAmelCase_ = sigma + gamma * sigma
UpperCAmelCase_ = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps)
return sample_hat, sigma_hat
def lowerCamelCase_ ( self : List[str] , __snake_case : torch.FloatTensor , __snake_case : float , __snake_case : float , __snake_case : torch.FloatTensor , __snake_case : bool = True , ):
UpperCAmelCase_ = sample_hat + sigma_hat * model_output
UpperCAmelCase_ = (sample_hat - pred_original_sample) / sigma_hat
UpperCAmelCase_ = sample_hat + (sigma_prev - sigma_hat) * derivative
if not return_dict:
return (sample_prev, derivative)
return KarrasVeOutput(
prev_sample=__snake_case , derivative=__snake_case , pred_original_sample=__snake_case )
def lowerCamelCase_ ( self : Union[str, Any] , __snake_case : torch.FloatTensor , __snake_case : float , __snake_case : float , __snake_case : torch.FloatTensor , __snake_case : torch.FloatTensor , __snake_case : torch.FloatTensor , __snake_case : bool = True , ):
UpperCAmelCase_ = sample_prev + sigma_prev * model_output
UpperCAmelCase_ = (sample_prev - pred_original_sample) / sigma_prev
UpperCAmelCase_ = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr)
if not return_dict:
return (sample_prev, derivative)
return KarrasVeOutput(
prev_sample=__snake_case , derivative=__snake_case , pred_original_sample=__snake_case )
def lowerCamelCase_ ( self : Optional[Any] , __snake_case : List[str] , __snake_case : Any , __snake_case : Union[str, Any] ):
raise NotImplementedError()
| 144
| 1
|
'''simple docstring'''
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 UpperCAmelCase_ ( a):
lowerCamelCase__ = ['image_processor', 'tokenizer']
lowerCamelCase__ = 'BridgeTowerImageProcessor'
lowerCamelCase__ = ('RobertaTokenizer', 'RobertaTokenizerFast')
def __init__( self, __a, __a):
'''simple docstring'''
super().__init__(__a, __a)
def __call__( self, __a, __a = None, __a = True, __a = False, __a = None, __a = None, __a = 0, __a = None, __a = None, __a = None, __a = False, __a = False, __a = False, __a = False, __a = True, __a = None, **__a, ):
'''simple docstring'''
_lowerCAmelCase : int = self.tokenizer(
text=__a, add_special_tokens=__a, padding=__a, truncation=__a, max_length=__a, stride=__a, pad_to_multiple_of=__a, return_token_type_ids=__a, return_attention_mask=__a, return_overflowing_tokens=__a, return_special_tokens_mask=__a, return_offsets_mapping=__a, return_length=__a, verbose=__a, return_tensors=__a, **__a, )
# add pixel_values + pixel_mask
_lowerCAmelCase : Optional[Any] = self.image_processor(
__a, return_tensors=__a, do_normalize=__a, do_center_crop=__a, **__a)
encoding.update(__a)
return encoding
def snake_case__ ( self, *__a, **__a):
'''simple docstring'''
return self.tokenizer.batch_decode(*__a, **__a)
def snake_case__ ( self, *__a, **__a):
'''simple docstring'''
return self.tokenizer.decode(*__a, **__a)
@property
def snake_case__ ( self):
'''simple docstring'''
_lowerCAmelCase : Any = self.tokenizer.model_input_names
_lowerCAmelCase : Dict = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
| 705
|
def A ( _lowerCamelCase = 1_000_000 ):
'''simple docstring'''
_lowerCAmelCase : Any = 1
_lowerCAmelCase : Optional[Any] = 1
_lowerCAmelCase : List[str] = {1: 1}
for inputa in range(2 , _lowerCamelCase ):
_lowerCAmelCase : int = 0
_lowerCAmelCase : Any = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
_lowerCAmelCase : Any = (3 * number) + 1
counter += 1
if inputa not in counters:
_lowerCAmelCase : Tuple = counter
if counter > pre_counter:
_lowerCAmelCase : Union[str, Any] = inputa
_lowerCAmelCase : Union[str, Any] = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 658
| 0
|
'''simple docstring'''
import argparse
import requests
import torch
# pip3 install salesforce-lavis
# I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis
from lavis.models import load_model_and_preprocess
from PIL import Image
from transformers import (
AutoTokenizer,
BlipaConfig,
BlipaForConditionalGeneration,
BlipaProcessor,
BlipaVisionConfig,
BlipImageProcessor,
OPTConfig,
TaConfig,
)
from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
def UpperCAmelCase__( ):
"""simple docstring"""
__A= 'https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png'
__A= Image.open(requests.get(_SCREAMING_SNAKE_CASE,stream=_SCREAMING_SNAKE_CASE ).raw ).convert('RGB' )
return image
def UpperCAmelCase__( _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
__A= []
# fmt: off
# vision encoder
rename_keys.append(('visual_encoder.cls_token', 'vision_model.embeddings.class_embedding') )
rename_keys.append(('visual_encoder.pos_embed', 'vision_model.embeddings.position_embedding') )
rename_keys.append(('visual_encoder.patch_embed.proj.weight', 'vision_model.embeddings.patch_embedding.weight') )
rename_keys.append(('visual_encoder.patch_embed.proj.bias', 'vision_model.embeddings.patch_embedding.bias') )
rename_keys.append(('ln_vision.weight', 'vision_model.post_layernorm.weight') )
rename_keys.append(('ln_vision.bias', 'vision_model.post_layernorm.bias') )
for i in range(config.vision_config.num_hidden_layers ):
rename_keys.append((f"""visual_encoder.blocks.{i}.norm1.weight""", f"""vision_model.encoder.layers.{i}.layer_norm1.weight""") )
rename_keys.append((f"""visual_encoder.blocks.{i}.norm1.bias""", f"""vision_model.encoder.layers.{i}.layer_norm1.bias""") )
rename_keys.append((f"""visual_encoder.blocks.{i}.norm2.weight""", f"""vision_model.encoder.layers.{i}.layer_norm2.weight""") )
rename_keys.append((f"""visual_encoder.blocks.{i}.norm2.bias""", f"""vision_model.encoder.layers.{i}.layer_norm2.bias""") )
rename_keys.append((f"""visual_encoder.blocks.{i}.attn.qkv.weight""", f"""vision_model.encoder.layers.{i}.self_attn.qkv.weight""") )
rename_keys.append((f"""visual_encoder.blocks.{i}.attn.proj.weight""", f"""vision_model.encoder.layers.{i}.self_attn.projection.weight""",) )
rename_keys.append((f"""visual_encoder.blocks.{i}.attn.proj.bias""", f"""vision_model.encoder.layers.{i}.self_attn.projection.bias""") )
rename_keys.append((f"""visual_encoder.blocks.{i}.mlp.fc1.weight""", f"""vision_model.encoder.layers.{i}.mlp.fc1.weight""") )
rename_keys.append((f"""visual_encoder.blocks.{i}.mlp.fc1.bias""", f"""vision_model.encoder.layers.{i}.mlp.fc1.bias""") )
rename_keys.append((f"""visual_encoder.blocks.{i}.mlp.fc2.weight""", f"""vision_model.encoder.layers.{i}.mlp.fc2.weight""") )
rename_keys.append((f"""visual_encoder.blocks.{i}.mlp.fc2.bias""", f"""vision_model.encoder.layers.{i}.mlp.fc2.bias""") )
# QFormer
rename_keys.append(('Qformer.bert.embeddings.LayerNorm.weight', 'qformer.layernorm.weight') )
rename_keys.append(('Qformer.bert.embeddings.LayerNorm.bias', 'qformer.layernorm.bias') )
# fmt: on
return rename_keys
def UpperCAmelCase__( _SCREAMING_SNAKE_CASE : Optional[Any],_SCREAMING_SNAKE_CASE : Dict,_SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
__A= dct.pop(_SCREAMING_SNAKE_CASE )
__A= val
def UpperCAmelCase__( _SCREAMING_SNAKE_CASE : Dict,_SCREAMING_SNAKE_CASE : List[str] ):
"""simple docstring"""
for i in range(config.vision_config.num_hidden_layers ):
# read in original q and v biases
__A= state_dict.pop(f"""visual_encoder.blocks.{i}.attn.q_bias""" )
__A= state_dict.pop(f"""visual_encoder.blocks.{i}.attn.v_bias""" )
# next, set bias in the state dict
__A= torch.cat((q_bias, torch.zeros_like(_SCREAMING_SNAKE_CASE,requires_grad=_SCREAMING_SNAKE_CASE ), v_bias) )
__A= qkv_bias
def UpperCAmelCase__( _SCREAMING_SNAKE_CASE : Any,_SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
__A= 364 if 'coco' in model_name else 224
__A= BlipaVisionConfig(image_size=_SCREAMING_SNAKE_CASE ).to_dict()
# make sure the models have proper bos_token_id and eos_token_id set (important for generation)
# seems like flan-T5 models don't have bos_token_id properly set?
if "opt-2.7b" in model_name:
__A= OPTConfig.from_pretrained('facebook/opt-2.7b',eos_token_id=_SCREAMING_SNAKE_CASE ).to_dict()
elif "opt-6.7b" in model_name:
__A= OPTConfig.from_pretrained('facebook/opt-6.7b',eos_token_id=_SCREAMING_SNAKE_CASE ).to_dict()
elif "t5-xl" in model_name:
__A= TaConfig.from_pretrained('google/flan-t5-xl',dense_act_fn='gelu',bos_token_id=1 ).to_dict()
elif "t5-xxl" in model_name:
__A= TaConfig.from_pretrained('google/flan-t5-xxl',dense_act_fn='gelu',bos_token_id=1 ).to_dict()
__A= BlipaConfig(vision_config=_SCREAMING_SNAKE_CASE,text_config=_SCREAMING_SNAKE_CASE )
return config, image_size
@torch.no_grad()
def UpperCAmelCase__( _SCREAMING_SNAKE_CASE : Optional[int],_SCREAMING_SNAKE_CASE : List[Any]=None,_SCREAMING_SNAKE_CASE : Tuple=False ):
"""simple docstring"""
__A= (
AutoTokenizer.from_pretrained('facebook/opt-2.7b' )
if 'opt' in model_name
else AutoTokenizer.from_pretrained('google/flan-t5-xl' )
)
__A= tokenizer('\n',add_special_tokens=_SCREAMING_SNAKE_CASE ).input_ids[0]
__A, __A= get_blipa_config(_SCREAMING_SNAKE_CASE,eos_token_id=_SCREAMING_SNAKE_CASE )
__A= BlipaForConditionalGeneration(_SCREAMING_SNAKE_CASE ).eval()
__A= {
'blip2-opt-2.7b': ('blip2_opt', 'pretrain_opt2.7b'),
'blip2-opt-6.7b': ('blip2_opt', 'pretrain_opt6.7b'),
'blip2-opt-2.7b-coco': ('blip2_opt', 'caption_coco_opt2.7b'),
'blip2-opt-6.7b-coco': ('blip2_opt', 'caption_coco_opt6.7b'),
'blip2-flan-t5-xl': ('blip2_t5', 'pretrain_flant5xl'),
'blip2-flan-t5-xl-coco': ('blip2_t5', 'caption_coco_flant5xl'),
'blip2-flan-t5-xxl': ('blip2_t5', 'pretrain_flant5xxl'),
}
__A, __A= model_name_to_original[model_name]
# load original model
print('Loading original model...' )
__A= 'cuda' if torch.cuda.is_available() else 'cpu'
__A, __A, __A= load_model_and_preprocess(
name=_SCREAMING_SNAKE_CASE,model_type=_SCREAMING_SNAKE_CASE,is_eval=_SCREAMING_SNAKE_CASE,device=_SCREAMING_SNAKE_CASE )
original_model.eval()
print('Done!' )
# update state dict keys
__A= original_model.state_dict()
__A= create_rename_keys(_SCREAMING_SNAKE_CASE )
for src, dest in rename_keys:
rename_key(_SCREAMING_SNAKE_CASE,_SCREAMING_SNAKE_CASE,_SCREAMING_SNAKE_CASE )
# some keys can be renamed efficiently
for key, val in state_dict.copy().items():
__A= state_dict.pop(_SCREAMING_SNAKE_CASE )
if key.startswith('Qformer.bert' ):
__A= key.replace('Qformer.bert','qformer' )
if "attention.self" in key:
__A= key.replace('self','attention' )
if "opt_proj" in key:
__A= key.replace('opt_proj','language_projection' )
if "t5_proj" in key:
__A= key.replace('t5_proj','language_projection' )
if key.startswith('opt' ):
__A= key.replace('opt','language' )
if key.startswith('t5' ):
__A= key.replace('t5','language' )
__A= val
# read in qv biases
read_in_q_v_bias(_SCREAMING_SNAKE_CASE,_SCREAMING_SNAKE_CASE )
__A, __A= hf_model.load_state_dict(_SCREAMING_SNAKE_CASE,strict=_SCREAMING_SNAKE_CASE )
assert len(_SCREAMING_SNAKE_CASE ) == 0
assert unexpected_keys == ["qformer.embeddings.position_ids"]
__A= load_demo_image()
__A= vis_processors['eval'](_SCREAMING_SNAKE_CASE ).unsqueeze(0 ).to(_SCREAMING_SNAKE_CASE )
__A= tokenizer(['\n'],return_tensors='pt' ).input_ids.to(_SCREAMING_SNAKE_CASE )
# create processor
__A= BlipImageProcessor(
size={'height': image_size, 'width': image_size},image_mean=_SCREAMING_SNAKE_CASE,image_std=_SCREAMING_SNAKE_CASE )
__A= BlipaProcessor(image_processor=_SCREAMING_SNAKE_CASE,tokenizer=_SCREAMING_SNAKE_CASE )
__A= processor(images=_SCREAMING_SNAKE_CASE,return_tensors='pt' ).pixel_values.to(_SCREAMING_SNAKE_CASE )
# make sure processor creates exact same pixel values
assert torch.allclose(_SCREAMING_SNAKE_CASE,_SCREAMING_SNAKE_CASE )
original_model.to(_SCREAMING_SNAKE_CASE )
hf_model.to(_SCREAMING_SNAKE_CASE )
with torch.no_grad():
if "opt" in model_name:
__A= original_model({'image': original_pixel_values, 'text_input': ['']} ).logits
__A= hf_model(_SCREAMING_SNAKE_CASE,_SCREAMING_SNAKE_CASE ).logits
else:
__A= original_model(
{'image': original_pixel_values, 'text_input': ['\n'], 'text_output': ['\n']} ).logits
__A= input_ids.masked_fill(input_ids == tokenizer.pad_token_id,-100 )
__A= hf_model(_SCREAMING_SNAKE_CASE,_SCREAMING_SNAKE_CASE,labels=_SCREAMING_SNAKE_CASE ).logits
assert original_logits.shape == logits.shape
print('First values of original logits:',original_logits[0, :3, :3] )
print('First values of HF logits:',logits[0, :3, :3] )
# assert values
if model_name == "blip2-flan-t5-xl":
__A= torch.tensor(
[[-41.58_50, -4.44_40, -8.99_22], [-47.43_22, -5.91_43, -1.73_40]],device=_SCREAMING_SNAKE_CASE )
assert torch.allclose(logits[0, :3, :3],_SCREAMING_SNAKE_CASE,atol=1e-4 )
elif model_name == "blip2-flan-t5-xl-coco":
__A= torch.tensor(
[[-57.01_09, -9.89_67, -12.62_80], [-68.65_78, -12.71_91, -10.50_65]],device=_SCREAMING_SNAKE_CASE )
else:
# cast to same type
__A= logits.dtype
assert torch.allclose(original_logits.to(_SCREAMING_SNAKE_CASE ),_SCREAMING_SNAKE_CASE,atol=1e-2 )
print('Looks ok!' )
print('Generating a caption...' )
__A= ''
__A= tokenizer(_SCREAMING_SNAKE_CASE,return_tensors='pt' ).input_ids.to(_SCREAMING_SNAKE_CASE )
__A= original_model.generate({'image': original_pixel_values} )
__A= hf_model.generate(
_SCREAMING_SNAKE_CASE,_SCREAMING_SNAKE_CASE,do_sample=_SCREAMING_SNAKE_CASE,num_beams=5,max_length=30,min_length=1,top_p=0.9,repetition_penalty=1.0,length_penalty=1.0,temperature=1,)
print('Original generation:',_SCREAMING_SNAKE_CASE )
__A= input_ids.shape[1]
__A= processor.batch_decode(outputs[:, prompt_length:],skip_special_tokens=_SCREAMING_SNAKE_CASE )
__A= [text.strip() for text in output_text]
print('HF generation:',_SCREAMING_SNAKE_CASE )
if pytorch_dump_folder_path is not None:
processor.save_pretrained(_SCREAMING_SNAKE_CASE )
hf_model.save_pretrained(_SCREAMING_SNAKE_CASE )
if push_to_hub:
processor.push_to_hub(f"""nielsr/{model_name}""" )
hf_model.push_to_hub(f"""nielsr/{model_name}""" )
if __name__ == "__main__":
UpperCAmelCase__ = argparse.ArgumentParser()
UpperCAmelCase__ = [
'''blip2-opt-2.7b''',
'''blip2-opt-6.7b''',
'''blip2-opt-2.7b-coco''',
'''blip2-opt-6.7b-coco''',
'''blip2-flan-t5-xl''',
'''blip2-flan-t5-xl-coco''',
'''blip2-flan-t5-xxl''',
]
parser.add_argument(
'''--model_name''',
default='''blip2-opt-2.7b''',
choices=choices,
type=str,
help='''Path to hf config.json of model to convert''',
)
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument(
'''--push_to_hub''',
action='''store_true''',
help='''Whether to push the model and processor to the hub after converting''',
)
UpperCAmelCase__ = parser.parse_args()
convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 186
|
'''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 a__ ( a_ ):
'''simple docstring'''
def lowerCAmelCase ( self : Tuple ) -> Optional[int]:
__A= self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(lowerCAmelCase_ , 'hidden_sizes' ) )
self.parent.assertTrue(hasattr(lowerCAmelCase_ , 'neck_hidden_sizes' ) )
self.parent.assertTrue(hasattr(lowerCAmelCase_ , 'num_attention_heads' ) )
class a__ :
'''simple docstring'''
def __init__( self : str , lowerCAmelCase_ : str , lowerCAmelCase_ : str=13 , lowerCAmelCase_ : Dict=32 , lowerCAmelCase_ : Tuple=2 , lowerCAmelCase_ : List[str]=3 , lowerCAmelCase_ : str=640 , lowerCAmelCase_ : str=4 , lowerCAmelCase_ : Dict="silu" , lowerCAmelCase_ : List[str]=3 , lowerCAmelCase_ : str=32 , lowerCAmelCase_ : List[Any]=0.1 , lowerCAmelCase_ : str=0.1 , lowerCAmelCase_ : str=0.1 , lowerCAmelCase_ : str=0.02 , lowerCAmelCase_ : Optional[int]=True , lowerCAmelCase_ : Optional[int]=True , lowerCAmelCase_ : Any=10 , lowerCAmelCase_ : Dict=None , ) -> Optional[Any]:
__A= parent
__A= batch_size
__A= image_size
__A= patch_size
__A= num_channels
__A= last_hidden_size
__A= num_attention_heads
__A= hidden_act
__A= conv_kernel_size
__A= output_stride
__A= hidden_dropout_prob
__A= attention_probs_dropout_prob
__A= classifier_dropout_prob
__A= use_labels
__A= is_training
__A= num_labels
__A= initializer_range
__A= scope
def lowerCAmelCase ( self : Union[str, Any] ) -> Dict:
__A= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__A= None
__A= None
if self.use_labels:
__A= ids_tensor([self.batch_size] , self.num_labels )
__A= ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
__A= self.get_config()
return config, pixel_values, labels, pixel_labels
def lowerCAmelCase ( self : List[Any] ) -> List[Any]:
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 : Any , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Optional[Any] ) -> Dict:
__A= MobileViTModel(config=lowerCAmelCase_ )
model.to(lowerCAmelCase_ )
model.eval()
__A= model(lowerCAmelCase_ )
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 : List[str] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Any ) -> Optional[Any]:
__A= self.num_labels
__A= MobileViTForImageClassification(lowerCAmelCase_ )
model.to(lowerCAmelCase_ )
model.eval()
__A= model(lowerCAmelCase_ , labels=lowerCAmelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def lowerCAmelCase ( self : Optional[int] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : int ) -> int:
__A= self.num_labels
__A= MobileViTForSemanticSegmentation(lowerCAmelCase_ )
model.to(lowerCAmelCase_ )
model.eval()
__A= model(lowerCAmelCase_ )
self.parent.assertEqual(
result.logits.shape , (
self.batch_size,
self.num_labels,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
__A= model(lowerCAmelCase_ , labels=lowerCAmelCase_ )
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 : Optional[int] ) -> Optional[int]:
__A= self.prepare_config_and_inputs()
__A, __A, __A, __A= config_and_inputs
__A= {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
class a__ ( a_ , a_ , unittest.TestCase ):
'''simple docstring'''
A : Union[str, Any] = (
(MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
if is_torch_available()
else ()
)
A : Any = (
{
'''feature-extraction''': MobileViTModel,
'''image-classification''': MobileViTForImageClassification,
'''image-segmentation''': MobileViTForSemanticSegmentation,
}
if is_torch_available()
else {}
)
A : int = False
A : Dict = False
A : Dict = False
A : str = False
def lowerCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]:
__A= MobileViTModelTester(self )
__A= MobileViTConfigTester(self , config_class=lowerCAmelCase_ , has_text_modality=lowerCAmelCase_ )
def lowerCAmelCase ( self : Any ) -> str:
self.config_tester.run_common_tests()
@unittest.skip(reason='MobileViT does not use inputs_embeds' )
def lowerCAmelCase ( self : int ) -> Any:
pass
@unittest.skip(reason='MobileViT does not support input and output embeddings' )
def lowerCAmelCase ( self : List[str] ) -> List[Any]:
pass
@unittest.skip(reason='MobileViT does not output attentions' )
def lowerCAmelCase ( self : List[str] ) -> Optional[int]:
pass
def lowerCAmelCase ( self : Optional[int] ) -> Optional[Any]:
__A, __A= self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__A= model_class(lowerCAmelCase_ )
__A= inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__A= [*signature.parameters.keys()]
__A= ['pixel_values']
self.assertListEqual(arg_names[:1] , lowerCAmelCase_ )
@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
def lowerCAmelCase ( self : str ) -> int:
pass
def lowerCAmelCase ( self : str ) -> Any:
__A= self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCAmelCase_ )
def lowerCAmelCase ( self : Optional[Any] ) -> str:
def check_hidden_states_output(lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : List[str] ):
__A= model_class(lowerCAmelCase_ )
model.to(lowerCAmelCase_ )
model.eval()
with torch.no_grad():
__A= model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) )
__A= outputs.hidden_states
__A= 5
self.assertEqual(len(lowerCAmelCase_ ) , lowerCAmelCase_ )
# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
# with the width and height being successively divided by 2.
__A= 2
for i in range(len(lowerCAmelCase_ ) ):
self.assertListEqual(
list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , )
divisor *= 2
self.assertEqual(self.model_tester.output_stride , divisor // 2 )
__A, __A= self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__A= True
check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__A= True
check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
def lowerCAmelCase ( self : Tuple ) -> Optional[Any]:
__A= self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_ )
def lowerCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]:
__A= self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase_ )
@slow
def lowerCAmelCase ( self : Union[str, Any] ) -> Optional[Any]:
for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__A= MobileViTModel.from_pretrained(lowerCAmelCase_ )
self.assertIsNotNone(lowerCAmelCase_ )
def UpperCAmelCase__( ):
"""simple docstring"""
__A= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_torch
@require_vision
class a__ ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def lowerCAmelCase ( self : Optional[Any] ) -> Tuple:
return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small' ) if is_vision_available() else None
@slow
def lowerCAmelCase ( self : int ) -> str:
__A= MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small' ).to(lowerCAmelCase_ )
__A= self.default_image_processor
__A= prepare_img()
__A= image_processor(images=lowerCAmelCase_ , return_tensors='pt' ).to(lowerCAmelCase_ )
# forward pass
with torch.no_grad():
__A= model(**lowerCAmelCase_ )
# verify the logits
__A= torch.Size((1, 1_000) )
self.assertEqual(outputs.logits.shape , lowerCAmelCase_ )
__A= torch.tensor([-1.93_64, -1.23_27, -0.46_53] ).to(lowerCAmelCase_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase_ , atol=1E-4 ) )
@slow
def lowerCAmelCase ( self : Union[str, Any] ) -> List[str]:
__A= MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
__A= model.to(lowerCAmelCase_ )
__A= MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
__A= prepare_img()
__A= image_processor(images=lowerCAmelCase_ , return_tensors='pt' ).to(lowerCAmelCase_ )
# forward pass
with torch.no_grad():
__A= model(**lowerCAmelCase_ )
__A= outputs.logits
# verify the logits
__A= torch.Size((1, 21, 32, 32) )
self.assertEqual(logits.shape , lowerCAmelCase_ )
__A= torch.tensor(
[
[[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]],
[[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]],
[[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]],
] , device=lowerCAmelCase_ , )
self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , lowerCAmelCase_ , atol=1E-4 ) )
@slow
def lowerCAmelCase ( self : Tuple ) -> str:
__A= MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
__A= model.to(lowerCAmelCase_ )
__A= MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
__A= prepare_img()
__A= image_processor(images=lowerCAmelCase_ , return_tensors='pt' ).to(lowerCAmelCase_ )
# forward pass
with torch.no_grad():
__A= model(**lowerCAmelCase_ )
__A= outputs.logits.detach().cpu()
__A= image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase_ , target_sizes=[(50, 60)] )
__A= torch.Size((50, 60) )
self.assertEqual(segmentation[0].shape , lowerCAmelCase_ )
__A= image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase_ )
__A= torch.Size((32, 32) )
self.assertEqual(segmentation[0].shape , lowerCAmelCase_ )
| 186
| 1
|
"""simple docstring"""
def snake_case__ ( _lowerCamelCase ) ->bool:
"""simple docstring"""
__lowercase : set[int] = set()
# To detect a back edge, keep track of vertices currently in the recursion stack
__lowercase : set[int] = set()
return any(
node not in visited and depth_first_search(_lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase )
for node in graph )
def snake_case__ ( _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase ) ->bool:
"""simple docstring"""
visited.add(_lowerCamelCase )
rec_stk.add(_lowerCamelCase )
for node in graph[vertex]:
if node not in visited:
if depth_first_search(_lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase ):
return True
elif node in rec_stk:
return True
# The node needs to be removed from recursion stack before function ends
rec_stk.remove(_lowerCamelCase )
return False
if __name__ == "__main__":
from doctest import testmod
testmod()
| 281
|
"""simple docstring"""
from __future__ import annotations
import os
from collections.abc import Mapping
__A : str = tuple[int, int]
class lowerCAmelCase__ :
"""simple docstring"""
def __init__( self : int , lowercase__ : set[int] , lowercase__ : Mapping[EdgeT, int] ):
__lowercase : set[int] = vertices
__lowercase : dict[EdgeT, int] = {
(min(lowercase__ ), max(lowercase__ )): weight for edge, weight in edges.items()
}
def snake_case ( self : Optional[Any] , lowercase__ : EdgeT , lowercase__ : int ):
self.vertices.add(edge[0] )
self.vertices.add(edge[1] )
__lowercase : Union[str, Any] = weight
def snake_case ( self : Dict ):
__lowercase : Graph = Graph({min(self.vertices )} , {} )
__lowercase : EdgeT
__lowercase : int
__lowercase : EdgeT
__lowercase : int
while len(subgraph.vertices ) < len(self.vertices ):
__lowercase : int = max(self.edges.values() ) + 1
for edge, weight in self.edges.items():
if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices):
if weight < min_weight:
__lowercase : Optional[Any] = edge
__lowercase : List[str] = weight
subgraph.add_edge(lowercase__ , lowercase__ )
return subgraph
def snake_case__ ( _lowerCamelCase = "p107_network.txt" ) ->int:
"""simple docstring"""
__lowercase : str = os.path.abspath(os.path.dirname(_lowerCamelCase ) )
__lowercase : str = os.path.join(_lowerCamelCase, _lowerCamelCase )
__lowercase : dict[EdgeT, int] = {}
__lowercase : list[str]
__lowercase : int
__lowercase : int
with open(_lowerCamelCase ) as f:
__lowercase : List[str] = f.read().strip().split("\n" )
__lowercase : Any = [line.split("," ) for line in data]
for edgea in range(1, len(_lowerCamelCase ) ):
for edgea in range(_lowerCamelCase ):
if adjaceny_matrix[edgea][edgea] != "-":
__lowercase : Dict = int(adjaceny_matrix[edgea][edgea] )
__lowercase : Graph = Graph(set(range(len(_lowerCamelCase ) ) ), _lowerCamelCase )
__lowercase : Graph = graph.prims_algorithm()
__lowercase : int = sum(graph.edges.values() )
__lowercase : int = sum(subgraph.edges.values() )
return initial_total - optimal_total
if __name__ == "__main__":
print(F"""{solution() = }""")
| 281
| 1
|
'''simple docstring'''
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
OPENAI_CLIP_MEAN,
OPENAI_CLIP_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_vision_available():
import PIL
__lowerCAmelCase = logging.get_logger(__name__)
class __magic_name__ ( _UpperCamelCase ):
lowerCAmelCase : Optional[Any] = ['pixel_values']
def __init__( self : Tuple ,_UpperCAmelCase : bool = True ,_UpperCAmelCase : Dict[str, int] = None ,_UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC ,_UpperCAmelCase : bool = True ,_UpperCAmelCase : Union[int, float] = 1 / 255 ,_UpperCAmelCase : bool = True ,_UpperCAmelCase : Optional[Union[float, List[float]]] = None ,_UpperCAmelCase : Optional[Union[float, List[float]]] = None ,_UpperCAmelCase : bool = True ,**_UpperCAmelCase : Tuple ,):
super().__init__(**_UpperCAmelCase )
_a : Union[str, Any] = size if size is not None else {'height': 384, 'width': 384}
_a : Any = get_size_dict(_UpperCAmelCase ,default_to_square=_UpperCAmelCase )
_a : Optional[Any] = do_resize
_a : Tuple = size
_a : str = resample
_a : Union[str, Any] = do_rescale
_a : Optional[int] = rescale_factor
_a : Any = do_normalize
_a : str = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
_a : Any = image_std if image_std is not None else OPENAI_CLIP_STD
_a : List[Any] = do_convert_rgb
def __lowercase ( self : Any ,_UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Dict[str, int] ,_UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC ,_UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None ,**_UpperCAmelCase : List[str] ,):
_a : Tuple = get_size_dict(_UpperCAmelCase ,default_to_square=_UpperCAmelCase )
if "height" not in size or "width" not in size:
raise ValueError(F"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""" )
_a : List[str] = (size['height'], size['width'])
return resize(_UpperCAmelCase ,size=_UpperCAmelCase ,resample=_UpperCAmelCase ,data_format=_UpperCAmelCase ,**_UpperCAmelCase )
def __lowercase ( self : Tuple ,_UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Union[int, float] ,_UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None ,**_UpperCAmelCase : List[Any] ,):
return rescale(_UpperCAmelCase ,scale=_UpperCAmelCase ,data_format=_UpperCAmelCase ,**_UpperCAmelCase )
def __lowercase ( self : int ,_UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Union[float, List[float]] ,_UpperCAmelCase : Union[float, List[float]] ,_UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None ,**_UpperCAmelCase : Union[str, Any] ,):
return normalize(_UpperCAmelCase ,mean=_UpperCAmelCase ,std=_UpperCAmelCase ,data_format=_UpperCAmelCase ,**_UpperCAmelCase )
def __lowercase ( self : Optional[int] ,_UpperCAmelCase : ImageInput ,_UpperCAmelCase : Optional[bool] = None ,_UpperCAmelCase : Optional[Dict[str, int]] = None ,_UpperCAmelCase : PILImageResampling = None ,_UpperCAmelCase : Optional[bool] = None ,_UpperCAmelCase : Optional[float] = None ,_UpperCAmelCase : Optional[bool] = None ,_UpperCAmelCase : Optional[Union[float, List[float]]] = None ,_UpperCAmelCase : Optional[Union[float, List[float]]] = None ,_UpperCAmelCase : Optional[Union[str, TensorType]] = None ,_UpperCAmelCase : bool = None ,_UpperCAmelCase : ChannelDimension = ChannelDimension.FIRST ,**_UpperCAmelCase : str ,):
_a : int = do_resize if do_resize is not None else self.do_resize
_a : Any = resample if resample is not None else self.resample
_a : Any = do_rescale if do_rescale is not None else self.do_rescale
_a : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor
_a : Optional[Any] = do_normalize if do_normalize is not None else self.do_normalize
_a : Union[str, Any] = image_mean if image_mean is not None else self.image_mean
_a : str = image_std if image_std is not None else self.image_std
_a : str = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
_a : Union[str, Any] = size if size is not None else self.size
_a : List[str] = get_size_dict(_UpperCAmelCase ,default_to_square=_UpperCAmelCase )
_a : str = make_list_of_images(_UpperCAmelCase )
if not valid_images(_UpperCAmelCase ):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.' )
if do_resize and size is None or resample is None:
raise ValueError('Size and resample must be specified if do_resize is True.' )
if do_rescale and rescale_factor is None:
raise ValueError('Rescale factor must be specified if do_rescale is True.' )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('Image mean and std must be specified if do_normalize is True.' )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
_a : List[Any] = [convert_to_rgb(_UpperCAmelCase ) for image in images]
# All transformations expect numpy arrays.
_a : Dict = [to_numpy_array(_UpperCAmelCase ) for image in images]
if do_resize:
_a : List[Any] = [self.resize(image=_UpperCAmelCase ,size=_UpperCAmelCase ,resample=_UpperCAmelCase ) for image in images]
if do_rescale:
_a : Dict = [self.rescale(image=_UpperCAmelCase ,scale=_UpperCAmelCase ) for image in images]
if do_normalize:
_a : int = [self.normalize(image=_UpperCAmelCase ,mean=_UpperCAmelCase ,std=_UpperCAmelCase ) for image in images]
_a : Optional[Any] = [to_channel_dimension_format(_UpperCAmelCase ,_UpperCAmelCase ) for image in images]
_a : str = BatchFeature(data={'pixel_values': images} ,tensor_type=_UpperCAmelCase )
return encoded_outputs
| 358
|
'''simple docstring'''
from __future__ import annotations
from math import gcd
def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ = 2 , lowerCAmelCase_ = 1 , lowerCAmelCase_ = 3 , ) -> int | None:
# A value less than 2 can cause an infinite loop in the algorithm.
if num < 2:
raise ValueError('The input value cannot be less than 2' )
# Because of the relationship between ``f(f(x))`` and ``f(x)``, this
# algorithm struggles to find factors that are divisible by two.
# As a workaround, we specifically check for two and even inputs.
# See: https://math.stackexchange.com/a/2856214/165820
if num > 2 and num % 2 == 0:
return 2
# Pollard's Rho algorithm requires a function that returns pseudorandom
# values between 0 <= X < ``num``. It doesn't need to be random in the
# sense that the output value is cryptographically secure or difficult
# to calculate, it only needs to be random in the sense that all output
# values should be equally likely to appear.
# For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num``
# However, the success of Pollard's algorithm isn't guaranteed and is
# determined in part by the initial seed and the chosen random function.
# To make retries easier, we will instead use ``f(x) = (x**2 + C) % num``
# where ``C`` is a value that we can modify between each attempt.
def rand_fn(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> int:
return (pow(lowerCAmelCase_ , 2 ) + step) % modulus
for _ in range(lowerCAmelCase_ ):
# These track the position within the cycle detection logic.
_a : Optional[int] = seed
_a : str = seed
while True:
# At each iteration, the tortoise moves one step and the hare moves two.
_a : str = rand_fn(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
_a : Dict = rand_fn(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
_a : Tuple = rand_fn(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
# At some point both the tortoise and the hare will enter a cycle whose
# length ``p`` is a divisor of ``num``. Once in that cycle, at some point
# the tortoise and hare will end up on the same value modulo ``p``.
# We can detect when this happens because the position difference between
# the tortoise and the hare will share a common divisor with ``num``.
_a : Optional[Any] = gcd(hare - tortoise , lowerCAmelCase_ )
if divisor == 1:
# No common divisor yet, just keep searching.
continue
else:
# We found a common divisor!
if divisor == num:
# Unfortunately, the divisor is ``num`` itself and is useless.
break
else:
# The divisor is a nontrivial factor of ``num``!
return divisor
# If we made it here, then this attempt failed.
# We need to pick a new starting seed for the tortoise and hare
# in addition to a new step value for the random function.
# To keep this example implementation deterministic, the
# new values will be generated based on currently available
# values instead of using something like ``random.randint``.
# We can use the hare's position as the new seed.
# This is actually what Richard Brent's the "optimized" variant does.
_a : Union[str, Any] = hare
# The new step value for the random function can just be incremented.
# At first the results will be similar to what the old function would
# have produced, but the value will quickly diverge after a bit.
step += 1
# We haven't found a divisor within the requested number of attempts.
# We were unlucky or ``num`` itself is actually prime.
return None
if __name__ == "__main__":
import argparse
__lowerCAmelCase = argparse.ArgumentParser()
parser.add_argument(
'''num''',
type=int,
help='''The value to find a divisor of''',
)
parser.add_argument(
'''--attempts''',
type=int,
default=3,
help='''The number of attempts before giving up''',
)
__lowerCAmelCase = parser.parse_args()
__lowerCAmelCase = pollard_rho(args.num, attempts=args.attempts)
if divisor is None:
print(f"""{args.num} is probably prime""")
else:
__lowerCAmelCase = args.num // divisor
print(f"""{args.num} = {divisor} * {quotient}""")
| 358
| 1
|
"""simple docstring"""
import warnings
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class A_ ( snake_case_ ):
UpperCAmelCase__ = ['''image_processor''', '''tokenizer''']
UpperCAmelCase__ = '''LayoutLMv3ImageProcessor'''
UpperCAmelCase__ = ('''LayoutLMv3Tokenizer''', '''LayoutLMv3TokenizerFast''')
def __init__( self : Union[str, Any] , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Optional[Any]=None , **__lowerCamelCase : Dict ) -> Tuple:
__magic_name__ = 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 , )
__magic_name__ = kwargs.pop("feature_extractor" )
__magic_name__ = 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 : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __lowerCamelCase : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , __lowerCamelCase : Union[List[List[int]], List[List[List[int]]]] = None , __lowerCamelCase : Optional[Union[List[int], List[List[int]]]] = None , __lowerCamelCase : bool = True , __lowerCamelCase : Union[bool, str, PaddingStrategy] = False , __lowerCamelCase : Union[bool, str, TruncationStrategy] = None , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : int = 0 , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : Optional[bool] = None , __lowerCamelCase : Optional[bool] = None , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , __lowerCamelCase : bool = True , __lowerCamelCase : Optional[Union[str, TensorType]] = None , **__lowerCamelCase : List[str] , ) -> 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
__magic_name__ = self.image_processor(images=__lowerCamelCase , return_tensors=__lowerCamelCase )
# second, apply the tokenizer
if text is not None and self.image_processor.apply_ocr and text_pair is None:
if isinstance(__lowerCamelCase , __lowerCamelCase ):
__magic_name__ = [text] # add batch dimension (as the image processor always adds a batch dimension)
__magic_name__ = features["words"]
__magic_name__ = 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=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , )
# add pixel values
__magic_name__ = features.pop("pixel_values" )
if return_overflowing_tokens is True:
__magic_name__ = self.get_overflowing_images(__lowerCamelCase , encoded_inputs["overflow_to_sample_mapping"] )
__magic_name__ = images
return encoded_inputs
def _snake_case ( self : Tuple , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int ) -> Union[str, Any]:
# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
__magic_name__ = []
for sample_idx in overflow_to_sample_mapping:
images_with_overflow.append(images[sample_idx] )
if len(__lowerCamelCase ) != len(__lowerCamelCase ):
raise ValueError(
"Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
f''' {len(__lowerCamelCase )} and {len(__lowerCamelCase )}''' )
return images_with_overflow
def _snake_case ( self : Optional[Any] , *__lowerCamelCase : Any , **__lowerCamelCase : Optional[Any] ) -> Union[str, Any]:
return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase )
def _snake_case ( self : str , *__lowerCamelCase : Any , **__lowerCamelCase : List[str] ) -> Dict:
return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase )
@property
def _snake_case ( self : Any ) -> str:
return ["input_ids", "bbox", "attention_mask", "pixel_values"]
@property
def _snake_case ( self : Union[str, Any] ) -> int:
warnings.warn(
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , __lowerCamelCase , )
return self.image_processor_class
@property
def _snake_case ( self : Any ) -> Tuple:
warnings.warn(
"`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , __lowerCamelCase , )
return self.image_processor
| 706
|
"""simple docstring"""
import argparse
import shlex
import runhouse as rh
if __name__ == "__main__":
# Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access
# setup instructions, if using on-demand hardware
# If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster
# If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster
# Throw an error if user passes both BYO and on-demand cluster args
# Otherwise, use default values
lowercase = argparse.ArgumentParser()
parser.add_argument('''--user''', type=str, default='''ubuntu''')
parser.add_argument('''--host''', type=str, default='''localhost''')
parser.add_argument('''--key_path''', type=str, default=None)
parser.add_argument('''--instance''', type=str, default='''V100:1''')
parser.add_argument('''--provider''', type=str, default='''cheapest''')
parser.add_argument('''--use_spot''', type=bool, default=False)
parser.add_argument('''--example''', type=str, default='''pytorch/text-generation/run_generation.py''')
lowercase , lowercase = parser.parse_known_args()
if args.host != "localhost":
if args.instance != "V100:1" or args.provider != "cheapest":
raise ValueError('''Cannot specify both BYO and on-demand cluster args''')
lowercase = rh.cluster(
name='''rh-cluster''', ips=[args.host], ssh_creds={'''ssh_user''': args.user, '''ssh_private_key''': args.key_path}
)
else:
lowercase = rh.cluster(
name='''rh-cluster''', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot
)
lowercase = args.example.rsplit('''/''', 1)[0]
# Set up remote environment
cluster.install_packages(['''pip:./''']) # Installs transformers from local source
# Note transformers is copied into the home directory on the remote machine, so we can install from there
cluster.run([f'''pip install -r transformers/examples/{example_dir}/requirements.txt'''])
cluster.run(['''pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117'''])
# Run example. You can bypass the CLI wrapper and paste your own code here.
cluster.run([f'''python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}'''])
# Alternatively, we can just import and run a training function (especially if there's no wrapper CLI):
# from my_script... import train
# reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard']
# launch_train_gpu = rh.function(fn=train,
# system=gpu,
# reqs=reqs,
# name='train_bert_glue')
#
# We can pass in arguments just like we would to a function:
# launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16
# stream_logs=True)
| 468
| 0
|
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_A = logging.get_logger(__name__)
_A = {
"""uw-madison/mra-base-512-4""": """https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json""",
}
class SCREAMING_SNAKE_CASE_ ( snake_case ):
__a : Any = '''mra'''
def __init__( self , lowercase=5_0_2_6_5 , lowercase=7_6_8 , lowercase=1_2 , lowercase=1_2 , lowercase=3_0_7_2 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=5_1_2 , lowercase=1 , lowercase=0.0_2 , lowercase=1e-5 , lowercase="absolute" , lowercase=4 , lowercase="full" , lowercase=0 , lowercase=0 , lowercase=1 , lowercase=0 , lowercase=2 , **lowercase , ) -> Any:
'''simple docstring'''
super().__init__(pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase , **lowercase )
__SCREAMING_SNAKE_CASE : Optional[int] = vocab_size
__SCREAMING_SNAKE_CASE : List[str] = max_position_embeddings
__SCREAMING_SNAKE_CASE : List[str] = hidden_size
__SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers
__SCREAMING_SNAKE_CASE : Any = num_attention_heads
__SCREAMING_SNAKE_CASE : List[str] = intermediate_size
__SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act
__SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob
__SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob
__SCREAMING_SNAKE_CASE : Optional[int] = initializer_range
__SCREAMING_SNAKE_CASE : Dict = type_vocab_size
__SCREAMING_SNAKE_CASE : int = layer_norm_eps
__SCREAMING_SNAKE_CASE : Tuple = position_embedding_type
__SCREAMING_SNAKE_CASE : Tuple = block_per_row
__SCREAMING_SNAKE_CASE : List[str] = approx_mode
__SCREAMING_SNAKE_CASE : Optional[int] = initial_prior_first_n_blocks
__SCREAMING_SNAKE_CASE : List[str] = initial_prior_diagonal_n_blocks
| 158
|
'''simple docstring'''
import logging
from dataclasses import dataclass, field
from typing import Optional
from seqaseq_trainer import arg_to_scheduler
from transformers import TrainingArguments
_A = logging.getLogger(__name__)
@dataclass
class SCREAMING_SNAKE_CASE_ ( snake_case ):
__a : Optional[float] = field(
default=0.0 , metadata={'''help''': '''The label smoothing epsilon to apply (if not zero).'''} )
__a : bool = field(default=snake_case , metadata={'''help''': '''Whether to SortishSamler or not.'''} )
__a : bool = field(
default=snake_case , metadata={'''help''': '''Whether to use generate to calculate generative metrics (ROUGE, BLEU).'''} )
__a : bool = field(default=snake_case , metadata={'''help''': '''whether to use adafactor'''} )
__a : Optional[float] = field(
default=snake_case , metadata={'''help''': '''Encoder layer dropout probability. Goes into model.config.'''} )
__a : Optional[float] = field(
default=snake_case , metadata={'''help''': '''Decoder layer dropout probability. Goes into model.config.'''} )
__a : Optional[float] = field(default=snake_case , metadata={'''help''': '''Dropout probability. Goes into model.config.'''} )
__a : Optional[float] = field(
default=snake_case , metadata={'''help''': '''Attention dropout probability. Goes into model.config.'''} )
__a : Optional[str] = field(
default='''linear''' , metadata={'''help''': f'''Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'''} , )
| 158
| 1
|
"""simple docstring"""
from typing import Optional, Union
import torch
from torch import nn
from ...configuration_utils import ConfigMixin, register_to_config
from ...models.modeling_utils import ModelMixin
class lowerCAmelCase ( snake_case__ , snake_case__ ):
'''simple docstring'''
@register_to_config
def __init__( self :str , lowerCamelCase_ :str = 7_6_8 , ) -> List[Any]:
"""simple docstring"""
super().__init__()
UpperCamelCase__ = nn.Parameter(torch.zeros(1 , _SCREAMING_SNAKE_CASE ) )
UpperCamelCase__ = nn.Parameter(torch.ones(1 , _SCREAMING_SNAKE_CASE ) )
def lowerCamelCase__ ( self :Union[str, Any] , lowerCamelCase_ :Union[str, Any] = None , lowerCamelCase_ :Any = None , ) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase__ = nn.Parameter(self.mean.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) )
UpperCamelCase__ = nn.Parameter(self.std.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) )
return self
def lowerCamelCase__ ( self :Dict , lowerCamelCase_ :Dict ) -> Tuple:
"""simple docstring"""
UpperCamelCase__ = (embeds - self.mean) * 1.0 / self.std
return embeds
def lowerCamelCase__ ( self :Tuple , lowerCamelCase_ :Dict ) -> Tuple:
"""simple docstring"""
UpperCamelCase__ = (embeds * self.std) + self.mean
return embeds
| 713
|
"""simple docstring"""
import random
import unittest
import numpy as np
import transformers
from transformers import is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax
if is_flax_available():
import os
import jax.numpy as jnp
from jax import jit
from transformers import AutoTokenizer, FlaxAutoModelForCausalLM
from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model
A : str = '0.12' # assumed parallelism: 8
if is_torch_available():
import torch
def snake_case__ ( _snake_case : List[Any] , _snake_case : Union[str, Any] , _snake_case : Union[str, Any]=None ):
"""simple docstring"""
if rng is None:
UpperCamelCase__ = random.Random()
UpperCamelCase__ = 1
for dim in shape:
total_dims *= dim
UpperCamelCase__ = []
for _ in range(_snake_case ):
values.append(rng.randint(0 , vocab_size - 1 ) )
UpperCamelCase__ = np.array(_snake_case , dtype=jnp.intaa ).reshape(_snake_case )
return output
def snake_case__ ( _snake_case : Optional[Any] , _snake_case : List[str]=None ):
"""simple docstring"""
UpperCamelCase__ = ids_tensor(_snake_case , vocab_size=2 , rng=_snake_case )
# make sure that at least one token is attended to for each batch
UpperCamelCase__ = 1
return attn_mask
@require_flax
class lowerCAmelCase :
'''simple docstring'''
A = None
A = ()
def lowerCamelCase__ ( self :Any ) -> int:
"""simple docstring"""
UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
# cut to half length & take max batch_size 3
UpperCamelCase__ = 2
UpperCamelCase__ = inputs["input_ids"].shape[-1] // 2
UpperCamelCase__ = inputs["input_ids"][:max_batch_size, :sequence_length]
UpperCamelCase__ = jnp.ones_like(lowerCamelCase_ )
UpperCamelCase__ = attention_mask[:max_batch_size, :sequence_length]
# generate max 5 tokens
UpperCamelCase__ = input_ids.shape[-1] + 5
if config.eos_token_id is not None and config.pad_token_id is None:
# hack to allow generate for models such as GPT2 as is done in `generate()`
UpperCamelCase__ = config.eos_token_id
return config, input_ids, attention_mask, max_length
@is_pt_flax_cross_test
def lowerCamelCase__ ( self :Optional[int] ) -> Optional[int]:
"""simple docstring"""
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config()
UpperCamelCase__ = False
UpperCamelCase__ = max_length
UpperCamelCase__ = 0
for model_class in self.all_generative_model_classes:
UpperCamelCase__ = model_class(lowerCamelCase_ )
UpperCamelCase__ = model_class.__name__[4:] # Skip the "Flax" at the beginning
UpperCamelCase__ = getattr(lowerCamelCase_ , lowerCamelCase_ )
UpperCamelCase__ = pt_model_class(lowerCamelCase_ ).eval()
UpperCamelCase__ = load_flax_weights_in_pytorch_model(lowerCamelCase_ , flax_model.params )
UpperCamelCase__ = flax_model.generate(lowerCamelCase_ ).sequences
UpperCamelCase__ = pt_model.generate(torch.tensor(lowerCamelCase_ , dtype=torch.long ) )
if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]:
UpperCamelCase__ = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]]
self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() )
def lowerCamelCase__ ( self :Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config()
UpperCamelCase__ = False
UpperCamelCase__ = max_length
for model_class in self.all_generative_model_classes:
UpperCamelCase__ = model_class(lowerCamelCase_ )
UpperCamelCase__ = model.generate(lowerCamelCase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowerCamelCase_ )
UpperCamelCase__ = jit(model.generate )
UpperCamelCase__ = jit_generate(lowerCamelCase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def lowerCamelCase__ ( self :List[Any] ) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config()
UpperCamelCase__ = True
UpperCamelCase__ = max_length
for model_class in self.all_generative_model_classes:
UpperCamelCase__ = model_class(lowerCamelCase_ )
UpperCamelCase__ = model.generate(lowerCamelCase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowerCamelCase_ )
UpperCamelCase__ = jit(model.generate )
UpperCamelCase__ = jit_generate(lowerCamelCase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def lowerCamelCase__ ( self :Tuple ) -> int:
"""simple docstring"""
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config()
UpperCamelCase__ = False
UpperCamelCase__ = max_length
UpperCamelCase__ = 2
for model_class in self.all_generative_model_classes:
UpperCamelCase__ = model_class(lowerCamelCase_ )
UpperCamelCase__ = model.generate(lowerCamelCase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowerCamelCase_ )
UpperCamelCase__ = jit(model.generate )
UpperCamelCase__ = jit_generate(lowerCamelCase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def lowerCamelCase__ ( self :Union[str, Any] ) -> Tuple:
"""simple docstring"""
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config()
UpperCamelCase__ = False
UpperCamelCase__ = max_length
UpperCamelCase__ = 2
UpperCamelCase__ = 2
for model_class in self.all_generative_model_classes:
UpperCamelCase__ = model_class(lowerCamelCase_ )
UpperCamelCase__ = model.generate(lowerCamelCase_ ).sequences
self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences )
def lowerCamelCase__ ( self :Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config()
UpperCamelCase__ = True
UpperCamelCase__ = max_length
UpperCamelCase__ = 0.8
UpperCamelCase__ = 1_0
UpperCamelCase__ = 0.3
UpperCamelCase__ = 1
UpperCamelCase__ = 8
UpperCamelCase__ = 9
for model_class in self.all_generative_model_classes:
UpperCamelCase__ = model_class(lowerCamelCase_ )
UpperCamelCase__ = model.generate(lowerCamelCase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowerCamelCase_ )
UpperCamelCase__ = jit(model.generate )
UpperCamelCase__ = jit_generate(lowerCamelCase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def lowerCamelCase__ ( self :Any ) -> str:
"""simple docstring"""
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config()
UpperCamelCase__ = max_length
UpperCamelCase__ = 1
UpperCamelCase__ = 8
UpperCamelCase__ = 9
for model_class in self.all_generative_model_classes:
UpperCamelCase__ = model_class(lowerCamelCase_ )
UpperCamelCase__ = model.generate(lowerCamelCase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowerCamelCase_ )
UpperCamelCase__ = jit(model.generate )
UpperCamelCase__ = jit_generate(lowerCamelCase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def lowerCamelCase__ ( self :int ) -> Tuple:
"""simple docstring"""
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config()
UpperCamelCase__ = max_length
UpperCamelCase__ = 2
UpperCamelCase__ = 1
UpperCamelCase__ = 8
UpperCamelCase__ = 9
for model_class in self.all_generative_model_classes:
UpperCamelCase__ = model_class(lowerCamelCase_ )
UpperCamelCase__ = model.generate(lowerCamelCase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowerCamelCase_ )
UpperCamelCase__ = jit(model.generate )
UpperCamelCase__ = jit_generate(lowerCamelCase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def lowerCamelCase__ ( self :Tuple ) -> int:
"""simple docstring"""
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config()
# pad attention mask on the left
UpperCamelCase__ = attention_mask.at[(0, 0)].set(0 )
UpperCamelCase__ = False
UpperCamelCase__ = max_length
for model_class in self.all_generative_model_classes:
UpperCamelCase__ = model_class(lowerCamelCase_ )
UpperCamelCase__ = model.generate(lowerCamelCase_ , attention_mask=lowerCamelCase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowerCamelCase_ )
UpperCamelCase__ = jit(model.generate )
UpperCamelCase__ = jit_generate(lowerCamelCase_ , attention_mask=lowerCamelCase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def lowerCamelCase__ ( self :Tuple ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config()
# pad attention mask on the left
UpperCamelCase__ = attention_mask.at[(0, 0)].set(0 )
UpperCamelCase__ = True
UpperCamelCase__ = max_length
for model_class in self.all_generative_model_classes:
UpperCamelCase__ = model_class(lowerCamelCase_ )
UpperCamelCase__ = model.generate(lowerCamelCase_ , attention_mask=lowerCamelCase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowerCamelCase_ )
UpperCamelCase__ = jit(model.generate )
UpperCamelCase__ = jit_generate(lowerCamelCase_ , attention_mask=lowerCamelCase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
def lowerCamelCase__ ( self :List[Any] ) -> Any:
"""simple docstring"""
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = self._get_input_ids_and_config()
# pad attention mask on the left
UpperCamelCase__ = attention_mask.at[(0, 0)].set(0 )
UpperCamelCase__ = 2
UpperCamelCase__ = max_length
for model_class in self.all_generative_model_classes:
UpperCamelCase__ = model_class(lowerCamelCase_ )
UpperCamelCase__ = model.generate(lowerCamelCase_ , attention_mask=lowerCamelCase_ ).sequences
self.assertEqual(generation_outputs.shape[-1] , lowerCamelCase_ )
UpperCamelCase__ = jit(model.generate )
UpperCamelCase__ = jit_generate(lowerCamelCase_ , attention_mask=lowerCamelCase_ ).sequences
self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() )
@require_flax
class lowerCAmelCase ( unittest.TestCase ):
'''simple docstring'''
def lowerCamelCase__ ( self :Tuple ) -> Any:
"""simple docstring"""
UpperCamelCase__ = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-bert" )
UpperCamelCase__ = FlaxAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-bert-flax-only" )
UpperCamelCase__ = "Hello world"
UpperCamelCase__ = tokenizer(lowerCamelCase_ , return_tensors="np" ).input_ids
# typos are quickly detected (the correct argument is `do_sample`)
with self.assertRaisesRegex(lowerCamelCase_ , "do_samples" ):
model.generate(lowerCamelCase_ , do_samples=lowerCamelCase_ )
# arbitrary arguments that will not be used anywhere are also not accepted
with self.assertRaisesRegex(lowerCamelCase_ , "foo" ):
UpperCamelCase__ = {"foo": "bar"}
model.generate(lowerCamelCase_ , **lowerCamelCase_ )
| 304
| 0
|
"""simple docstring"""
import numpy as np
def lowercase__ ( lowercase_ ) -> Optional[Any]:
"""simple docstring"""
return (2 / (1 + np.exp(-2 * vector ))) - 1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 624
|
'''simple docstring'''
import pytest
from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.text import TextDatasetReader
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
assert dataset.num_rows == 4
assert dataset.num_columns == 1
assert dataset.column_names == ["text"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
_snake_case = tmp_path / "cache"
_snake_case = {"text": "string"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
_snake_case = TextDatasetReader(SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ ).read()
_check_text_dataset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
@pytest.mark.parametrize(
"features" , [
None,
{"text": "string"},
{"text": "int32"},
{"text": "float32"},
] , )
def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
_snake_case = tmp_path / "cache"
_snake_case = {"text": "string"}
_snake_case = features.copy() if features else default_expected_features
_snake_case = (
Features({feature: Value(SCREAMING_SNAKE_CASE__ ) for feature, dtype in features.items()} ) if features is not None else None
)
_snake_case = TextDatasetReader(SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ ).read()
_check_text_dataset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
_snake_case = tmp_path / "cache"
_snake_case = {"text": "string"}
_snake_case = TextDatasetReader(SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ ).read()
_check_text_dataset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize("path_type" , [str, list] )
def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
if issubclass(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
_snake_case = text_path
elif issubclass(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
_snake_case = [text_path]
_snake_case = tmp_path / "cache"
_snake_case = {"text": "string"}
_snake_case = TextDatasetReader(SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ ).read()
_check_text_dataset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=("train",) ):
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
for split in splits:
_snake_case = dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 1
assert dataset.column_names == ["text"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
_snake_case = tmp_path / "cache"
_snake_case = {"text": "string"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
_snake_case = TextDatasetReader({"train": text_path} , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ ).read()
_check_text_datasetdict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
@pytest.mark.parametrize(
"features" , [
None,
{"text": "string"},
{"text": "int32"},
{"text": "float32"},
] , )
def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
_snake_case = tmp_path / "cache"
# CSV file loses col_1 string dtype information: default now is "int64" instead of "string"
_snake_case = {"text": "string"}
_snake_case = features.copy() if features else default_expected_features
_snake_case = (
Features({feature: Value(SCREAMING_SNAKE_CASE__ ) for feature, dtype in features.items()} ) if features is not None else None
)
_snake_case = TextDatasetReader({"train": text_path} , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ ).read()
_check_text_datasetdict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
if split:
_snake_case = {split: text_path}
else:
_snake_case = "train"
_snake_case = {"train": text_path, "test": text_path}
_snake_case = tmp_path / "cache"
_snake_case = {"text": "string"}
_snake_case = TextDatasetReader(SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ ).read()
_check_text_datasetdict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
| 672
| 0
|
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
a__ : List[str] = logging.get_logger(__name__)
a__ : int = {
'''microsoft/swin-tiny-patch4-window7-224''': (
'''https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json'''
),
# See all Swin models at https://huggingface.co/models?filter=swin
}
class a_ ( a__ , a__ ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : List[str] = 'swin'
__SCREAMING_SNAKE_CASE : List[str] = {
'num_attention_heads': 'num_heads',
'num_hidden_layers': 'num_layers',
}
def __init__( self , _lowerCamelCase=224 , _lowerCamelCase=4 , _lowerCamelCase=3 , _lowerCamelCase=96 , _lowerCamelCase=[2, 2, 6, 2] , _lowerCamelCase=[3, 6, 12, 24] , _lowerCamelCase=7 , _lowerCamelCase=4.0 , _lowerCamelCase=True , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=0.1 , _lowerCamelCase="gelu" , _lowerCamelCase=False , _lowerCamelCase=0.0_2 , _lowerCamelCase=1e-5 , _lowerCamelCase=32 , _lowerCamelCase=None , _lowerCamelCase=None , **_lowerCamelCase , ) ->List[Any]:
super().__init__(**_lowerCamelCase )
SCREAMING_SNAKE_CASE : Tuple = image_size
SCREAMING_SNAKE_CASE : str = patch_size
SCREAMING_SNAKE_CASE : Any = num_channels
SCREAMING_SNAKE_CASE : int = embed_dim
SCREAMING_SNAKE_CASE : Optional[Any] = depths
SCREAMING_SNAKE_CASE : str = len(_lowerCamelCase )
SCREAMING_SNAKE_CASE : int = num_heads
SCREAMING_SNAKE_CASE : Optional[Any] = window_size
SCREAMING_SNAKE_CASE : Dict = mlp_ratio
SCREAMING_SNAKE_CASE : Union[str, Any] = qkv_bias
SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob
SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE : Any = drop_path_rate
SCREAMING_SNAKE_CASE : Optional[int] = hidden_act
SCREAMING_SNAKE_CASE : Any = use_absolute_embeddings
SCREAMING_SNAKE_CASE : Any = layer_norm_eps
SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range
SCREAMING_SNAKE_CASE : Optional[Any] = encoder_stride
# we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
# this indicates the channel dimension after the last stage of the model
SCREAMING_SNAKE_CASE : Union[str, Any] = int(embed_dim * 2 ** (len(_lowerCamelCase ) - 1) )
SCREAMING_SNAKE_CASE : Optional[int] = ['''stem'''] + [F"""stage{idx}""" for idx in range(1 , len(_lowerCamelCase ) + 1 )]
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = get_aligned_output_features_output_indices(
out_features=_lowerCamelCase , out_indices=_lowerCamelCase , stage_names=self.stage_names )
class a_ ( a__ ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : int = version.parse('1.11' )
@property
def __lowerCAmelCase ( self ) ->Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
] )
@property
def __lowerCAmelCase ( self ) ->float:
return 1e-4
| 702
|
import inspect
import unittest
from transformers import MobileNetVaConfig
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 MobileNetVaForImageClassification, MobileNetVaModel
from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import MobileNetVaImageProcessor
class a_ ( a__ ):
"""simple docstring"""
def __lowerCAmelCase ( self ) ->int:
SCREAMING_SNAKE_CASE : Optional[int] = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(_lowerCamelCase , '''tf_padding''' ) )
self.parent.assertTrue(hasattr(_lowerCamelCase , '''depth_multiplier''' ) )
class a_ :
"""simple docstring"""
def __init__( self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=3 , _lowerCamelCase=32 , _lowerCamelCase=0.2_5 , _lowerCamelCase=8 , _lowerCamelCase=True , _lowerCamelCase=1024 , _lowerCamelCase=32 , _lowerCamelCase="relu6" , _lowerCamelCase=0.1 , _lowerCamelCase=0.0_2 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=10 , _lowerCamelCase=None , ) ->List[Any]:
SCREAMING_SNAKE_CASE : Union[str, Any] = parent
SCREAMING_SNAKE_CASE : Tuple = batch_size
SCREAMING_SNAKE_CASE : str = num_channels
SCREAMING_SNAKE_CASE : Dict = image_size
SCREAMING_SNAKE_CASE : Optional[int] = depth_multiplier
SCREAMING_SNAKE_CASE : Optional[Any] = min_depth
SCREAMING_SNAKE_CASE : Union[str, Any] = tf_padding
SCREAMING_SNAKE_CASE : Optional[Any] = int(last_hidden_size * depth_multiplier )
SCREAMING_SNAKE_CASE : Any = output_stride
SCREAMING_SNAKE_CASE : List[Any] = hidden_act
SCREAMING_SNAKE_CASE : List[str] = classifier_dropout_prob
SCREAMING_SNAKE_CASE : int = use_labels
SCREAMING_SNAKE_CASE : int = is_training
SCREAMING_SNAKE_CASE : Any = num_labels
SCREAMING_SNAKE_CASE : List[Any] = initializer_range
SCREAMING_SNAKE_CASE : Dict = scope
def __lowerCAmelCase ( self ) ->str:
SCREAMING_SNAKE_CASE : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
SCREAMING_SNAKE_CASE : Any = None
SCREAMING_SNAKE_CASE : Optional[Any] = None
if self.use_labels:
SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size] , self.num_labels )
SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
SCREAMING_SNAKE_CASE : Any = self.get_config()
return config, pixel_values, labels, pixel_labels
def __lowerCAmelCase ( self ) ->Any:
return MobileNetVaConfig(
num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , )
def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->int:
SCREAMING_SNAKE_CASE : str = MobileNetVaModel(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
SCREAMING_SNAKE_CASE : Union[str, Any] = model(_lowerCamelCase )
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 , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ->List[Any]:
SCREAMING_SNAKE_CASE : str = self.num_labels
SCREAMING_SNAKE_CASE : List[str] = MobileNetVaForImageClassification(_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
SCREAMING_SNAKE_CASE : str = model(_lowerCamelCase , labels=_lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __lowerCAmelCase ( self ) ->Optional[int]:
SCREAMING_SNAKE_CASE : str = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = config_and_inputs
SCREAMING_SNAKE_CASE : str = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class a_ ( a__ , a__ , unittest.TestCase ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : str = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
__SCREAMING_SNAKE_CASE : Union[str, Any] = (
{'feature-extraction': MobileNetVaModel, 'image-classification': MobileNetVaForImageClassification}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE : int = False
__SCREAMING_SNAKE_CASE : Tuple = False
__SCREAMING_SNAKE_CASE : Dict = False
__SCREAMING_SNAKE_CASE : Optional[int] = False
def __lowerCAmelCase ( self ) ->str:
SCREAMING_SNAKE_CASE : int = MobileNetVaModelTester(self )
SCREAMING_SNAKE_CASE : Optional[Any] = MobileNetVaConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase )
def __lowerCAmelCase ( self ) ->Union[str, Any]:
self.config_tester.run_common_tests()
@unittest.skip(reason='''MobileNetV1 does not use inputs_embeds''' )
def __lowerCAmelCase ( self ) ->List[str]:
pass
@unittest.skip(reason='''MobileNetV1 does not support input and output embeddings''' )
def __lowerCAmelCase ( self ) ->str:
pass
@unittest.skip(reason='''MobileNetV1 does not output attentions''' )
def __lowerCAmelCase ( self ) ->Tuple:
pass
def __lowerCAmelCase ( self ) ->Any:
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE : Optional[int] = model_class(_lowerCamelCase )
SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
SCREAMING_SNAKE_CASE : int = [*signature.parameters.keys()]
SCREAMING_SNAKE_CASE : int = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , _lowerCamelCase )
def __lowerCAmelCase ( self ) ->Optional[int]:
SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_lowerCamelCase )
def __lowerCAmelCase ( self ) ->Union[str, Any]:
def check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ):
SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
with torch.no_grad():
SCREAMING_SNAKE_CASE : Dict = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) )
SCREAMING_SNAKE_CASE : Any = outputs.hidden_states
SCREAMING_SNAKE_CASE : Tuple = 26
self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase )
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE : Tuple = True
check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
SCREAMING_SNAKE_CASE : Optional[Any] = True
check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
def __lowerCAmelCase ( self ) ->str:
SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase )
@slow
def __lowerCAmelCase ( self ) ->List[Any]:
for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE : Union[str, Any] = MobileNetVaModel.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
def UpperCAmelCase_( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : int = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_torch
@require_vision
class a_ ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def __lowerCAmelCase ( self ) ->Any:
return (
MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v1_1.0_224''' ) if is_vision_available() else None
)
@slow
def __lowerCAmelCase ( self ) ->Union[str, Any]:
SCREAMING_SNAKE_CASE : Dict = MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v1_1.0_224''' ).to(_lowerCamelCase )
SCREAMING_SNAKE_CASE : Optional[Any] = self.default_image_processor
SCREAMING_SNAKE_CASE : Any = prepare_img()
SCREAMING_SNAKE_CASE : str = image_processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
# forward pass
with torch.no_grad():
SCREAMING_SNAKE_CASE : Union[str, Any] = model(**_lowerCamelCase )
# verify the logits
SCREAMING_SNAKE_CASE : Dict = torch.Size((1, 1001) )
self.assertEqual(outputs.logits.shape , _lowerCamelCase )
SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) )
| 333
| 0
|
def __SCREAMING_SNAKE_CASE ( a__ : Dict ) -> Optional[Any]:
__A : Optional[Any] = len(a__ )
for i in range(length - 1 ):
__A : Optional[Any] = i
for k in range(i + 1 ,a__ ):
if collection[k] < collection[least]:
__A : Dict = k
if least != i:
__A , __A : str = (collection[i], collection[least])
return collection
if __name__ == "__main__":
UpperCAmelCase_ : Any = input('''Enter numbers separated by a comma:\n''').strip()
UpperCAmelCase_ : Optional[Any] = [int(item) for item in user_input.split(''',''')]
print(selection_sort(unsorted))
| 17
|
'''simple docstring'''
def _a ( __lowerCAmelCase : str ):
"""simple docstring"""
snake_case__ : str = len(__lowerCAmelCase )
snake_case__ : Optional[Any] = sum(__lowerCAmelCase )
snake_case__ : Any = [[False for x in range(s + 1 )] for y in range(n + 1 )]
for i in range(1 , n + 1 ):
snake_case__ : Dict = True
for i in range(1 , s + 1 ):
snake_case__ : Dict = False
for i in range(1 , n + 1 ):
for j in range(1 , s + 1 ):
snake_case__ : Tuple = dp[i][j - 1]
if arr[i - 1] <= j:
snake_case__ : str = dp[i][j] or dp[i - 1][j - arr[i - 1]]
for j in range(int(s / 2 ) , -1 , -1 ):
if dp[n][j] is True:
snake_case__ : Union[str, Any] = s - 2 * j
break
return diff
| 347
| 0
|
'''simple docstring'''
import argparse
from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird
from transformers.utils import logging
logging.set_verbosity_info()
def __UpperCAmelCase ( __magic_name__ ,__magic_name__ ,__magic_name__ ,__magic_name__ )-> str:
"""simple docstring"""
snake_case_ : Optional[int] = BigBirdConfig.from_json_file(__magic_name__ )
print(F'''Building PyTorch model from configuration: {config}''' )
if is_trivia_qa:
snake_case_ : str = BigBirdForQuestionAnswering(__magic_name__ )
else:
snake_case_ : List[Any] = BigBirdForPreTraining(__magic_name__ )
# Load weights from tf checkpoint
load_tf_weights_in_big_bird(__magic_name__ ,__magic_name__ ,is_trivia_qa=__magic_name__ )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
model.save_pretrained(__magic_name__ )
if __name__ == "__main__":
__lowerCamelCase : List[Any] = 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(
'''--big_bird_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.'''
)
parser.add_argument(
'''--is_trivia_qa''', action='''store_true''', help='''Whether to convert a model with a trivia_qa head.'''
)
__lowerCamelCase : Dict = parser.parse_args()
convert_tf_checkpoint_to_pytorch(
args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa
)
| 656
|
'''simple docstring'''
import unittest
from transformers import (
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
Pipeline,
ZeroShotClassificationPipeline,
pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow
from .test_pipelines_common import ANY
# These 2 model types require different inputs than those of the usual text models.
__lowerCamelCase : List[str] = {'''LayoutLMv2Config''', '''LayoutLMv3Config'''}
@is_pipeline_test
class A_ (unittest.TestCase ):
"""simple docstring"""
a__ = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
a__ = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
if model_mapping is not None:
a__ = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
if tf_model_mapping is not None:
a__ = {
config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
}
def _A ( self :Tuple , lowerCAmelCase__ :Tuple , lowerCAmelCase__ :Union[str, Any] , lowerCAmelCase__ :Dict ) -> Any:
'''simple docstring'''
snake_case_ : Optional[Any] = ZeroShotClassificationPipeline(
model=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , candidate_labels=["polics", "health"] )
return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]
def _A ( self :List[str] , lowerCAmelCase__ :Optional[int] , lowerCAmelCase__ :Any ) -> Optional[Any]:
'''simple docstring'''
snake_case_ : Tuple = classifier("Who are you voting for in 2020?" , candidate_labels="politics" )
self.assertEqual(lowerCAmelCase__ , {"sequence": ANY(lowerCAmelCase__ ), "labels": [ANY(lowerCAmelCase__ )], "scores": [ANY(lowerCAmelCase__ )]} )
# No kwarg
snake_case_ : List[Any] = classifier("Who are you voting for in 2020?" , ["politics"] )
self.assertEqual(lowerCAmelCase__ , {"sequence": ANY(lowerCAmelCase__ ), "labels": [ANY(lowerCAmelCase__ )], "scores": [ANY(lowerCAmelCase__ )]} )
snake_case_ : Dict = classifier("Who are you voting for in 2020?" , candidate_labels=["politics"] )
self.assertEqual(lowerCAmelCase__ , {"sequence": ANY(lowerCAmelCase__ ), "labels": [ANY(lowerCAmelCase__ )], "scores": [ANY(lowerCAmelCase__ )]} )
snake_case_ : int = classifier("Who are you voting for in 2020?" , candidate_labels="politics, public health" )
self.assertEqual(
lowerCAmelCase__ , {"sequence": ANY(lowerCAmelCase__ ), "labels": [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )], "scores": [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )]} )
self.assertAlmostEqual(sum(nested_simplify(outputs["scores"] ) ) , 1.0 )
snake_case_ : Optional[int] = classifier("Who are you voting for in 2020?" , candidate_labels=["politics", "public health"] )
self.assertEqual(
lowerCAmelCase__ , {"sequence": ANY(lowerCAmelCase__ ), "labels": [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )], "scores": [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )]} )
self.assertAlmostEqual(sum(nested_simplify(outputs["scores"] ) ) , 1.0 )
snake_case_ : str = classifier(
"Who are you voting for in 2020?" , candidate_labels="politics" , hypothesis_template="This text is about {}" )
self.assertEqual(lowerCAmelCase__ , {"sequence": ANY(lowerCAmelCase__ ), "labels": [ANY(lowerCAmelCase__ )], "scores": [ANY(lowerCAmelCase__ )]} )
# https://github.com/huggingface/transformers/issues/13846
snake_case_ : Dict = classifier(["I am happy"] , ["positive", "negative"] )
self.assertEqual(
lowerCAmelCase__ , [
{"sequence": ANY(lowerCAmelCase__ ), "labels": [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )], "scores": [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )]}
for i in range(1 )
] , )
snake_case_ : Tuple = classifier(["I am happy", "I am sad"] , ["positive", "negative"] )
self.assertEqual(
lowerCAmelCase__ , [
{"sequence": ANY(lowerCAmelCase__ ), "labels": [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )], "scores": [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )]}
for i in range(2 )
] , )
with self.assertRaises(lowerCAmelCase__ ):
classifier("" , candidate_labels="politics" )
with self.assertRaises(lowerCAmelCase__ ):
classifier(lowerCAmelCase__ , candidate_labels="politics" )
with self.assertRaises(lowerCAmelCase__ ):
classifier("Who are you voting for in 2020?" , candidate_labels="" )
with self.assertRaises(lowerCAmelCase__ ):
classifier("Who are you voting for in 2020?" , candidate_labels=lowerCAmelCase__ )
with self.assertRaises(lowerCAmelCase__ ):
classifier(
"Who are you voting for in 2020?" , candidate_labels="politics" , hypothesis_template="Not formatting template" , )
with self.assertRaises(lowerCAmelCase__ ):
classifier(
"Who are you voting for in 2020?" , candidate_labels="politics" , hypothesis_template=lowerCAmelCase__ , )
self.run_entailment_id(lowerCAmelCase__ )
def _A ( self :List[Any] , lowerCAmelCase__ :Pipeline ) -> Union[str, Any]:
'''simple docstring'''
snake_case_ : int = zero_shot_classifier.model.config
snake_case_ : Optional[int] = config.labelaid
snake_case_ : Tuple = zero_shot_classifier.entailment_id
snake_case_ : Optional[Any] = {"LABEL_0": 0, "LABEL_1": 1, "LABEL_2": 2}
self.assertEqual(zero_shot_classifier.entailment_id , -1 )
snake_case_ : Tuple = {"entailment": 0, "neutral": 1, "contradiction": 2}
self.assertEqual(zero_shot_classifier.entailment_id , 0 )
snake_case_ : str = {"ENTAIL": 0, "NON-ENTAIL": 1}
self.assertEqual(zero_shot_classifier.entailment_id , 0 )
snake_case_ : str = {"ENTAIL": 2, "NEUTRAL": 1, "CONTR": 0}
self.assertEqual(zero_shot_classifier.entailment_id , 2 )
snake_case_ : List[str] = original_labelaid
self.assertEqual(lowerCAmelCase__ , zero_shot_classifier.entailment_id )
@require_torch
def _A ( self :Tuple ) -> Any:
'''simple docstring'''
snake_case_ : List[Any] = pipeline(
"zero-shot-classification" , model="sshleifer/tiny-distilbert-base-cased-distilled-squad" , framework="pt" , )
# There was a regression in 4.10 for this
# Adding a test so we don't make the mistake again.
# https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499
zero_shot_classifier(
"Who are you voting for in 2020?" * 100 , candidate_labels=["politics", "public health", "science"] )
@require_torch
def _A ( self :Optional[Any] ) -> Tuple:
'''simple docstring'''
snake_case_ : Union[str, Any] = pipeline(
"zero-shot-classification" , model="sshleifer/tiny-distilbert-base-cased-distilled-squad" , framework="pt" , )
snake_case_ : int = zero_shot_classifier(
"Who are you voting for in 2020?" , candidate_labels=["politics", "public health", "science"] )
self.assertEqual(
nested_simplify(lowerCAmelCase__ ) , {
"sequence": "Who are you voting for in 2020?",
"labels": ["science", "public health", "politics"],
"scores": [0.3_3_3, 0.3_3_3, 0.3_3_3],
} , )
@require_tf
def _A ( self :Union[str, Any] ) -> Dict:
'''simple docstring'''
snake_case_ : List[str] = pipeline(
"zero-shot-classification" , model="sshleifer/tiny-distilbert-base-cased-distilled-squad" , framework="tf" , )
snake_case_ : Optional[int] = zero_shot_classifier(
"Who are you voting for in 2020?" , candidate_labels=["politics", "public health", "science"] )
self.assertEqual(
nested_simplify(lowerCAmelCase__ ) , {
"sequence": "Who are you voting for in 2020?",
"labels": ["science", "public health", "politics"],
"scores": [0.3_3_3, 0.3_3_3, 0.3_3_3],
} , )
@slow
@require_torch
def _A ( self :Union[str, Any] ) -> int:
'''simple docstring'''
snake_case_ : int = pipeline("zero-shot-classification" , model="roberta-large-mnli" , framework="pt" )
snake_case_ : str = zero_shot_classifier(
"Who are you voting for in 2020?" , candidate_labels=["politics", "public health", "science"] )
self.assertEqual(
nested_simplify(lowerCAmelCase__ ) , {
"sequence": "Who are you voting for in 2020?",
"labels": ["politics", "public health", "science"],
"scores": [0.9_7_6, 0.0_1_5, 0.0_0_9],
} , )
snake_case_ : Optional[int] = zero_shot_classifier(
"The dominant sequence transduction models are based on complex recurrent or convolutional neural networks"
" in an encoder-decoder configuration. The best performing models also connect the encoder and decoder"
" through an attention mechanism. We propose a new simple network architecture, the Transformer, based"
" solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two"
" machine translation tasks show these models to be superior in quality while being more parallelizable"
" and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014"
" English-to-German translation task, improving over the existing best results, including ensembles by"
" over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new"
" single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small"
" fraction of the training costs of the best models from the literature. We show that the Transformer"
" generalizes well to other tasks by applying it successfully to English constituency parsing both with"
" large and limited training data." , candidate_labels=["machine learning", "statistics", "translation", "vision"] , multi_label=lowerCAmelCase__ , )
self.assertEqual(
nested_simplify(lowerCAmelCase__ ) , {
"sequence": (
"The dominant sequence transduction models are based on complex recurrent or convolutional neural"
" networks in an encoder-decoder configuration. The best performing models also connect the"
" encoder and decoder through an attention mechanism. We propose a new simple network"
" architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence"
" and convolutions entirely. Experiments on two machine translation tasks show these models to be"
" superior in quality while being more parallelizable and requiring significantly less time to"
" train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,"
" improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014"
" English-to-French translation task, our model establishes a new single-model state-of-the-art"
" BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training"
" costs of the best models from the literature. We show that the Transformer generalizes well to"
" other tasks by applying it successfully to English constituency parsing both with large and"
" limited training data."
),
"labels": ["translation", "machine learning", "vision", "statistics"],
"scores": [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8],
} , )
@slow
@require_tf
def _A ( self :List[str] ) -> str:
'''simple docstring'''
snake_case_ : int = pipeline("zero-shot-classification" , model="roberta-large-mnli" , framework="tf" )
snake_case_ : Optional[Any] = zero_shot_classifier(
"Who are you voting for in 2020?" , candidate_labels=["politics", "public health", "science"] )
self.assertEqual(
nested_simplify(lowerCAmelCase__ ) , {
"sequence": "Who are you voting for in 2020?",
"labels": ["politics", "public health", "science"],
"scores": [0.9_7_6, 0.0_1_5, 0.0_0_9],
} , )
snake_case_ : Tuple = zero_shot_classifier(
"The dominant sequence transduction models are based on complex recurrent or convolutional neural networks"
" in an encoder-decoder configuration. The best performing models also connect the encoder and decoder"
" through an attention mechanism. We propose a new simple network architecture, the Transformer, based"
" solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two"
" machine translation tasks show these models to be superior in quality while being more parallelizable"
" and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014"
" English-to-German translation task, improving over the existing best results, including ensembles by"
" over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new"
" single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small"
" fraction of the training costs of the best models from the literature. We show that the Transformer"
" generalizes well to other tasks by applying it successfully to English constituency parsing both with"
" large and limited training data." , candidate_labels=["machine learning", "statistics", "translation", "vision"] , multi_label=lowerCAmelCase__ , )
self.assertEqual(
nested_simplify(lowerCAmelCase__ ) , {
"sequence": (
"The dominant sequence transduction models are based on complex recurrent or convolutional neural"
" networks in an encoder-decoder configuration. The best performing models also connect the"
" encoder and decoder through an attention mechanism. We propose a new simple network"
" architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence"
" and convolutions entirely. Experiments on two machine translation tasks show these models to be"
" superior in quality while being more parallelizable and requiring significantly less time to"
" train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,"
" improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014"
" English-to-French translation task, our model establishes a new single-model state-of-the-art"
" BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training"
" costs of the best models from the literature. We show that the Transformer generalizes well to"
" other tasks by applying it successfully to English constituency parsing both with large and"
" limited training data."
),
"labels": ["translation", "machine learning", "vision", "statistics"],
"scores": [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8],
} , )
| 656
| 1
|
'''simple docstring'''
import warnings
from ...utils import logging
from .image_processing_clip import CLIPImageProcessor
__a = logging.get_logger(__name__)
class A__ ( UpperCamelCase ):
"""simple docstring"""
def __init__( self : int , *lowerCAmelCase__ : Optional[Any] , **lowerCAmelCase__ : Optional[Any] ) -> None:
"""simple docstring"""
warnings.warn(
"The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
" use CLIPImageProcessor instead." , lowerCAmelCase__ , )
super().__init__(*lowerCAmelCase__ , **lowerCAmelCase__ )
| 494
|
'''simple docstring'''
def __UpperCAmelCase ( a_: int ):
if not isinstance(a_, a_ ):
_UpperCAmelCase : List[str] = f"""Input value of [number={number}] must be an integer"""
raise TypeError(a_ )
if number < 0:
return False
_UpperCAmelCase : Union[str, Any] = number * number
while number > 0:
if number % 10 != number_square % 10:
return False
number //= 10
number_square //= 10
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
| 494
| 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
lowerCamelCase_ = logging.get_logger(__name__)
lowerCamelCase_ = {
'''google/mobilenet_v1_1.0_224''': '''https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json''',
'''google/mobilenet_v1_0.75_192''': '''https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json''',
# See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
}
class UpperCamelCase_ (__A ):
__magic_name__ = '''mobilenet_v1'''
def __init__( self : int , lowerCAmelCase_ : Optional[Any]=3 , lowerCAmelCase_ : Optional[int]=224 , lowerCAmelCase_ : List[Any]=1.0 , lowerCAmelCase_ : List[str]=8 , lowerCAmelCase_ : Optional[Any]="relu6" , lowerCAmelCase_ : Union[str, Any]=True , lowerCAmelCase_ : int=0.9_9_9 , lowerCAmelCase_ : List[str]=0.0_2 , lowerCAmelCase_ : Tuple=0.0_0_1 , **lowerCAmelCase_ : Optional[Any] , ) -> List[str]:
super().__init__(**lowerCAmelCase_ )
if depth_multiplier <= 0:
raise ValueError("depth_multiplier must be greater than zero." )
UpperCAmelCase_ : Optional[int] = num_channels
UpperCAmelCase_ : Any = image_size
UpperCAmelCase_ : Union[str, Any] = depth_multiplier
UpperCAmelCase_ : List[str] = min_depth
UpperCAmelCase_ : Optional[int] = hidden_act
UpperCAmelCase_ : List[str] = tf_padding
UpperCAmelCase_ : List[Any] = classifier_dropout_prob
UpperCAmelCase_ : Dict = initializer_range
UpperCAmelCase_ : Tuple = layer_norm_eps
class UpperCamelCase_ (__A ):
__magic_name__ = version.parse('''1.11''' )
@property
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]:
return OrderedDict([("pixel_values", {0: "batch"})] )
@property
def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Mapping[str, Mapping[int, str]]:
if self.task == "image-classification":
return OrderedDict([("logits", {0: "batch"})] )
else:
return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})] )
@property
def _SCREAMING_SNAKE_CASE ( self : str ) -> float:
return 1e-4
| 463
|
"""simple docstring"""
import os
import pytest
from datasets import (
get_dataset_config_info,
get_dataset_config_names,
get_dataset_infos,
get_dataset_split_names,
inspect_dataset,
inspect_metric,
)
lowerCamelCase_ = pytest.mark.integration
@pytest.mark.parametrize("path" ,["paws", "csv"] )
def snake_case ( A__ ,A__ ):
inspect_dataset(A__ ,A__ )
UpperCAmelCase_ : Tuple = path + ".py"
assert script_name in os.listdir(A__ )
assert "__pycache__" not in os.listdir(A__ )
@pytest.mark.filterwarnings("ignore:inspect_metric is deprecated:FutureWarning" )
@pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" )
@pytest.mark.parametrize("path" ,["accuracy"] )
def snake_case ( A__ ,A__ ):
inspect_metric(A__ ,A__ )
UpperCAmelCase_ : List[str] = path + ".py"
assert script_name in os.listdir(A__ )
assert "__pycache__" not in os.listdir(A__ )
@pytest.mark.parametrize(
"path, config_name, expected_splits" ,[
("squad", "plain_text", ["train", "validation"]),
("dalle-mini/wit", "dalle-mini--wit", ["train"]),
("paws", "labeled_final", ["train", "test", "validation"]),
] ,)
def snake_case ( A__ ,A__ ,A__ ):
UpperCAmelCase_ : Dict = get_dataset_config_info(A__ ,config_name=A__ )
assert info.config_name == config_name
assert list(info.splits.keys() ) == expected_splits
@pytest.mark.parametrize(
"path, config_name, expected_exception" ,[
("paws", None, ValueError),
] ,)
def snake_case ( A__ ,A__ ,A__ ):
with pytest.raises(A__ ):
get_dataset_config_info(A__ ,config_name=A__ )
@pytest.mark.parametrize(
"path, expected" ,[
("squad", "plain_text"),
("acronym_identification", "default"),
("lhoestq/squad", "plain_text"),
("lhoestq/test", "default"),
("lhoestq/demo1", "lhoestq--demo1"),
("dalle-mini/wit", "dalle-mini--wit"),
] ,)
def snake_case ( A__ ,A__ ):
UpperCAmelCase_ : str = get_dataset_config_names(A__ )
assert expected in config_names
@pytest.mark.parametrize(
"path, expected_configs, expected_splits_in_first_config" ,[
("squad", ["plain_text"], ["train", "validation"]),
("dalle-mini/wit", ["dalle-mini--wit"], ["train"]),
("paws", ["labeled_final", "labeled_swap", "unlabeled_final"], ["train", "test", "validation"]),
] ,)
def snake_case ( A__ ,A__ ,A__ ):
UpperCAmelCase_ : List[str] = get_dataset_infos(A__ )
assert list(infos.keys() ) == expected_configs
UpperCAmelCase_ : List[str] = expected_configs[0]
assert expected_config in infos
UpperCAmelCase_ : int = infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys() ) == expected_splits_in_first_config
@pytest.mark.parametrize(
"path, expected_config, expected_splits" ,[
("squad", "plain_text", ["train", "validation"]),
("dalle-mini/wit", "dalle-mini--wit", ["train"]),
("paws", "labeled_final", ["train", "test", "validation"]),
] ,)
def snake_case ( A__ ,A__ ,A__ ):
UpperCAmelCase_ : Optional[Any] = get_dataset_infos(A__ )
assert expected_config in infos
UpperCAmelCase_ : Union[str, Any] = infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys() ) == expected_splits
@pytest.mark.parametrize(
"path, config_name, expected_exception" ,[
("paws", None, ValueError),
] ,)
def snake_case ( A__ ,A__ ,A__ ):
with pytest.raises(A__ ):
get_dataset_split_names(A__ ,config_name=A__ )
| 463
| 1
|
'''simple docstring'''
from __future__ import annotations
import copy
import inspect
import unittest
import numpy as np
from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
LayoutLMvaConfig,
TFLayoutLMvaForQuestionAnswering,
TFLayoutLMvaForSequenceClassification,
TFLayoutLMvaForTokenClassification,
TFLayoutLMvaModel,
)
if is_vision_available():
from PIL import Image
from transformers import LayoutLMvaImageProcessor
class __magic_name__ :
def __init__( self , snake_case_ , snake_case_=2 , snake_case_=3 , snake_case_=4 , snake_case_=2 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=36 , snake_case_=2 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=5_12 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=6 , snake_case_=6 , snake_case_=3 , snake_case_=4 , snake_case_=None , snake_case_=10_00 , ):
lowercase =parent
lowercase =batch_size
lowercase =num_channels
lowercase =image_size
lowercase =patch_size
lowercase =is_training
lowercase =use_input_mask
lowercase =use_token_type_ids
lowercase =use_labels
lowercase =vocab_size
lowercase =hidden_size
lowercase =num_hidden_layers
lowercase =num_attention_heads
lowercase =intermediate_size
lowercase =hidden_act
lowercase =hidden_dropout_prob
lowercase =attention_probs_dropout_prob
lowercase =max_position_embeddings
lowercase =type_vocab_size
lowercase =type_sequence_label_size
lowercase =initializer_range
lowercase =coordinate_size
lowercase =shape_size
lowercase =num_labels
lowercase =num_choices
lowercase =scope
lowercase =range_bbox
# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
lowercase =text_seq_length
lowercase =(image_size // patch_size) ** 2 + 1
lowercase =self.text_seq_length + self.image_seq_length
def _A( self ):
lowercase =ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size )
lowercase =ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox )
lowercase =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]:
lowercase =bbox[i, j, 3]
lowercase =bbox[i, j, 1]
lowercase =tmp_coordinate
if bbox[i, j, 2] < bbox[i, j, 0]:
lowercase =bbox[i, j, 2]
lowercase =bbox[i, j, 0]
lowercase =tmp_coordinate
lowercase =tf.constant(snake_case_ )
lowercase =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowercase =None
if self.use_input_mask:
lowercase =random_attention_mask([self.batch_size, self.text_seq_length] )
lowercase =None
if self.use_token_type_ids:
lowercase =ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size )
lowercase =None
lowercase =None
if self.use_labels:
lowercase =ids_tensor([self.batch_size] , self.type_sequence_label_size )
lowercase =ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels )
lowercase =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 _A( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ):
lowercase =TFLayoutLMvaModel(config=snake_case_ )
# text + image
lowercase =model(snake_case_ , pixel_values=snake_case_ , training=snake_case_ )
lowercase =model(
snake_case_ , bbox=snake_case_ , pixel_values=snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , training=snake_case_ , )
lowercase =model(snake_case_ , bbox=snake_case_ , pixel_values=snake_case_ , training=snake_case_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
# text only
lowercase =model(snake_case_ , training=snake_case_ )
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) )
# image only
lowercase =model({'''pixel_values''': pixel_values} , training=snake_case_ )
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) )
def _A( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ):
lowercase =self.num_labels
lowercase =TFLayoutLMvaForSequenceClassification(config=snake_case_ )
lowercase =model(
snake_case_ , bbox=snake_case_ , pixel_values=snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ , training=snake_case_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _A( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ):
lowercase =self.num_labels
lowercase =TFLayoutLMvaForTokenClassification(config=snake_case_ )
lowercase =model(
snake_case_ , bbox=snake_case_ , pixel_values=snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ , training=snake_case_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) )
def _A( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ):
lowercase =2
lowercase =TFLayoutLMvaForQuestionAnswering(config=snake_case_ )
lowercase =model(
snake_case_ , bbox=snake_case_ , pixel_values=snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , start_positions=snake_case_ , end_positions=snake_case_ , training=snake_case_ , )
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 ):
lowercase =self.prepare_config_and_inputs()
(lowercase) =config_and_inputs
lowercase ={
"""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 __magic_name__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ):
UpperCamelCase__ = (
(
TFLayoutLMvaModel,
TFLayoutLMvaForQuestionAnswering,
TFLayoutLMvaForSequenceClassification,
TFLayoutLMvaForTokenClassification,
)
if is_tf_available()
else ()
)
UpperCamelCase__ = (
{'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
if is_tf_available()
else {}
)
UpperCamelCase__ = False
UpperCamelCase__ = False
UpperCamelCase__ = False
def _A( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ):
return True
def _A( self , snake_case_ , snake_case_ , snake_case_=False ):
lowercase =copy.deepcopy(snake_case_ )
if model_class in get_values(snake_case_ ):
lowercase ={
k: tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) )
if isinstance(snake_case_ , tf.Tensor ) and v.ndim > 0
else v
for k, v in inputs_dict.items()
}
if return_labels:
if model_class in get_values(snake_case_ ):
lowercase =tf.ones(self.model_tester.batch_size , dtype=tf.intaa )
elif model_class in get_values(snake_case_ ):
lowercase =tf.zeros(self.model_tester.batch_size , dtype=tf.intaa )
lowercase =tf.zeros(self.model_tester.batch_size , dtype=tf.intaa )
elif model_class in get_values(snake_case_ ):
lowercase =tf.zeros(self.model_tester.batch_size , dtype=tf.intaa )
elif model_class in get_values(snake_case_ ):
lowercase =tf.zeros(
(self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa )
return inputs_dict
def _A( self ):
lowercase =TFLayoutLMvaModelTester(self )
lowercase =ConfigTester(self , config_class=snake_case_ , hidden_size=37 )
def _A( self ):
self.config_tester.run_common_tests()
def _A( self ):
lowercase =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase =model_class(snake_case_ )
if getattr(snake_case_ , '''hf_compute_loss''' , snake_case_ ):
# The number of elements in the loss should be the same as the number of elements in the label
lowercase =self._prepare_for_class(inputs_dict.copy() , snake_case_ , return_labels=snake_case_ )
lowercase =prepared_for_class[
sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=snake_case_ )[0]
]
lowercase =added_label.shape.as_list()[:1]
# Test that model correctly compute the loss with kwargs
lowercase =self._prepare_for_class(inputs_dict.copy() , snake_case_ , return_labels=snake_case_ )
lowercase =prepared_for_class.pop('''input_ids''' )
lowercase =model(snake_case_ , **snake_case_ )[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
lowercase =self._prepare_for_class(inputs_dict.copy() , snake_case_ , return_labels=snake_case_ )
lowercase =prepared_for_class.pop('''input_ids''' )
if "labels" in prepared_for_class:
lowercase =prepared_for_class["""labels"""].numpy()
if len(labels.shape ) > 1 and labels.shape[1] != 1:
lowercase =-1_00
lowercase =tf.convert_to_tensor(snake_case_ )
lowercase =model(snake_case_ , **snake_case_ )[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
lowercase =self._prepare_for_class(inputs_dict.copy() , snake_case_ , return_labels=snake_case_ )
lowercase =model(snake_case_ )[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
lowercase =self._prepare_for_class(inputs_dict.copy() , snake_case_ , return_labels=snake_case_ )
# Get keys that were added with the _prepare_for_class function
lowercase =prepared_for_class.keys() - inputs_dict.keys()
lowercase =inspect.signature(model.call ).parameters
lowercase =list(signature.keys() )
# Create a dictionary holding the location of the tensors in the tuple
lowercase ={0: """input_ids"""}
for label_key in label_keys:
lowercase =signature_names.index(snake_case_ )
lowercase =label_key
lowercase =sorted(tuple_index_mapping.items() )
# Initialize a list with their default values, update the values and convert to a tuple
lowercase =[]
for name in signature_names:
if name != "kwargs":
list_input.append(signature[name].default )
for index, value in sorted_tuple_index_mapping:
lowercase =prepared_for_class[value]
lowercase =tuple(snake_case_ )
# Send to model
lowercase =model(tuple_input[:-1] )[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] )
def _A( self ):
(
lowercase
) =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
def _A( self ):
(
lowercase
) =self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
lowercase =type
self.model_tester.create_and_check_model(snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
def _A( self ):
(
lowercase
) =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(
snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
def _A( self ):
(
lowercase
) =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(
snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
def _A( self ):
(
lowercase
) =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(
snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
@slow
def _A( self ):
for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowercase =TFLayoutLMvaModel.from_pretrained(snake_case_ )
self.assertIsNotNone(snake_case_ )
def UpperCamelCase ( ) -> Dict:
'''simple docstring'''
lowercase =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_tf
class __magic_name__ ( unittest.TestCase ):
@cached_property
def _A( self ):
return LayoutLMvaImageProcessor(apply_ocr=snake_case_ ) if is_vision_available() else None
@slow
def _A( self ):
lowercase =TFLayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base''' )
lowercase =self.default_image_processor
lowercase =prepare_img()
lowercase =image_processor(images=snake_case_ , return_tensors='''tf''' ).pixel_values
lowercase =tf.constant([[1, 2]] )
lowercase =tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 )
# forward pass
lowercase =model(input_ids=snake_case_ , bbox=snake_case_ , pixel_values=snake_case_ , training=snake_case_ )
# verify the logits
lowercase =(1, 1_99, 7_68)
self.assertEqual(outputs.last_hidden_state.shape , snake_case_ )
lowercase =tf.constant(
[[-0.05_29, 0.36_18, 0.16_32], [-0.15_87, -0.16_67, -0.04_00], [-0.15_57, -0.16_71, -0.05_05]] )
self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , snake_case_ , atol=1E-4 ) )
| 72
|
"""simple docstring"""
import multiprocessing
from typing import TYPE_CHECKING, Optional, Union
from .. import Dataset, Features, config
from ..formatting import query_table
from ..packaged_modules.sql.sql import Sql
from ..utils import logging
from .abc import AbstractDatasetInputStream
if TYPE_CHECKING:
import sqlitea
import sqlalchemy
class lowerCamelCase__ ( A ):
"""simple docstring"""
def __init__( self : Optional[Any] , UpperCamelCase : Union[str, "sqlalchemy.sql.Selectable"] , UpperCamelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , UpperCamelCase : Optional[Features] = None , UpperCamelCase : str = None , UpperCamelCase : bool = False , **UpperCamelCase : List[Any] , ):
'''simple docstring'''
super().__init__(features=UpperCamelCase , cache_dir=UpperCamelCase , keep_in_memory=UpperCamelCase , **UpperCamelCase )
__UpperCAmelCase : Dict = Sql(
cache_dir=UpperCamelCase , features=UpperCamelCase , sql=UpperCamelCase , con=UpperCamelCase , **UpperCamelCase , )
def lowerCamelCase__ ( self : Dict ):
'''simple docstring'''
__UpperCAmelCase : Tuple = None
__UpperCAmelCase : Tuple = None
__UpperCAmelCase : str = None
__UpperCAmelCase : Dict = None
self.builder.download_and_prepare(
download_config=UpperCamelCase , download_mode=UpperCamelCase , verification_mode=UpperCamelCase , base_path=UpperCamelCase , )
# Build dataset for splits
__UpperCAmelCase : Optional[int] = self.builder.as_dataset(
split="""train""" , verification_mode=UpperCamelCase , in_memory=self.keep_in_memory )
return dataset
class lowerCamelCase__ :
"""simple docstring"""
def __init__( self : List[Any] , UpperCamelCase : Dataset , UpperCamelCase : str , UpperCamelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , UpperCamelCase : Optional[int] = None , UpperCamelCase : Optional[int] = None , **UpperCamelCase : Tuple , ):
'''simple docstring'''
if num_proc is not None and num_proc <= 0:
raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' )
__UpperCAmelCase : Tuple = dataset
__UpperCAmelCase : int = name
__UpperCAmelCase : Union[str, Any] = con
__UpperCAmelCase : Optional[int] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
__UpperCAmelCase : Optional[int] = num_proc
__UpperCAmelCase : Any = to_sql_kwargs
def lowerCamelCase__ ( self : Union[str, Any] ):
'''simple docstring'''
__UpperCAmelCase : Dict = self.to_sql_kwargs.pop("""sql""" , UpperCamelCase )
__UpperCAmelCase : Dict = self.to_sql_kwargs.pop("""con""" , UpperCamelCase )
__UpperCAmelCase : Any = self.to_sql_kwargs.pop("""index""" , UpperCamelCase )
__UpperCAmelCase : Dict = self._write(index=UpperCamelCase , **self.to_sql_kwargs )
return written
def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase : str ):
'''simple docstring'''
__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase : Any = args
__UpperCAmelCase : Optional[int] = {**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs
__UpperCAmelCase : Optional[int] = query_table(
table=self.dataset.data , key=slice(UpperCamelCase , offset + self.batch_size ) , indices=self.dataset._indices , )
__UpperCAmelCase : Optional[int] = batch.to_pandas()
__UpperCAmelCase : Union[str, Any] = df.to_sql(self.name , self.con , index=UpperCamelCase , **UpperCamelCase )
return num_rows or len(UpperCamelCase )
def lowerCamelCase__ ( self : Tuple , UpperCamelCase : Optional[int] , **UpperCamelCase : str ):
'''simple docstring'''
__UpperCAmelCase : List[Any] = 0
if self.num_proc is None or self.num_proc == 1:
for offset in logging.tqdm(
range(0 , len(self.dataset ) , self.batch_size ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ):
written += self._batch_sql((offset, index, to_sql_kwargs) )
else:
__UpperCAmelCase ,__UpperCAmelCase : Tuple = len(self.dataset ), self.batch_size
with multiprocessing.Pool(self.num_proc ) as pool:
for num_rows in logging.tqdm(
pool.imap(
self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , UpperCamelCase , UpperCamelCase )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ):
written += num_rows
return written
| 139
| 0
|
import os
from datetime import datetime as dt
from github import Github
__UpperCamelCase : List[Any] = [
"good first issue",
"feature request",
"wip",
]
def _a ( ):
"""simple docstring"""
UpperCamelCase__ : Union[str, Any] = Github(os.environ['''GITHUB_TOKEN'''] )
UpperCamelCase__ : List[Any] = g.get_repo('''huggingface/accelerate''' )
UpperCamelCase__ : Tuple = repo.get_issues(state='''open''' )
for issue in open_issues:
UpperCamelCase__ : str = sorted([comment for comment in issue.get_comments()] , key=lambda SCREAMING_SNAKE_CASE : i.created_at , reverse=SCREAMING_SNAKE_CASE )
UpperCamelCase__ : str = comments[0] if len(SCREAMING_SNAKE_CASE ) > 0 else None
UpperCamelCase__ : Optional[int] = dt.utcnow()
UpperCamelCase__ : Optional[Any] = (current_time - issue.updated_at).days
UpperCamelCase__ : List[Any] = (current_time - issue.created_at).days
if (
last_comment is not None
and last_comment.user.login == "github-actions[bot]"
and days_since_updated > 7
and days_since_creation >= 30
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# Close issue since it has been 7 days of inactivity since bot mention.
issue.edit(state='''closed''' )
elif (
days_since_updated > 23
and days_since_creation >= 30
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# Add stale comment
issue.create_comment(
'''This issue has been automatically marked as stale because it has not had '''
'''recent activity. If you think this still needs to be addressed '''
'''please comment on this thread.\n\nPlease note that issues that do not follow the '''
'''[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) '''
'''are likely to be ignored.''' )
if __name__ == "__main__":
main()
| 106
|
from argparse import ArgumentParser, Namespace
from ..utils import logging
from . import BaseTransformersCLICommand
def _a ( SCREAMING_SNAKE_CASE : Namespace ):
"""simple docstring"""
return ConvertCommand(
args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name )
__UpperCamelCase : List[Any] = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n"
class __magic_name__ ( __lowerCAmelCase):
@staticmethod
def UpperCAmelCase__ ( lowerCamelCase__ : ArgumentParser ) -> Optional[int]:
'''simple docstring'''
UpperCamelCase__ : int = parser.add_parser(
'''convert''' , help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.''' , )
train_parser.add_argument('''--model_type''' , type=lowerCamelCase__ , required=lowerCamelCase__ , help='''Model\'s type.''' )
train_parser.add_argument(
'''--tf_checkpoint''' , type=lowerCamelCase__ , required=lowerCamelCase__ , help='''TensorFlow checkpoint path or folder.''' )
train_parser.add_argument(
'''--pytorch_dump_output''' , type=lowerCamelCase__ , required=lowerCamelCase__ , help='''Path to the PyTorch saved model output.''' )
train_parser.add_argument('''--config''' , type=lowerCamelCase__ , default='''''' , help='''Configuration file path or folder.''' )
train_parser.add_argument(
'''--finetuning_task_name''' , type=lowerCamelCase__ , default=lowerCamelCase__ , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , )
train_parser.set_defaults(func=lowerCamelCase__ )
def __init__( self : Optional[Any] , lowerCamelCase__ : str , lowerCamelCase__ : str , lowerCamelCase__ : str , lowerCamelCase__ : str , lowerCamelCase__ : str , *lowerCamelCase__ : Optional[int] , ) -> List[Any]:
'''simple docstring'''
UpperCamelCase__ : List[Any] = logging.get_logger('''transformers-cli/converting''' )
self._logger.info(F"Loading model {model_type}" )
UpperCamelCase__ : List[str] = model_type
UpperCamelCase__ : Optional[int] = tf_checkpoint
UpperCamelCase__ : List[Any] = pytorch_dump_output
UpperCamelCase__ : List[Any] = config
UpperCamelCase__ : Any = finetuning_task_name
def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]:
'''simple docstring'''
if self._model_type == "albert":
try:
from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import (
convert_tf_checkpoint_to_pytorch,
)
except ImportError:
raise ImportError(lowerCamelCase__ )
convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output )
elif self._model_type == "bert":
try:
from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import (
convert_tf_checkpoint_to_pytorch,
)
except ImportError:
raise ImportError(lowerCamelCase__ )
convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output )
elif self._model_type == "funnel":
try:
from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import (
convert_tf_checkpoint_to_pytorch,
)
except ImportError:
raise ImportError(lowerCamelCase__ )
convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output )
elif self._model_type == "t5":
try:
from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
except ImportError:
raise ImportError(lowerCamelCase__ )
convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output )
elif self._model_type == "gpt":
from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import (
convert_openai_checkpoint_to_pytorch,
)
convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output )
elif self._model_type == "transfo_xl":
try:
from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import (
convert_transfo_xl_checkpoint_to_pytorch,
)
except ImportError:
raise ImportError(lowerCamelCase__ )
if "ckpt" in self._tf_checkpoint.lower():
UpperCamelCase__ : str = self._tf_checkpoint
UpperCamelCase__ : List[Any] = ''''''
else:
UpperCamelCase__ : Any = self._tf_checkpoint
UpperCamelCase__ : List[Any] = ''''''
convert_transfo_xl_checkpoint_to_pytorch(
lowerCamelCase__ , self._config , self._pytorch_dump_output , lowerCamelCase__ )
elif self._model_type == "gpt2":
try:
from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import (
convert_gpta_checkpoint_to_pytorch,
)
except ImportError:
raise ImportError(lowerCamelCase__ )
convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output )
elif self._model_type == "xlnet":
try:
from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import (
convert_xlnet_checkpoint_to_pytorch,
)
except ImportError:
raise ImportError(lowerCamelCase__ )
convert_xlnet_checkpoint_to_pytorch(
self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name )
elif self._model_type == "xlm":
from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import (
convert_xlm_checkpoint_to_pytorch,
)
convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output )
elif self._model_type == "lxmert":
from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import (
convert_lxmert_checkpoint_to_pytorch,
)
convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output )
elif self._model_type == "rembert":
from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import (
convert_rembert_tf_checkpoint_to_pytorch,
)
convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output )
else:
raise ValueError(
'''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )
| 106
| 1
|
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 lowercase :
'''simple docstring'''
def __init__( self , _snake_case , _snake_case=13 , _snake_case=30 , _snake_case=2 , _snake_case=3 , _snake_case=True , _snake_case=True , _snake_case=32 , _snake_case=5 , _snake_case=4 , _snake_case=37 , _snake_case="gelu" , _snake_case=0.1 , _snake_case=0.1 , _snake_case=10 , _snake_case=0.02 , _snake_case=None , ) -> Dict:
"""simple docstring"""
UpperCAmelCase = parent
UpperCAmelCase = batch_size
UpperCAmelCase = image_size
UpperCAmelCase = patch_size
UpperCAmelCase = num_channels
UpperCAmelCase = is_training
UpperCAmelCase = use_labels
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 = type_sequence_label_size
UpperCAmelCase = initializer_range
UpperCAmelCase = scope
# in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
UpperCAmelCase = (image_size // patch_size) ** 2
UpperCAmelCase = num_patches + 1
def snake_case_ ( self ) -> List[Any]:
"""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.type_sequence_label_size )
UpperCAmelCase = self.get_config()
return config, pixel_values, labels
def snake_case_ ( self ) -> Tuple:
"""simple docstring"""
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 snake_case_ ( self , _snake_case , _snake_case , _snake_case ) -> Union[str, Any]:
"""simple docstring"""
UpperCAmelCase = ViTMSNModel(config=_snake_case )
model.to(_snake_case )
model.eval()
UpperCAmelCase = model(_snake_case )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def snake_case_ ( self , _snake_case , _snake_case , _snake_case ) -> Union[str, Any]:
"""simple docstring"""
UpperCAmelCase = self.type_sequence_label_size
UpperCAmelCase = ViTMSNForImageClassification(_snake_case )
model.to(_snake_case )
model.eval()
UpperCAmelCase = model(_snake_case , labels=_snake_case )
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
UpperCAmelCase = 1
UpperCAmelCase = ViTMSNForImageClassification(_snake_case )
model.to(_snake_case )
model.eval()
UpperCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
UpperCAmelCase = model(_snake_case )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def snake_case_ ( self ) -> Tuple:
"""simple docstring"""
UpperCAmelCase = self.prepare_config_and_inputs()
UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = config_and_inputs
UpperCAmelCase = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class lowercase ( A__ , A__ , unittest.TestCase ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
__SCREAMING_SNAKE_CASE = (
{"""feature-extraction""": ViTMSNModel, """image-classification""": ViTMSNForImageClassification}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
def snake_case_ ( self ) -> int:
"""simple docstring"""
UpperCAmelCase = ViTMSNModelTester(self )
UpperCAmelCase = ConfigTester(self , config_class=_snake_case , has_text_modality=_snake_case , hidden_size=37 )
def snake_case_ ( self ) -> Union[str, Any]:
"""simple docstring"""
self.config_tester.run_common_tests()
@unittest.skip(reason='''ViTMSN does not use inputs_embeds''' )
def snake_case_ ( self ) -> Tuple:
"""simple docstring"""
pass
def snake_case_ ( self ) -> str:
"""simple docstring"""
UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase = model_class(_snake_case )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
UpperCAmelCase = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(_snake_case , nn.Linear ) )
def snake_case_ ( self ) -> Dict:
"""simple docstring"""
UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase = model_class(_snake_case )
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] , _snake_case )
def snake_case_ ( self ) -> Optional[int]:
"""simple docstring"""
UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_snake_case )
def snake_case_ ( self ) -> Dict:
"""simple docstring"""
UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_snake_case )
@slow
def snake_case_ ( self ) -> Dict:
"""simple docstring"""
for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCAmelCase = ViTMSNModel.from_pretrained(_snake_case )
self.assertIsNotNone(_snake_case )
def _lowerCAmelCase ( ):
'''simple docstring'''
UpperCAmelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_torch
@require_vision
class lowercase ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def snake_case_ ( self ) -> int:
"""simple docstring"""
return ViTImageProcessor.from_pretrained('''facebook/vit-msn-small''' ) if is_vision_available() else None
@slow
def snake_case_ ( self ) -> Dict:
"""simple docstring"""
torch.manual_seed(2 )
UpperCAmelCase = ViTMSNForImageClassification.from_pretrained('''facebook/vit-msn-small''' ).to(_snake_case )
UpperCAmelCase = self.default_image_processor
UpperCAmelCase = prepare_img()
UpperCAmelCase = image_processor(images=_snake_case , return_tensors='''pt''' ).to(_snake_case )
# forward pass
with torch.no_grad():
UpperCAmelCase = model(**_snake_case )
# verify the logits
UpperCAmelCase = torch.Size((1, 1000) )
self.assertEqual(outputs.logits.shape , _snake_case )
UpperCAmelCase = torch.tensor([-0.0803, -0.4454, -0.2375] ).to(_snake_case )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , _snake_case , atol=1e-4 ) )
| 254
|
from __future__ import annotations
__magic_name__ = list[list[int]]
# assigning initial values to the grid
__magic_name__ = [
[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0],
]
# a grid with no solution
__magic_name__ = [
[5, 0, 6, 5, 0, 8, 4, 0, 3],
[5, 2, 0, 0, 0, 0, 0, 0, 2],
[1, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0],
]
def _lowerCAmelCase ( A__: Matrix , A__: int , A__: int , A__: int ):
'''simple docstring'''
for i in range(9 ):
if grid[row][i] == n or grid[i][column] == n:
return False
for i in range(3 ):
for j in range(3 ):
if grid[(row - row % 3) + i][(column - column % 3) + j] == n:
return False
return True
def _lowerCAmelCase ( A__: Matrix ):
'''simple docstring'''
for i in range(9 ):
for j in range(9 ):
if grid[i][j] == 0:
return i, j
return None
def _lowerCAmelCase ( A__: Matrix ):
'''simple docstring'''
if location := find_empty_location(A__ ):
UpperCAmelCase , UpperCAmelCase = location
else:
# If the location is ``None``, then the grid is solved.
return grid
for digit in range(1 , 10 ):
if is_safe(A__ , A__ , A__ , A__ ):
UpperCAmelCase = digit
if sudoku(A__ ) is not None:
return grid
UpperCAmelCase = 0
return None
def _lowerCAmelCase ( A__: Matrix ):
'''simple docstring'''
for row in grid:
for cell in row:
print(A__ , end=''' ''' )
print()
if __name__ == "__main__":
# make a copy of grid so that you can compare with the unmodified grid
for example_grid in (initial_grid, no_solution):
print("\nExample grid:\n" + "=" * 20)
print_solution(example_grid)
print("\nExample grid solution:")
__magic_name__ = sudoku(example_grid)
if solution is not None:
print_solution(solution)
else:
print("Cannot find a solution.")
| 254
| 1
|
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.:
# python ./utils/get_modified_files.py utils src tests examples
#
# it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered
# since the output of this script is fed into Makefile commands it doesn't print a newline after the results
import re
import subprocess
import sys
_snake_case = subprocess.check_output('''git merge-base main HEAD'''.split()).decode('''utf-8''')
_snake_case = subprocess.check_output(F"git diff --name-only {fork_point_sha}".split()).decode('''utf-8''').split()
_snake_case = '''|'''.join(sys.argv[1:])
_snake_case = re.compile(rF"^({joined_dirs}).*?\.py$")
_snake_case = [x for x in modified_files if regex.match(x)]
print(''' '''.join(relevant_modified_files), end='''''')
| 715
|
import cva
import numpy as np
class _lowerCAmelCase :
"""simple docstring"""
def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : int ):
"""simple docstring"""
if k in (0.04, 0.06):
UpperCamelCase = k
UpperCamelCase = window_size
else:
raise ValueError('invalid k value' )
def __str__( self : Any ):
"""simple docstring"""
return str(self.k )
def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ):
"""simple docstring"""
UpperCamelCase = cva.imread(SCREAMING_SNAKE_CASE__ , 0 )
UpperCamelCase , UpperCamelCase = img.shape
UpperCamelCase = []
UpperCamelCase = img.copy()
UpperCamelCase = cva.cvtColor(SCREAMING_SNAKE_CASE__ , cva.COLOR_GRAY2RGB )
UpperCamelCase , UpperCamelCase = np.gradient(SCREAMING_SNAKE_CASE__ )
UpperCamelCase = dx**2
UpperCamelCase = dy**2
UpperCamelCase = dx * dy
UpperCamelCase = 0.04
UpperCamelCase = self.window_size // 2
for y in range(SCREAMING_SNAKE_CASE__ , h - offset ):
for x in range(SCREAMING_SNAKE_CASE__ , w - offset ):
UpperCamelCase = ixx[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
UpperCamelCase = iyy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
UpperCamelCase = ixy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
UpperCamelCase = (wxx * wyy) - (wxy**2)
UpperCamelCase = wxx + wyy
UpperCamelCase = det - k * (trace**2)
# Can change the value
if r > 0.5:
corner_list.append([x, y, r] )
color_img.itemset((y, x, 0) , 0 )
color_img.itemset((y, x, 1) , 0 )
color_img.itemset((y, x, 2) , 2_55 )
return color_img, corner_list
if __name__ == "__main__":
_snake_case = HarrisCorner(0.04, 3)
_snake_case , _snake_case = edge_detect.detect('''path_to_image''')
cva.imwrite('''detect.png''', color_img)
| 170
| 0
|
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 : Tuple ) -> Optional[int]:
"""simple docstring"""
lowercase__ = tempfile.mkdtemp()
# fmt: off
lowercase__ = ["""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
lowercase__ = dict(zip(_UpperCAmelCase , range(len(_UpperCAmelCase ) ) ) )
lowercase__ = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""]
lowercase__ = {"""unk_token""": """<unk>"""}
lowercase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] )
lowercase__ = 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(_UpperCAmelCase ) + """\n""" )
with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp:
fp.write("""\n""".join(_UpperCAmelCase ) )
lowercase__ = {
"""do_resize""": True,
"""size""": 20,
"""do_center_crop""": True,
"""crop_size""": 18,
"""do_normalize""": True,
"""image_mean""": [0.48_145_466, 0.4_578_275, 0.40_821_073],
"""image_std""": [0.26_862_954, 0.26_130_258, 0.27_577_711],
}
lowercase__ = os.path.join(self.tmpdirname , _UpperCAmelCase )
with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
def lowerCamelCase__ (self : Union[str, Any] , **_UpperCAmelCase : Optional[int] ) -> int:
"""simple docstring"""
return CLIPTokenizer.from_pretrained(self.tmpdirname , **_UpperCAmelCase )
def lowerCamelCase__ (self : List[Any] , **_UpperCAmelCase : str ) -> Any:
"""simple docstring"""
return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **_UpperCAmelCase )
def lowerCamelCase__ (self : Union[str, Any] , **_UpperCAmelCase : str ) -> Union[str, Any]:
"""simple docstring"""
return CLIPImageProcessor.from_pretrained(self.tmpdirname , **_UpperCAmelCase )
def lowerCamelCase__ (self : Dict ) -> Union[str, Any]:
"""simple docstring"""
shutil.rmtree(self.tmpdirname )
def lowerCamelCase__ (self : int ) -> Optional[int]:
"""simple docstring"""
lowercase__ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
lowercase__ = [Image.fromarray(np.moveaxis(_UpperCAmelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def lowerCamelCase__ (self : List[str] ) -> Optional[Any]:
"""simple docstring"""
lowercase__ = self.get_tokenizer()
lowercase__ = self.get_rust_tokenizer()
lowercase__ = self.get_image_processor()
lowercase__ = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
processor_slow.save_pretrained(self.tmpdirname )
lowercase__ = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=_UpperCAmelCase )
lowercase__ = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
processor_fast.save_pretrained(self.tmpdirname )
lowercase__ = 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 , _UpperCAmelCase )
self.assertIsInstance(processor_fast.tokenizer , _UpperCAmelCase )
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 , _UpperCAmelCase )
self.assertIsInstance(processor_fast.image_processor , _UpperCAmelCase )
def lowerCamelCase__ (self : Tuple ) -> List[str]:
"""simple docstring"""
lowercase__ = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
lowercase__ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" )
lowercase__ = self.get_image_processor(do_normalize=_UpperCAmelCase , padding_value=1.0 )
lowercase__ = CLIPProcessor.from_pretrained(
self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=_UpperCAmelCase , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , _UpperCAmelCase )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _UpperCAmelCase )
def lowerCamelCase__ (self : str ) -> Tuple:
"""simple docstring"""
lowercase__ = self.get_image_processor()
lowercase__ = self.get_tokenizer()
lowercase__ = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
lowercase__ = self.prepare_image_inputs()
lowercase__ = image_processor(_UpperCAmelCase , return_tensors="""np""" )
lowercase__ = processor(images=_UpperCAmelCase , 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 : Tuple ) -> str:
"""simple docstring"""
lowercase__ = self.get_image_processor()
lowercase__ = self.get_tokenizer()
lowercase__ = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
lowercase__ = """lower newer"""
lowercase__ = processor(text=_UpperCAmelCase )
lowercase__ = tokenizer(_UpperCAmelCase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def lowerCamelCase__ (self : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
lowercase__ = self.get_image_processor()
lowercase__ = self.get_tokenizer()
lowercase__ = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
lowercase__ = """lower newer"""
lowercase__ = self.prepare_image_inputs()
lowercase__ = processor(text=_UpperCAmelCase , images=_UpperCAmelCase )
self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] )
# test if it raises when no input is passed
with pytest.raises(_UpperCAmelCase ):
processor()
def lowerCamelCase__ (self : int ) -> Dict:
"""simple docstring"""
lowercase__ = self.get_image_processor()
lowercase__ = self.get_tokenizer()
lowercase__ = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
lowercase__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
lowercase__ = processor.batch_decode(_UpperCAmelCase )
lowercase__ = tokenizer.batch_decode(_UpperCAmelCase )
self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase )
def lowerCamelCase__ (self : List[Any] ) -> Optional[int]:
"""simple docstring"""
lowercase__ = self.get_image_processor()
lowercase__ = self.get_tokenizer()
lowercase__ = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
lowercase__ = """lower newer"""
lowercase__ = self.prepare_image_inputs()
lowercase__ = processor(text=_UpperCAmelCase , images=_UpperCAmelCase )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 15
|
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import AutoTokenizer, BarkProcessor
from transformers.testing_utils import require_torch, slow
@require_torch
class A ( unittest.TestCase ):
'''simple docstring'''
def lowerCamelCase__ (self : List[Any] ) -> List[str]:
"""simple docstring"""
lowercase__ = """ylacombe/bark-small"""
lowercase__ = tempfile.mkdtemp()
lowercase__ = """en_speaker_1"""
lowercase__ = """This is a test string"""
lowercase__ = """speaker_embeddings_path.json"""
lowercase__ = """speaker_embeddings"""
def lowerCamelCase__ (self : str , **_UpperCAmelCase : Optional[int] ) -> str:
"""simple docstring"""
return AutoTokenizer.from_pretrained(self.checkpoint , **_UpperCAmelCase )
def lowerCamelCase__ (self : str ) -> List[str]:
"""simple docstring"""
shutil.rmtree(self.tmpdirname )
def lowerCamelCase__ (self : Optional[int] ) -> List[str]:
"""simple docstring"""
lowercase__ = self.get_tokenizer()
lowercase__ = BarkProcessor(tokenizer=_UpperCAmelCase )
processor.save_pretrained(self.tmpdirname )
lowercase__ = BarkProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
@slow
def lowerCamelCase__ (self : str ) -> Tuple:
"""simple docstring"""
lowercase__ = BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
processor.save_pretrained(
self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , )
lowercase__ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" )
lowercase__ = BarkProcessor.from_pretrained(
self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
def lowerCamelCase__ (self : List[str] ) -> List[Any]:
"""simple docstring"""
lowercase__ = BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
lowercase__ = 35
lowercase__ = 2
lowercase__ = 8
lowercase__ = {
"""semantic_prompt""": np.ones(_UpperCAmelCase ),
"""coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ),
"""fine_prompt""": np.ones((nb_codebooks_total, seq_len) ),
}
# test providing already loaded voice_preset
lowercase__ = processor(text=self.input_string , voice_preset=_UpperCAmelCase )
lowercase__ = inputs["""history_prompt"""]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_UpperCAmelCase , np.array([] ) ).tolist() )
# test loading voice preset from npz file
lowercase__ = os.path.join(self.tmpdirname , """file.npz""" )
np.savez(_UpperCAmelCase , **_UpperCAmelCase )
lowercase__ = processor(text=self.input_string , voice_preset=_UpperCAmelCase )
lowercase__ = inputs["""history_prompt"""]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_UpperCAmelCase , np.array([] ) ).tolist() )
# test loading voice preset from the hub
lowercase__ = processor(text=self.input_string , voice_preset=self.voice_preset )
def lowerCamelCase__ (self : int ) -> Tuple:
"""simple docstring"""
lowercase__ = self.get_tokenizer()
lowercase__ = BarkProcessor(tokenizer=_UpperCAmelCase )
lowercase__ = processor(text=self.input_string )
lowercase__ = tokenizer(
self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=_UpperCAmelCase , return_attention_mask=_UpperCAmelCase , return_token_type_ids=_UpperCAmelCase , )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
| 15
| 1
|
def lowerCamelCase__ ( _A = 50000000 ):
'''simple docstring'''
snake_case_ = set()
snake_case_ = int((limit - 24) ** (1 / 2) )
snake_case_ = set(range(3 , prime_square_limit + 1 , 2 ) )
primes.add(2 )
for p in range(3 , prime_square_limit + 1 , 2 ):
if p not in primes:
continue
primes.difference_update(set(range(p * p , prime_square_limit + 1 , _A ) ) )
for primea in primes:
snake_case_ = primea * primea
for primea in primes:
snake_case_ = primea * primea * primea
if square + cube >= limit - 16:
break
for primea in primes:
snake_case_ = primea * primea * primea * primea
snake_case_ = square + cube + tetr
if total >= limit:
break
ret.add(_A )
return len(_A )
if __name__ == "__main__":
print(f'''{solution() = }''')
| 139
|
from __future__ import annotations
def lowerCamelCase__ ( _A ):
'''simple docstring'''
snake_case_ = str(_A )
return n == n[::-1]
def lowerCamelCase__ ( _A = 1000000 ):
'''simple docstring'''
snake_case_ = 0
for i in range(1 , _A ):
if is_palindrome(_A ) and is_palindrome(bin(_A ).split("b" )[1] ):
total += i
return total
if __name__ == "__main__":
print(solution(int(str(input().strip()))))
| 139
| 1
|
'''simple docstring'''
def UpperCamelCase_ ( snake_case_ : list , snake_case_ : list , snake_case_ : int ) -> list:
'''simple docstring'''
__lowerCAmelCase = len(snake_case_ )
__lowerCAmelCase = [[0] * n for i in range(snake_case_ )]
for i in range(snake_case_ ):
__lowerCAmelCase = y_points[i]
for i in range(2 , snake_case_ ):
for j in range(snake_case_ , snake_case_ ):
__lowerCAmelCase = (
(xa - x_points[j - i + 1]) * q[j][i - 1]
- (xa - x_points[j]) * q[j - 1][i - 1]
) / (x_points[j] - x_points[j - i + 1])
return [q[n - 1][n - 1], q]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 427
|
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_A : Optional[int] = {
'''configuration_luke''': ['''LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LukeConfig'''],
'''tokenization_luke''': ['''LukeTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_A : Optional[Any] = [
'''LUKE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''LukeForEntityClassification''',
'''LukeForEntityPairClassification''',
'''LukeForEntitySpanClassification''',
'''LukeForMultipleChoice''',
'''LukeForQuestionAnswering''',
'''LukeForSequenceClassification''',
'''LukeForTokenClassification''',
'''LukeForMaskedLM''',
'''LukeModel''',
'''LukePreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig
from .tokenization_luke import LukeTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_luke import (
LUKE_PRETRAINED_MODEL_ARCHIVE_LIST,
LukeForEntityClassification,
LukeForEntityPairClassification,
LukeForEntitySpanClassification,
LukeForMaskedLM,
LukeForMultipleChoice,
LukeForQuestionAnswering,
LukeForSequenceClassification,
LukeForTokenClassification,
LukeModel,
LukePreTrainedModel,
)
else:
import sys
_A : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 427
| 1
|
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_torch_available,
)
_UpperCAmelCase : Union[str, Any] = {
"configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCAmelCase : Tuple = [
"RESNET_PRETRAINED_MODEL_ARCHIVE_LIST",
"ResNetForImageClassification",
"ResNetModel",
"ResNetPreTrainedModel",
"ResNetBackbone",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCAmelCase : Union[str, Any] = [
"TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFResNetForImageClassification",
"TFResNetModel",
"TFResNetPreTrainedModel",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCAmelCase : Union[str, Any] = [
"FlaxResNetForImageClassification",
"FlaxResNetModel",
"FlaxResNetPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_resnet import (
RESNET_PRETRAINED_MODEL_ARCHIVE_LIST,
ResNetBackbone,
ResNetForImageClassification,
ResNetModel,
ResNetPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_resnet import (
TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST,
TFResNetForImageClassification,
TFResNetModel,
TFResNetPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel
else:
import sys
_UpperCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure)
| 288
|
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available
_UpperCAmelCase : Optional[Any] = {
"configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCAmelCase : Any = [
"ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST",
"ErnieForCausalLM",
"ErnieForMaskedLM",
"ErnieForMultipleChoice",
"ErnieForNextSentencePrediction",
"ErnieForPreTraining",
"ErnieForQuestionAnswering",
"ErnieForSequenceClassification",
"ErnieForTokenClassification",
"ErnieModel",
"ErniePreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_ernie import (
ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,
ErnieForCausalLM,
ErnieForMaskedLM,
ErnieForMultipleChoice,
ErnieForNextSentencePrediction,
ErnieForPreTraining,
ErnieForQuestionAnswering,
ErnieForSequenceClassification,
ErnieForTokenClassification,
ErnieModel,
ErniePreTrainedModel,
)
else:
import sys
_UpperCAmelCase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 288
| 1
|
import numpy as np
def UpperCAmelCase__( __UpperCAmelCase : np.ndarray , __UpperCAmelCase : float ):
return np.where(vector > 0 , __UpperCAmelCase , (alpha * (np.exp(__UpperCAmelCase ) - 1)) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 576
|
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class __SCREAMING_SNAKE_CASE :
"""simple docstring"""
__UpperCAmelCase = 42
__UpperCAmelCase = None
__UpperCAmelCase = None
def UpperCAmelCase__( __UpperCAmelCase : TreeNode | None ):
# Validation
def is_valid_tree(__UpperCAmelCase : TreeNode | None ) -> bool:
if node is None:
return True
if not isinstance(__UpperCAmelCase , __UpperCAmelCase ):
return False
try:
float(node.data )
except (TypeError, ValueError):
return False
return is_valid_tree(node.left ) and is_valid_tree(node.right )
if not is_valid_tree(__UpperCAmelCase ):
raise ValueError(
'Each node should be type of TreeNode and data should be float.' )
def is_binary_search_tree_recursive_check(
__UpperCAmelCase : TreeNode | None , __UpperCAmelCase : float , __UpperCAmelCase : float ) -> bool:
if node is None:
return True
return (
left_bound < node.data < right_bound
and is_binary_search_tree_recursive_check(node.left , __UpperCAmelCase , node.data )
and is_binary_search_tree_recursive_check(
node.right , node.data , __UpperCAmelCase )
)
return is_binary_search_tree_recursive_check(__UpperCAmelCase , -float('inf' ) , float('inf' ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 576
| 1
|
from typing import Optional, Union
import torch
from torch import nn
from ...configuration_utils import ConfigMixin, register_to_config
from ...models.modeling_utils import ModelMixin
class A ( _UpperCAmelCase , _UpperCAmelCase ):
"""simple docstring"""
@register_to_config
def __init__( self : Optional[int],lowercase_ : int = 7_6_8,)-> str:
'''simple docstring'''
super().__init__()
A__ = nn.Parameter(torch.zeros(1,lowercase_ ) )
A__ = nn.Parameter(torch.ones(1,lowercase_ ) )
def snake_case__ ( self : List[str],lowercase_ : Optional[Union[str, torch.device]] = None,lowercase_ : Optional[torch.dtype] = None,)-> Union[str, Any]:
'''simple docstring'''
A__ = nn.Parameter(self.mean.to(lowercase_ ).to(lowercase_ ) )
A__ = nn.Parameter(self.std.to(lowercase_ ).to(lowercase_ ) )
return self
def snake_case__ ( self : Optional[Any],lowercase_ : Tuple )-> Union[str, Any]:
'''simple docstring'''
A__ = (embeds - self.mean) * 1.0 / self.std
return embeds
def snake_case__ ( self : List[Any],lowercase_ : Any )-> Optional[Any]:
'''simple docstring'''
A__ = (embeds * self.std) + self.mean
return embeds
| 586
|
from typing import List, Optional, Union
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class A ( _UpperCAmelCase ):
"""simple docstring"""
lowerCamelCase = ['image_processor', 'tokenizer']
lowerCamelCase = 'BlipImageProcessor'
lowerCamelCase = 'AutoTokenizer'
def __init__( self : List[Any],lowercase_ : Dict,lowercase_ : str )-> Any:
'''simple docstring'''
A__ = False
super().__init__(lowercase_,lowercase_ )
A__ = self.image_processor
def __call__( self : Union[str, Any],lowercase_ : ImageInput = None,lowercase_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,lowercase_ : bool = True,lowercase_ : Union[bool, str, PaddingStrategy] = False,lowercase_ : Union[bool, str, TruncationStrategy] = None,lowercase_ : Optional[int] = None,lowercase_ : int = 0,lowercase_ : Optional[int] = None,lowercase_ : Optional[bool] = None,lowercase_ : bool = False,lowercase_ : bool = False,lowercase_ : bool = False,lowercase_ : bool = False,lowercase_ : bool = False,lowercase_ : bool = True,lowercase_ : Optional[Union[str, TensorType]] = None,**lowercase_ : Dict,)-> BatchEncoding:
'''simple docstring'''
if images is None and text is None:
raise ValueError('You have to specify either images or text.' )
# Get only text
if images is None:
A__ = self.tokenizer
A__ = self.tokenizer(
text=lowercase_,add_special_tokens=lowercase_,padding=lowercase_,truncation=lowercase_,max_length=lowercase_,stride=lowercase_,pad_to_multiple_of=lowercase_,return_attention_mask=lowercase_,return_overflowing_tokens=lowercase_,return_special_tokens_mask=lowercase_,return_offsets_mapping=lowercase_,return_token_type_ids=lowercase_,return_length=lowercase_,verbose=lowercase_,return_tensors=lowercase_,**lowercase_,)
return text_encoding
# add pixel_values
A__ = self.image_processor(lowercase_,return_tensors=lowercase_ )
if text is not None:
A__ = self.tokenizer(
text=lowercase_,add_special_tokens=lowercase_,padding=lowercase_,truncation=lowercase_,max_length=lowercase_,stride=lowercase_,pad_to_multiple_of=lowercase_,return_attention_mask=lowercase_,return_overflowing_tokens=lowercase_,return_special_tokens_mask=lowercase_,return_offsets_mapping=lowercase_,return_token_type_ids=lowercase_,return_length=lowercase_,verbose=lowercase_,return_tensors=lowercase_,**lowercase_,)
else:
A__ = None
if text_encoding is not None:
encoding_image_processor.update(lowercase_ )
return encoding_image_processor
def snake_case__ ( self : int,*lowercase_ : Union[str, Any],**lowercase_ : Union[str, Any] )-> Dict:
'''simple docstring'''
return self.tokenizer.batch_decode(*lowercase_,**lowercase_ )
def snake_case__ ( self : Optional[Any],*lowercase_ : List[str],**lowercase_ : List[Any] )-> Union[str, Any]:
'''simple docstring'''
return self.tokenizer.decode(*lowercase_,**lowercase_ )
@property
# Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
def snake_case__ ( self : List[Any] )-> int:
'''simple docstring'''
A__ = self.tokenizer.model_input_names
A__ = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
| 586
| 1
|
import unittest
from transformers import MPNetConfig, is_torch_available
from transformers.testing_utils import 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 (
MPNetForMaskedLM,
MPNetForMultipleChoice,
MPNetForQuestionAnswering,
MPNetForSequenceClassification,
MPNetForTokenClassification,
MPNetModel,
)
class __UpperCAmelCase :
"""simple docstring"""
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=False , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=64 , 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 , ) -> Optional[int]:
"""simple docstring"""
UpperCamelCase = parent
UpperCamelCase = batch_size
UpperCamelCase = seq_length
UpperCamelCase = is_training
UpperCamelCase = use_input_mask
UpperCamelCase = use_token_type_ids
UpperCamelCase = use_labels
UpperCamelCase = vocab_size
UpperCamelCase = hidden_size
UpperCamelCase = num_hidden_layers
UpperCamelCase = num_attention_heads
UpperCamelCase = intermediate_size
UpperCamelCase = hidden_act
UpperCamelCase = hidden_dropout_prob
UpperCamelCase = attention_probs_dropout_prob
UpperCamelCase = max_position_embeddings
UpperCamelCase = type_vocab_size
UpperCamelCase = type_sequence_label_size
UpperCamelCase = initializer_range
UpperCamelCase = num_labels
UpperCamelCase = num_choices
UpperCamelCase = scope
def __lowerCAmelCase ( self ) -> Optional[Any]:
"""simple docstring"""
return MPNetConfig.from_pretrained("microsoft/mpnet-base" )
def __lowerCAmelCase ( self ) -> List[str]:
"""simple docstring"""
UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
UpperCamelCase = None
if self.use_input_mask:
UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] )
UpperCamelCase = None
UpperCamelCase = None
UpperCamelCase = None
if self.use_labels:
UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices )
UpperCamelCase = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def __lowerCAmelCase ( self ) -> Dict:
"""simple docstring"""
return MPNetConfig(
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 , initializer_range=self.initializer_range , )
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]:
"""simple docstring"""
UpperCamelCase = MPNetModel(config=SCREAMING_SNAKE_CASE )
model.to(SCREAMING_SNAKE_CASE )
model.eval()
UpperCamelCase = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
UpperCamelCase = model(SCREAMING_SNAKE_CASE )
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 __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]:
"""simple docstring"""
UpperCamelCase = MPNetForQuestionAnswering(config=SCREAMING_SNAKE_CASE )
model.to(SCREAMING_SNAKE_CASE )
model.eval()
UpperCamelCase = model(
SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , start_positions=SCREAMING_SNAKE_CASE , end_positions=SCREAMING_SNAKE_CASE , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Dict:
"""simple docstring"""
UpperCamelCase = self.num_labels
UpperCamelCase = MPNetForSequenceClassification(SCREAMING_SNAKE_CASE )
model.to(SCREAMING_SNAKE_CASE )
model.eval()
UpperCamelCase = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]:
"""simple docstring"""
UpperCamelCase = self.num_choices
UpperCamelCase = MPNetForMultipleChoice(config=SCREAMING_SNAKE_CASE )
model.to(SCREAMING_SNAKE_CASE )
model.eval()
UpperCamelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
UpperCamelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
UpperCamelCase = model(
SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]:
"""simple docstring"""
UpperCamelCase = self.num_labels
UpperCamelCase = MPNetForTokenClassification(config=SCREAMING_SNAKE_CASE )
model.to(SCREAMING_SNAKE_CASE )
model.eval()
UpperCamelCase = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def __lowerCAmelCase ( self ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase = self.prepare_config_and_inputs()
(UpperCamelCase) = config_and_inputs
UpperCamelCase = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class __UpperCAmelCase ( lowercase__ , lowercase__ , unittest.TestCase ):
"""simple docstring"""
lowercase = (
(
MPNetForMaskedLM,
MPNetForMultipleChoice,
MPNetForQuestionAnswering,
MPNetForSequenceClassification,
MPNetForTokenClassification,
MPNetModel,
)
if is_torch_available()
else ()
)
lowercase = (
{
"feature-extraction": MPNetModel,
"fill-mask": MPNetForMaskedLM,
"question-answering": MPNetForQuestionAnswering,
"text-classification": MPNetForSequenceClassification,
"token-classification": MPNetForTokenClassification,
"zero-shot": MPNetForSequenceClassification,
}
if is_torch_available()
else {}
)
lowercase = False
lowercase = True
def __lowerCAmelCase ( self ) -> List[str]:
"""simple docstring"""
UpperCamelCase = MPNetModelTester(self )
UpperCamelCase = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=37 )
def __lowerCAmelCase ( self ) -> Any:
"""simple docstring"""
self.config_tester.run_common_tests()
def __lowerCAmelCase ( self ) -> str:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_model(*SCREAMING_SNAKE_CASE )
def __lowerCAmelCase ( self ) -> List[Any]:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_sequence_classification(*SCREAMING_SNAKE_CASE )
def __lowerCAmelCase ( self ) -> Dict:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_multiple_choice(*SCREAMING_SNAKE_CASE )
def __lowerCAmelCase ( self ) -> List[str]:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_token_classification(*SCREAMING_SNAKE_CASE )
def __lowerCAmelCase ( self ) -> Tuple:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_question_answering(*SCREAMING_SNAKE_CASE )
@require_torch
class __UpperCAmelCase ( unittest.TestCase ):
"""simple docstring"""
@slow
def __lowerCAmelCase ( self ) -> int:
"""simple docstring"""
UpperCamelCase = MPNetModel.from_pretrained("microsoft/mpnet-base" )
UpperCamelCase = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] )
UpperCamelCase = model(SCREAMING_SNAKE_CASE )[0]
UpperCamelCase = torch.Size((1, 11, 768) )
self.assertEqual(output.shape , SCREAMING_SNAKE_CASE )
UpperCamelCase = torch.tensor(
[[[-0.0_550, 0.1_943, -0.0_740], [-0.0_562, 0.2_211, -0.0_579], [-0.0_437, 0.3_337, -0.0_641]]] )
# compare the actual values for a slice.
self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
| 606
|
'''simple docstring'''
from typing import List
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a : Tuple = logging.get_logger(__name__)
a : str = {
"snap-research/efficientformer-l1-300": (
"https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json"
),
}
class UpperCamelCase__ ( lowercase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Tuple = "efficientformer"
def __init__( self , snake_case = [3, 2, 6, 4] , snake_case = [4_8, 9_6, 2_2_4, 4_4_8] , snake_case = [True, True, True, True] , snake_case = 4_4_8 , snake_case = 3_2 , snake_case = 4 , snake_case = 7 , snake_case = 5 , snake_case = 8 , snake_case = 4 , snake_case = 0.0 , snake_case = 1_6 , snake_case = 3 , snake_case = 3 , snake_case = 3 , snake_case = 2 , snake_case = 1 , snake_case = 0.0 , snake_case = 1 , snake_case = True , snake_case = True , snake_case = 1e-5 , snake_case = "gelu" , snake_case = 0.02 , snake_case = 1e-12 , snake_case = 2_2_4 , snake_case = 1e-05 , **snake_case , ):
'''simple docstring'''
super().__init__(**snake_case )
UpperCAmelCase : Any = hidden_act
UpperCAmelCase : Optional[Any] = hidden_dropout_prob
UpperCAmelCase : List[Any] = hidden_sizes
UpperCAmelCase : str = num_hidden_layers
UpperCAmelCase : int = num_attention_heads
UpperCAmelCase : List[Any] = initializer_range
UpperCAmelCase : str = layer_norm_eps
UpperCAmelCase : int = patch_size
UpperCAmelCase : Optional[int] = num_channels
UpperCAmelCase : Any = depths
UpperCAmelCase : Dict = mlp_expansion_ratio
UpperCAmelCase : List[str] = downsamples
UpperCAmelCase : List[Any] = dim
UpperCAmelCase : Any = key_dim
UpperCAmelCase : List[str] = attention_ratio
UpperCAmelCase : Union[str, Any] = resolution
UpperCAmelCase : List[str] = pool_size
UpperCAmelCase : Dict = downsample_patch_size
UpperCAmelCase : Optional[int] = downsample_stride
UpperCAmelCase : Any = downsample_pad
UpperCAmelCase : int = drop_path_rate
UpperCAmelCase : Optional[Any] = num_metaad_blocks
UpperCAmelCase : List[str] = distillation
UpperCAmelCase : int = use_layer_scale
UpperCAmelCase : List[str] = layer_scale_init_value
UpperCAmelCase : Union[str, Any] = image_size
UpperCAmelCase : Any = batch_norm_eps
| 679
| 0
|
import collections
from typing import List, Optional, Union
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
from ..bert.tokenization_bert_fast import BertTokenizerFast
from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer
_UpperCAmelCase = logging.get_logger(__name__)
_UpperCAmelCase = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
_UpperCAmelCase = {
"vocab_file": {
"facebook/dpr-ctx_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt"
),
"facebook/dpr-ctx_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"facebook/dpr-ctx_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json"
),
"facebook/dpr-ctx_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json"
),
},
}
_UpperCAmelCase = {
"vocab_file": {
"facebook/dpr-question_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt"
),
"facebook/dpr-question_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"facebook/dpr-question_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json"
),
"facebook/dpr-question_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json"
),
},
}
_UpperCAmelCase = {
"vocab_file": {
"facebook/dpr-reader-single-nq-base": (
"https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt"
),
"facebook/dpr-reader-multiset-base": (
"https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"facebook/dpr-reader-single-nq-base": (
"https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json"
),
"facebook/dpr-reader-multiset-base": (
"https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json"
),
},
}
_UpperCAmelCase = {
"facebook/dpr-ctx_encoder-single-nq-base": 512,
"facebook/dpr-ctx_encoder-multiset-base": 512,
}
_UpperCAmelCase = {
"facebook/dpr-question_encoder-single-nq-base": 512,
"facebook/dpr-question_encoder-multiset-base": 512,
}
_UpperCAmelCase = {
"facebook/dpr-reader-single-nq-base": 512,
"facebook/dpr-reader-multiset-base": 512,
}
_UpperCAmelCase = {
"facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True},
"facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True},
}
_UpperCAmelCase = {
"facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True},
"facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True},
}
_UpperCAmelCase = {
"facebook/dpr-reader-single-nq-base": {"do_lower_case": True},
"facebook/dpr-reader-multiset-base": {"do_lower_case": True},
}
class __magic_name__ ( lowercase_ ):
"""simple docstring"""
_UpperCamelCase = VOCAB_FILES_NAMES
_UpperCamelCase = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
_UpperCamelCase = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_UpperCamelCase = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION
_UpperCamelCase = DPRContextEncoderTokenizer
class __magic_name__ ( lowercase_ ):
"""simple docstring"""
_UpperCamelCase = VOCAB_FILES_NAMES
_UpperCamelCase = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
_UpperCamelCase = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_UpperCamelCase = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION
_UpperCamelCase = DPRQuestionEncoderTokenizer
_UpperCAmelCase = collections.namedtuple(
"DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"]
)
_UpperCAmelCase = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"])
_UpperCAmelCase = r"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n "
@add_start_docstrings(lowercase_ )
class __magic_name__ :
"""simple docstring"""
def __call__( self , a__ , a__ = None , a__ = None , a__ = False , a__ = False , a__ = None , a__ = None , a__ = None , **a__ , ):
if titles is None and texts is None:
return super().__call__(
a__ , padding=a__ , truncation=a__ , max_length=a__ , return_tensors=a__ , return_attention_mask=a__ , **a__ , )
elif titles is None or texts is None:
_lowerCamelCase = titles if texts is None else texts
return super().__call__(
a__ , a__ , padding=a__ , truncation=a__ , max_length=a__ , return_tensors=a__ , return_attention_mask=a__ , **a__ , )
_lowerCamelCase = titles if not isinstance(a__ , a__ ) else [titles]
_lowerCamelCase = texts if not isinstance(a__ , a__ ) else [texts]
_lowerCamelCase = len(a__ )
_lowerCamelCase = questions if not isinstance(a__ , a__ ) else [questions] * n_passages
assert len(a__ ) == len(
a__ ), f'''There should be as many titles than texts but got {len(a__ )} titles and {len(a__ )} texts.'''
_lowerCamelCase = super().__call__(a__ , a__ , padding=a__ , truncation=a__ )['''input_ids''']
_lowerCamelCase = super().__call__(a__ , add_special_tokens=a__ , padding=a__ , truncation=a__ )['''input_ids''']
_lowerCamelCase = {
'''input_ids''': [
(encoded_question_and_title + encoded_text)[:max_length]
if max_length is not None and truncation
else encoded_question_and_title + encoded_text
for encoded_question_and_title, encoded_text in zip(a__ , a__ )
]
}
if return_attention_mask is not False:
_lowerCamelCase = []
for input_ids in encoded_inputs["input_ids"]:
attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] )
_lowerCamelCase = attention_mask
return self.pad(a__ , padding=a__ , max_length=a__ , return_tensors=a__ )
def _UpperCAmelCase ( self , a__ , a__ , a__ = 16 , a__ = 64 , a__ = 4 , ):
_lowerCamelCase = reader_input['''input_ids''']
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase = reader_output[:3]
_lowerCamelCase = len(a__ )
_lowerCamelCase = sorted(range(a__ ) , reverse=a__ , key=relevance_logits.__getitem__ )
_lowerCamelCase = []
for doc_id in sorted_docs:
_lowerCamelCase = list(input_ids[doc_id] )
# assuming question & title information is at the beginning of the sequence
_lowerCamelCase = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id
if sequence_ids[-1] == self.pad_token_id:
_lowerCamelCase = sequence_ids.index(self.pad_token_id )
else:
_lowerCamelCase = len(a__ )
_lowerCamelCase = self._get_best_spans(
start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=a__ , top_spans=a__ , )
for start_index, end_index in best_spans:
start_index += passage_offset
end_index += passage_offset
nbest_spans_predictions.append(
DPRSpanPrediction(
span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=a__ , start_index=a__ , end_index=a__ , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) )
if len(a__ ) >= num_spans:
break
return nbest_spans_predictions[:num_spans]
def _UpperCAmelCase ( self , a__ , a__ , a__ , a__ , ):
_lowerCamelCase = []
for start_index, start_score in enumerate(a__ ):
for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ):
scores.append(((start_index, start_index + answer_length), start_score + end_score) )
_lowerCamelCase = sorted(a__ , key=lambda a__ : x[1] , reverse=a__ )
_lowerCamelCase = []
for (start_index, end_index), score in scores:
assert start_index <= end_index, f'''Wrong span indices: [{start_index}:{end_index}]'''
_lowerCamelCase = end_index - start_index + 1
assert length <= max_answer_length, f'''Span is too long: {length} > {max_answer_length}'''
if any(
start_index <= prev_start_index <= prev_end_index <= end_index
or prev_start_index <= start_index <= end_index <= prev_end_index
for (prev_start_index, prev_end_index) in chosen_span_intervals ):
continue
chosen_span_intervals.append((start_index, end_index) )
if len(a__ ) == top_spans:
break
return chosen_span_intervals
@add_end_docstrings(lowercase_ )
class __magic_name__ ( lowercase_ ,lowercase_ ):
"""simple docstring"""
_UpperCamelCase = VOCAB_FILES_NAMES
_UpperCamelCase = READER_PRETRAINED_VOCAB_FILES_MAP
_UpperCamelCase = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_UpperCamelCase = READER_PRETRAINED_INIT_CONFIGURATION
_UpperCamelCase = ["input_ids", "attention_mask"]
_UpperCamelCase = DPRReaderTokenizer
| 297
|
import argparse
import torch
from transformers import (
SpeechTaConfig,
SpeechTaFeatureExtractor,
SpeechTaForSpeechToSpeech,
SpeechTaForSpeechToText,
SpeechTaForTextToSpeech,
SpeechTaProcessor,
SpeechTaTokenizer,
logging,
)
from transformers.tokenization_utils import AddedToken
logging.set_verbosity_info()
_UpperCAmelCase = logging.get_logger("transformers.models.speecht5")
_UpperCAmelCase = {
"speech_encoder_prenet.layer_norm": "speecht5.encoder.prenet.feature_projection.layer_norm",
"speech_encoder_prenet.post_extract_proj": "speecht5.encoder.prenet.feature_projection.projection",
"speech_encoder_prenet.pos_conv.0": "speecht5.encoder.prenet.pos_conv_embed.conv",
"speech_encoder_prenet.mask_emb": "speecht5.encoder.prenet.masked_spec_embed",
}
_UpperCAmelCase = {
"text_encoder_prenet.encoder_prenet.0": "speecht5.encoder.prenet.embed_tokens",
"text_encoder_prenet.encoder_prenet.1.alpha": "speecht5.encoder.prenet.encode_positions.alpha",
}
_UpperCAmelCase = {
"speech_decoder_prenet.decoder_prenet.0.0.prenet.0.0": "speecht5.decoder.prenet.layers.0",
"speech_decoder_prenet.decoder_prenet.0.0.prenet.1.0": "speecht5.decoder.prenet.layers.1",
"speech_decoder_prenet.decoder_prenet.0.1": "speecht5.decoder.prenet.final_layer",
"speech_decoder_prenet.decoder_prenet.1.alpha": "speecht5.decoder.prenet.encode_positions.alpha",
"speech_decoder_prenet.spkembs_layer.0": "speecht5.decoder.prenet.speaker_embeds_layer",
}
_UpperCAmelCase = {
"speech_decoder_postnet.feat_out": "speech_decoder_postnet.feat_out",
"speech_decoder_postnet.prob_out": "speech_decoder_postnet.prob_out",
"speech_decoder_postnet.postnet.postnet.0.0": "speech_decoder_postnet.layers.0.conv",
"speech_decoder_postnet.postnet.postnet.0.1": "speech_decoder_postnet.layers.0.batch_norm",
"speech_decoder_postnet.postnet.postnet.1.0": "speech_decoder_postnet.layers.1.conv",
"speech_decoder_postnet.postnet.postnet.1.1": "speech_decoder_postnet.layers.1.batch_norm",
"speech_decoder_postnet.postnet.postnet.2.0": "speech_decoder_postnet.layers.2.conv",
"speech_decoder_postnet.postnet.postnet.2.1": "speech_decoder_postnet.layers.2.batch_norm",
"speech_decoder_postnet.postnet.postnet.3.0": "speech_decoder_postnet.layers.3.conv",
"speech_decoder_postnet.postnet.postnet.3.1": "speech_decoder_postnet.layers.3.batch_norm",
"speech_decoder_postnet.postnet.postnet.4.0": "speech_decoder_postnet.layers.4.conv",
"speech_decoder_postnet.postnet.postnet.4.1": "speech_decoder_postnet.layers.4.batch_norm",
}
_UpperCAmelCase = {
"text_decoder_prenet.embed_tokens": "speecht5.decoder.prenet.embed_tokens",
}
_UpperCAmelCase = {
"text_decoder_postnet.output_projection": "text_decoder_postnet.lm_head",
}
_UpperCAmelCase = {
"encoder.layers.*.self_attn.k_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.k_proj",
"encoder.layers.*.self_attn.v_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.v_proj",
"encoder.layers.*.self_attn.q_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.q_proj",
"encoder.layers.*.self_attn.out_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.out_proj",
"encoder.layers.*.self_attn_layer_norm": "speecht5.encoder.wrapped_encoder.layers.*.layer_norm",
"encoder.layers.*.fc1": "speecht5.encoder.wrapped_encoder.layers.*.feed_forward.intermediate_dense",
"encoder.layers.*.fc2": "speecht5.encoder.wrapped_encoder.layers.*.feed_forward.output_dense",
"encoder.layers.*.final_layer_norm": "speecht5.encoder.wrapped_encoder.layers.*.final_layer_norm",
"encoder.layer_norm": "speecht5.encoder.wrapped_encoder.layer_norm",
"encoder.pos_emb.pe_k": "speecht5.encoder.wrapped_encoder.embed_positions.pe_k",
}
_UpperCAmelCase = {
"decoder.layers.*.self_attn.k_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.k_proj",
"decoder.layers.*.self_attn.v_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.v_proj",
"decoder.layers.*.self_attn.q_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.q_proj",
"decoder.layers.*.self_attn.out_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.out_proj",
"decoder.layers.*.self_attn_layer_norm": "speecht5.decoder.wrapped_decoder.layers.*.self_attn_layer_norm",
"decoder.layers.*.encoder_attn.k_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.k_proj",
"decoder.layers.*.encoder_attn.v_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.v_proj",
"decoder.layers.*.encoder_attn.q_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.q_proj",
"decoder.layers.*.encoder_attn.out_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.out_proj",
"decoder.layers.*.encoder_attn_layer_norm": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn_layer_norm",
"decoder.layers.*.fc1": "speecht5.decoder.wrapped_decoder.layers.*.feed_forward.intermediate_dense",
"decoder.layers.*.fc2": "speecht5.decoder.wrapped_decoder.layers.*.feed_forward.output_dense",
"decoder.layers.*.final_layer_norm": "speecht5.decoder.wrapped_decoder.layers.*.final_layer_norm",
}
_UpperCAmelCase = {
**MAPPING_SPEECH_ENCODER_PRENET,
**MAPPING_ENCODER,
**MAPPING_DECODER,
**MAPPING_TEXT_DECODER_PRENET,
**MAPPING_TEXT_DECODER_POSTNET,
}
_UpperCAmelCase = {
**MAPPING_TEXT_ENCODER_PRENET,
**MAPPING_ENCODER,
**MAPPING_DECODER,
**MAPPING_SPEECH_DECODER_PRENET,
**MAPPING_SPEECH_DECODER_POSTNET,
}
_UpperCAmelCase = {
**MAPPING_SPEECH_ENCODER_PRENET,
**MAPPING_ENCODER,
**MAPPING_DECODER,
**MAPPING_SPEECH_DECODER_PRENET,
**MAPPING_SPEECH_DECODER_POSTNET,
}
_UpperCAmelCase = []
_UpperCAmelCase = [
"encoder.version",
"encoder.layers.*.norm_k.weight",
"encoder.layers.*.norm_k.bias",
"decoder.version",
"decoder.layers.*.norm_k.weight",
"decoder.layers.*.norm_k.bias",
"decoder.pos_emb.pe_k",
"speech_encoder_prenet.embed_positions._float_tensor",
"text_decoder_prenet.embed_positions._float_tensor",
]
_UpperCAmelCase = IGNORE_KEYS + [
"encoder.proj",
"text_encoder_prenet.*",
"speech_decoder_prenet.*",
"speech_decoder_postnet.*",
]
_UpperCAmelCase = IGNORE_KEYS + [
"encoder.proj",
"speech_encoder_prenet.*",
"text_decoder_prenet.*",
"text_decoder_postnet.*",
]
_UpperCAmelCase = IGNORE_KEYS + [
"encoder.proj",
"text_encoder_prenet.*",
"text_decoder_prenet.*",
"text_decoder_postnet.*",
]
def _lowerCamelCase ( _a , _a , _a , _a , _a ):
"""simple docstring"""
for attribute in key.split('''.''' ):
_lowerCamelCase = getattr(_a , _a )
if weight_type is not None:
_lowerCamelCase = getattr(_a , _a ).shape
else:
_lowerCamelCase = hf_pointer.shape
if hf_shape != value.shape:
raise ValueError(
F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be'''
F''' {value.shape} for {full_name}''' )
if weight_type == "weight":
_lowerCamelCase = value
elif weight_type == "weight_g":
_lowerCamelCase = value
elif weight_type == "weight_v":
_lowerCamelCase = value
elif weight_type == "bias":
_lowerCamelCase = value
elif weight_type == "running_mean":
_lowerCamelCase = value
elif weight_type == "running_var":
_lowerCamelCase = value
elif weight_type == "num_batches_tracked":
_lowerCamelCase = value
else:
_lowerCamelCase = value
logger.info(F'''{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.''' )
def _lowerCamelCase ( _a , _a ):
"""simple docstring"""
for key in ignore_keys:
if key.endswith('''.*''' ):
if name.startswith(key[:-1] ):
return True
elif ".*." in key:
_lowerCamelCase , _lowerCamelCase = key.split('''.*.''' )
if prefix in name and suffix in name:
return True
elif key in name:
return True
return False
def _lowerCamelCase ( _a , _a , _a ):
"""simple docstring"""
_lowerCamelCase = []
if task == "s2t":
_lowerCamelCase = hf_model.speechta.encoder.prenet.feature_encoder
_lowerCamelCase = MAPPING_S2T
_lowerCamelCase = IGNORE_KEYS_S2T
elif task == "t2s":
_lowerCamelCase = None
_lowerCamelCase = MAPPING_T2S
_lowerCamelCase = IGNORE_KEYS_T2S
elif task == "s2s":
_lowerCamelCase = hf_model.speechta.encoder.prenet.feature_encoder
_lowerCamelCase = MAPPING_S2S
_lowerCamelCase = IGNORE_KEYS_S2S
else:
raise ValueError(F'''Unsupported task: {task}''' )
for name, value in fairseq_dict.items():
if should_ignore(_a , _a ):
logger.info(F'''{name} was ignored''' )
continue
_lowerCamelCase = False
if "conv_layers" in name:
load_conv_layer(
_a , _a , _a , _a , hf_model.config.feat_extract_norm == '''group''' , )
_lowerCamelCase = True
else:
for key, mapped_key in MAPPING.items():
# mapped_key = "speecht5." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if "*" in key:
_lowerCamelCase , _lowerCamelCase = key.split('''.*.''' )
if prefix in name and suffix in name:
_lowerCamelCase = suffix
# if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]:
if key in name:
_lowerCamelCase = True
if "*" in mapped_key:
_lowerCamelCase = name.split(_a )[0].split('''.''' )[-2]
_lowerCamelCase = mapped_key.replace('''*''' , _a )
if "weight_g" in name:
_lowerCamelCase = '''weight_g'''
elif "weight_v" in name:
_lowerCamelCase = '''weight_v'''
elif "bias" in name:
_lowerCamelCase = '''bias'''
elif "weight" in name:
_lowerCamelCase = '''weight'''
elif "running_mean" in name:
_lowerCamelCase = '''running_mean'''
elif "running_var" in name:
_lowerCamelCase = '''running_var'''
elif "num_batches_tracked" in name:
_lowerCamelCase = '''num_batches_tracked'''
else:
_lowerCamelCase = None
set_recursively(_a , _a , _a , _a , _a )
continue
if not is_used:
unused_weights.append(_a )
logger.warning(F'''Unused weights: {unused_weights}''' )
def _lowerCamelCase ( _a , _a , _a , _a , _a ):
"""simple docstring"""
_lowerCamelCase = full_name.split('''conv_layers.''' )[-1]
_lowerCamelCase = name.split('''.''' )
_lowerCamelCase = int(items[0] )
_lowerCamelCase = int(items[1] )
if type_id == 0:
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' )
_lowerCamelCase = value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' )
_lowerCamelCase = value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' )
_lowerCamelCase = value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' )
_lowerCamelCase = value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
else:
unused_weights.append(_a )
@torch.no_grad()
def _lowerCamelCase ( _a , _a , _a , _a=None , _a=None , _a=None , ):
"""simple docstring"""
if config_path is not None:
_lowerCamelCase = SpeechTaConfig.from_pretrained(_a )
else:
_lowerCamelCase = SpeechTaConfig()
if task == "s2t":
_lowerCamelCase = config.max_text_positions
_lowerCamelCase = SpeechTaForSpeechToText(_a )
elif task == "t2s":
_lowerCamelCase = 1_8_7_6
_lowerCamelCase = 6_0_0
_lowerCamelCase = config.max_speech_positions
_lowerCamelCase = SpeechTaForTextToSpeech(_a )
elif task == "s2s":
_lowerCamelCase = 1_8_7_6
_lowerCamelCase = config.max_speech_positions
_lowerCamelCase = SpeechTaForSpeechToSpeech(_a )
else:
raise ValueError(F'''Unknown task name: {task}''' )
if vocab_path:
_lowerCamelCase = SpeechTaTokenizer(_a , model_max_length=config.max_text_positions )
# Mask token behaves like a normal word, i.e. include the space before it
_lowerCamelCase = AddedToken('''<mask>''' , lstrip=_a , rstrip=_a )
_lowerCamelCase = mask_token
tokenizer.add_special_tokens({'''mask_token''': mask_token} )
tokenizer.add_tokens(['''<ctc_blank>'''] )
_lowerCamelCase = SpeechTaFeatureExtractor()
_lowerCamelCase = SpeechTaProcessor(tokenizer=_a , feature_extractor=_a )
processor.save_pretrained(_a )
_lowerCamelCase = torch.load(_a )
recursively_load_weights(fairseq_checkpoint['''model'''] , _a , _a )
model.save_pretrained(_a )
if repo_id:
print('''Pushing to the hub...''' )
processor.push_to_hub(_a )
model.push_to_hub(_a )
if __name__ == "__main__":
_UpperCAmelCase = argparse.ArgumentParser()
parser.add_argument(
"--task",
default="s2t",
type=str,
help="Type of the SpeechT5 model you'd like to convert. Should be one of 's2t', 't2s', 's2s'.",
)
parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to fairseq checkpoint")
parser.add_argument("--vocab_path", default=None, type=str, help="Path to SentencePiece model")
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
parser.add_argument(
"--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model."
)
parser.add_argument(
"--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub."
)
_UpperCAmelCase = parser.parse_args()
convert_speechta_checkpoint(
args.task,
args.checkpoint_path,
args.pytorch_dump_folder_path,
args.config_path,
args.vocab_path,
args.push_to_hub,
)
| 297
| 1
|
'''simple docstring'''
import gc
import random
import unittest
import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel
from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
class _snake_case( _UpperCamelCase , unittest.TestCase ):
__snake_case: Tuple = ShapEImgaImgPipeline
__snake_case: Optional[Any] = ["image"]
__snake_case: List[str] = ["image"]
__snake_case: Optional[Any] = [
"num_images_per_prompt",
"num_inference_steps",
"generator",
"latents",
"guidance_scale",
"frame_size",
"output_type",
"return_dict",
]
__snake_case: Tuple = False
@property
def _UpperCamelCase (self : str ) -> str:
"""simple docstring"""
return 32
@property
def _UpperCamelCase (self : List[Any] ) -> Any:
"""simple docstring"""
return 32
@property
def _UpperCamelCase (self : Dict ) -> List[str]:
"""simple docstring"""
return self.time_input_dim * 4
@property
def _UpperCamelCase (self : Tuple ) -> Any:
"""simple docstring"""
return 8
@property
def _UpperCamelCase (self : List[str] ) -> int:
"""simple docstring"""
torch.manual_seed(0 )
A__ = CLIPVisionConfig(
hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , )
A__ = CLIPVisionModel(a )
return model
@property
def _UpperCamelCase (self : str ) -> Optional[int]:
"""simple docstring"""
A__ = CLIPImageProcessor(
crop_size=2_24 , do_center_crop=a , do_normalize=a , do_resize=a , 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_24 , )
return image_processor
@property
def _UpperCamelCase (self : int ) -> Optional[Any]:
"""simple docstring"""
torch.manual_seed(0 )
A__ = {
'num_attention_heads': 2,
'attention_head_dim': 16,
'embedding_dim': self.time_input_dim,
'num_embeddings': 32,
'embedding_proj_dim': self.text_embedder_hidden_size,
'time_embed_dim': self.time_embed_dim,
'num_layers': 1,
'clip_embed_dim': self.time_input_dim * 2,
'additional_embeddings': 0,
'time_embed_act_fn': 'gelu',
'norm_in_type': 'layer',
'embedding_proj_norm_type': 'layer',
'encoder_hid_proj_type': None,
'added_emb_type': None,
}
A__ = PriorTransformer(**a )
return model
@property
def _UpperCamelCase (self : int ) -> int:
"""simple docstring"""
torch.manual_seed(0 )
A__ = {
'param_shapes': (
(self.renderer_dim, 93),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
),
'd_latent': self.time_input_dim,
'd_hidden': self.renderer_dim,
'n_output': 12,
'background': (
0.1,
0.1,
0.1,
),
}
A__ = ShapERenderer(**a )
return model
def _UpperCamelCase (self : Any ) -> Any:
"""simple docstring"""
A__ = self.dummy_prior
A__ = self.dummy_image_encoder
A__ = self.dummy_image_processor
A__ = self.dummy_renderer
A__ = HeunDiscreteScheduler(
beta_schedule='exp' , num_train_timesteps=10_24 , prediction_type='sample' , use_karras_sigmas=a , clip_sample=a , clip_sample_range=1.0 , )
A__ = {
'prior': prior,
'image_encoder': image_encoder,
'image_processor': image_processor,
'renderer': renderer,
'scheduler': scheduler,
}
return components
def _UpperCamelCase (self : str , a : Optional[int] , a : Any=0 ) -> Union[str, Any]:
"""simple docstring"""
A__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(a ) ).to(a )
if str(a ).startswith('mps' ):
A__ = torch.manual_seed(a )
else:
A__ = torch.Generator(device=a ).manual_seed(a )
A__ = {
'image': input_image,
'generator': generator,
'num_inference_steps': 1,
'frame_size': 32,
'output_type': 'np',
}
return inputs
def _UpperCamelCase (self : Dict ) -> Tuple:
"""simple docstring"""
A__ = 'cpu'
A__ = self.get_dummy_components()
A__ = self.pipeline_class(**a )
A__ = pipe.to(a )
pipe.set_progress_bar_config(disable=a )
A__ = pipe(**self.get_dummy_inputs(a ) )
A__ = output.images[0]
A__ = image[0, -3:, -3:, -1]
assert image.shape == (20, 32, 32, 3)
A__ = np.array(
[
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def _UpperCamelCase (self : str ) -> Dict:
"""simple docstring"""
self._test_inference_batch_consistent(batch_sizes=[1, 2] )
def _UpperCamelCase (self : Tuple ) -> Optional[int]:
"""simple docstring"""
A__ = torch_device == 'cpu'
A__ = True
self._test_inference_batch_single_identical(
batch_size=2 , test_max_difference=a , relax_max_difference=a , )
def _UpperCamelCase (self : Union[str, Any] ) -> Dict:
"""simple docstring"""
A__ = self.get_dummy_components()
A__ = self.pipeline_class(**a )
A__ = pipe.to(a )
pipe.set_progress_bar_config(disable=a )
A__ = 1
A__ = 2
A__ = self.get_dummy_inputs(a )
for key in inputs.keys():
if key in self.batch_params:
A__ = batch_size * [inputs[key]]
A__ = pipe(**a , num_images_per_prompt=a )[0]
assert images.shape[0] == batch_size * num_images_per_prompt
@slow
@require_torch_gpu
class _snake_case( unittest.TestCase ):
def _UpperCamelCase (self : str ) -> Tuple:
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _UpperCamelCase (self : Optional[Any] ) -> Union[str, Any]:
"""simple docstring"""
A__ = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/corgi.png' )
A__ = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/shap_e/test_shap_e_img2img_out.npy' )
A__ = ShapEImgaImgPipeline.from_pretrained('openai/shap-e-img2img' )
A__ = pipe.to(a )
pipe.set_progress_bar_config(disable=a )
A__ = torch.Generator(device=a ).manual_seed(0 )
A__ = pipe(
a , generator=a , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0]
assert images.shape == (20, 64, 64, 3)
assert_mean_pixel_difference(a , a )
| 531
|
"""simple docstring"""
import math
from typing import Optional
import numpy as np
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a__ : Any = logging.get_logger(__name__)
a__ : Tuple = {
"""facebook/encodec_24khz""": """https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json""",
"""facebook/encodec_48khz""": """https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json""",
}
class __magic_name__ ( _UpperCamelCase ):
UpperCamelCase : Tuple = "encodec"
def __init__( self , __magic_name__=[1.5, 3.0, 6.0, 12.0, 24.0] , __magic_name__=2_4_0_0_0 , __magic_name__=1 , __magic_name__=False , __magic_name__=None , __magic_name__=None , __magic_name__=1_2_8 , __magic_name__=3_2 , __magic_name__=1 , __magic_name__=[8, 5, 4, 2] , __magic_name__="weight_norm" , __magic_name__=7 , __magic_name__=7 , __magic_name__=3 , __magic_name__=2 , __magic_name__=True , __magic_name__="reflect" , __magic_name__=2 , __magic_name__=2 , __magic_name__=1.0 , __magic_name__=1_0_2_4 , __magic_name__=None , __magic_name__=True , **__magic_name__ , ):
"""simple docstring"""
_lowerCAmelCase = target_bandwidths
_lowerCAmelCase = sampling_rate
_lowerCAmelCase = audio_channels
_lowerCAmelCase = normalize
_lowerCAmelCase = chunk_length_s
_lowerCAmelCase = overlap
_lowerCAmelCase = hidden_size
_lowerCAmelCase = num_filters
_lowerCAmelCase = num_residual_layers
_lowerCAmelCase = upsampling_ratios
_lowerCAmelCase = norm_type
_lowerCAmelCase = kernel_size
_lowerCAmelCase = last_kernel_size
_lowerCAmelCase = residual_kernel_size
_lowerCAmelCase = dilation_growth_rate
_lowerCAmelCase = use_causal_conv
_lowerCAmelCase = pad_mode
_lowerCAmelCase = compress
_lowerCAmelCase = num_lstm_layers
_lowerCAmelCase = trim_right_ratio
_lowerCAmelCase = codebook_size
_lowerCAmelCase = codebook_dim if codebook_dim is not None else hidden_size
_lowerCAmelCase = use_conv_shortcut
if self.norm_type not in ["weight_norm", "time_group_norm"]:
raise ValueError(
F'''self.norm_type must be one of `"weight_norm"`, `"time_group_norm"`), got {self.norm_type}''' )
super().__init__(**__magic_name__ )
@property
def _lowerCamelCase ( self ):
"""simple docstring"""
if self.chunk_length_s is None:
return None
else:
return int(self.chunk_length_s * self.sampling_rate )
@property
def _lowerCamelCase ( self ):
"""simple docstring"""
if self.chunk_length_s is None or self.overlap is None:
return None
else:
return max(1 , int((1.0 - self.overlap) * self.chunk_length ) )
@property
def _lowerCamelCase ( self ):
"""simple docstring"""
_lowerCAmelCase = np.prod(self.upsampling_ratios )
return math.ceil(self.sampling_rate / hop_length )
@property
def _lowerCamelCase ( self ):
"""simple docstring"""
return int(1_0_0_0 * self.target_bandwidths[-1] // (self.frame_rate * 1_0) )
| 589
| 0
|
class snake_case_ :
"""simple docstring"""
def __init__( self):
"""simple docstring"""
UpperCAmelCase_ : dict[str, TrieNode] = {} # Mapping from char to TrieNode
UpperCAmelCase_ : Tuple = False
def A_ ( self ,lowercase):
"""simple docstring"""
for word in words:
self.insert(lowercase)
def A_ ( self ,lowercase):
"""simple docstring"""
UpperCAmelCase_ : Any = self
for char in word:
if char not in curr.nodes:
UpperCAmelCase_ : str = TrieNode()
UpperCAmelCase_ : Tuple = curr.nodes[char]
UpperCAmelCase_ : Union[str, Any] = True
def A_ ( self ,lowercase):
"""simple docstring"""
UpperCAmelCase_ : Union[str, Any] = self
for char in word:
if char not in curr.nodes:
return False
UpperCAmelCase_ : List[Any] = curr.nodes[char]
return curr.is_leaf
def A_ ( self ,lowercase):
"""simple docstring"""
def _delete(lowercase ,lowercase ,lowercase) -> bool:
if index == len(lowercase):
# If word does not exist
if not curr.is_leaf:
return False
UpperCAmelCase_ : List[str] = False
return len(curr.nodes) == 0
UpperCAmelCase_ : List[str] = word[index]
UpperCAmelCase_ : Union[str, Any] = curr.nodes.get(lowercase)
# If char not in current trie node
if not char_node:
return False
# Flag to check if node can be deleted
UpperCAmelCase_ : Tuple = _delete(lowercase ,lowercase ,index + 1)
if delete_curr:
del curr.nodes[char]
return len(curr.nodes) == 0
return delete_curr
_delete(self ,lowercase ,0)
def _snake_case ( __snake_case , __snake_case ) -> None:
'''simple docstring'''
if node.is_leaf:
print(__snake_case , end=" " )
for key, value in node.nodes.items():
print_words(__snake_case , word + key )
def _snake_case ( ) -> bool:
'''simple docstring'''
UpperCAmelCase_ : Tuple = "banana bananas bandana band apple all beast".split()
UpperCAmelCase_ : Any = TrieNode()
root.insert_many(__snake_case )
# print_words(root, "")
assert all(root.find(__snake_case ) for word in words )
assert root.find("banana" )
assert not root.find("bandanas" )
assert not root.find("apps" )
assert root.find("apple" )
assert root.find("all" )
root.delete("all" )
assert not root.find("all" )
root.delete("banana" )
assert not root.find("banana" )
assert root.find("bananas" )
return True
def _snake_case ( __snake_case , __snake_case ) -> None:
'''simple docstring'''
print(str(__snake_case ) , "works!" if passes else "doesn't work :(" )
def _snake_case ( ) -> None:
'''simple docstring'''
assert test_trie()
def _snake_case ( ) -> None:
'''simple docstring'''
print_results("Testing trie functionality" , test_trie() )
if __name__ == "__main__":
main()
| 455
|
import argparse
import logging
import pickle
import random
import time
import numpy as np
from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO
)
__lowerCamelCase = logging.getLogger(__name__)
def _snake_case ( ) -> Dict:
'''simple docstring'''
UpperCAmelCase_ : Any = argparse.ArgumentParser(
description="Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids)." )
parser.add_argument("--file_path" , type=__snake_case , default="data/dump.txt" , help="The path to the data." )
parser.add_argument("--tokenizer_type" , type=__snake_case , default="bert" , choices=["bert", "roberta", "gpt2"] )
parser.add_argument("--tokenizer_name" , type=__snake_case , default="bert-base-uncased" , help="The tokenizer to use." )
parser.add_argument("--dump_file" , type=__snake_case , default="data/dump" , help="The dump file prefix." )
UpperCAmelCase_ : str = parser.parse_args()
logger.info(F"""Loading Tokenizer ({args.tokenizer_name})""" )
if args.tokenizer_type == "bert":
UpperCAmelCase_ : int = BertTokenizer.from_pretrained(args.tokenizer_name )
UpperCAmelCase_ : Optional[Any] = tokenizer.special_tokens_map["cls_token"] # `[CLS]`
UpperCAmelCase_ : Dict = tokenizer.special_tokens_map["sep_token"] # `[SEP]`
elif args.tokenizer_type == "roberta":
UpperCAmelCase_ : str = RobertaTokenizer.from_pretrained(args.tokenizer_name )
UpperCAmelCase_ : int = tokenizer.special_tokens_map["cls_token"] # `<s>`
UpperCAmelCase_ : Optional[Any] = tokenizer.special_tokens_map["sep_token"] # `</s>`
elif args.tokenizer_type == "gpt2":
UpperCAmelCase_ : Tuple = GPTaTokenizer.from_pretrained(args.tokenizer_name )
UpperCAmelCase_ : List[Any] = tokenizer.special_tokens_map["bos_token"] # `<|endoftext|>`
UpperCAmelCase_ : List[str] = tokenizer.special_tokens_map["eos_token"] # `<|endoftext|>`
logger.info(F"""Loading text from {args.file_path}""" )
with open(args.file_path , "r" , encoding="utf8" ) as fp:
UpperCAmelCase_ : Union[str, Any] = fp.readlines()
logger.info("Start encoding" )
logger.info(F"""{len(__snake_case )} examples to process.""" )
UpperCAmelCase_ : List[str] = []
UpperCAmelCase_ : str = 0
UpperCAmelCase_ : Union[str, Any] = 1_0_0_0_0
UpperCAmelCase_ : int = time.time()
for text in data:
UpperCAmelCase_ : str = F"""{bos} {text.strip()} {sep}"""
UpperCAmelCase_ : Any = tokenizer.encode(__snake_case , add_special_tokens=__snake_case )
rslt.append(__snake_case )
iter += 1
if iter % interval == 0:
UpperCAmelCase_ : List[str] = time.time()
logger.info(F"""{iter} examples processed. - {(end-start):.2f}s/{interval}expl""" )
UpperCAmelCase_ : Optional[Any] = time.time()
logger.info("Finished binarization" )
logger.info(F"""{len(__snake_case )} examples processed.""" )
UpperCAmelCase_ : List[Any] = F"""{args.dump_file}.{args.tokenizer_name}.pickle"""
UpperCAmelCase_ : Optional[int] = tokenizer.vocab_size
if vocab_size < (1 << 1_6):
UpperCAmelCase_ : List[Any] = [np.uintaa(__snake_case ) for d in rslt]
else:
UpperCAmelCase_ : str = [np.intaa(__snake_case ) for d in rslt]
random.shuffle(rslt_ )
logger.info(F"""Dump to {dp_file}""" )
with open(__snake_case , "wb" ) as handle:
pickle.dump(rslt_ , __snake_case , protocol=pickle.HIGHEST_PROTOCOL )
if __name__ == "__main__":
main()
| 455
| 1
|
'''simple docstring'''
import math
import sys
def _a ( _lowerCamelCase ) -> str:
"""simple docstring"""
__snake_case : List[str] = """"""
try:
with open(_lowerCamelCase , """rb""" ) as binary_file:
__snake_case : Optional[Any] = binary_file.read()
for dat in data:
__snake_case : Union[str, Any] = F'''{dat:08b}'''
result += curr_byte
return result
except OSError:
print("""File not accessible""" )
sys.exit()
def _a ( _lowerCamelCase ) -> str:
"""simple docstring"""
__snake_case : int = {"""0""": """0""", """1""": """1"""}
__snake_case , __snake_case : List[str] = """""", """"""
__snake_case : Dict = len(_lowerCamelCase )
for i in range(len(_lowerCamelCase ) ):
curr_string += data_bits[i]
if curr_string not in lexicon:
continue
__snake_case : str = lexicon[curr_string]
result += last_match_id
__snake_case : List[str] = last_match_id + """0"""
if math.loga(_lowerCamelCase ).is_integer():
__snake_case : Optional[int] = {}
for curr_key in list(_lowerCamelCase ):
__snake_case : Optional[Any] = lexicon.pop(_lowerCamelCase )
__snake_case : Optional[int] = new_lex
__snake_case : List[Any] = last_match_id + """1"""
index += 1
__snake_case : List[Any] = """"""
return result
def _a ( _lowerCamelCase , _lowerCamelCase ) -> None:
"""simple docstring"""
__snake_case : Optional[Any] = 8
try:
with open(_lowerCamelCase , """wb""" ) as opened_file:
__snake_case : Any = [
to_write[i : i + byte_length]
for i in range(0 , len(_lowerCamelCase ) , _lowerCamelCase )
]
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(_lowerCamelCase , 2 ).to_bytes(1 , byteorder="""big""" ) )
except OSError:
print("""File not accessible""" )
sys.exit()
def _a ( _lowerCamelCase ) -> str:
"""simple docstring"""
__snake_case : List[Any] = 0
for letter in data_bits:
if letter == "1":
break
counter += 1
__snake_case : Optional[int] = data_bits[counter:]
__snake_case : int = data_bits[counter + 1 :]
return data_bits
def _a ( _lowerCamelCase , _lowerCamelCase ) -> None:
"""simple docstring"""
__snake_case : Union[str, Any] = read_file_binary(_lowerCamelCase )
__snake_case : Optional[int] = remove_prefix(_lowerCamelCase )
__snake_case : int = decompress_data(_lowerCamelCase )
write_file_binary(_lowerCamelCase , _lowerCamelCase )
if __name__ == "__main__":
compress(sys.argv[1], sys.argv[2])
| 26
|
import argparse
import json
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Dict:
"""simple docstring"""
a = 3_8_4
if "tiny" in model_name:
a = [3, 3, 9, 3]
a = [9_6, 1_9_2, 3_8_4, 7_6_8]
if "small" in model_name:
a = [3, 3, 2_7, 3]
a = [9_6, 1_9_2, 3_8_4, 7_6_8]
if "base" in model_name:
a = [3, 3, 2_7, 3]
a = [1_2_8, 2_5_6, 5_1_2, 1_0_2_4]
a = 5_1_2
if "large" in model_name:
a = [3, 3, 2_7, 3]
a = [1_9_2, 3_8_4, 7_6_8, 1_5_3_6]
a = 7_6_8
if "xlarge" in model_name:
a = [3, 3, 2_7, 3]
a = [2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8]
a = 1_0_2_4
# set label information
a = 1_5_0
a = '''huggingface/label-files'''
a = '''ade20k-id2label.json'''
a = json.load(open(hf_hub_download(snake_case_, snake_case_, repo_type='''dataset''' ), '''r''' ) )
a = {int(snake_case_ ): v for k, v in idalabel.items()}
a = {v: k for k, v in idalabel.items()}
a = ConvNextConfig(
depths=snake_case_, hidden_sizes=snake_case_, out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] )
a = UperNetConfig(
backbone_config=snake_case_, auxiliary_in_channels=snake_case_, num_labels=snake_case_, idalabel=snake_case_, labelaid=snake_case_, )
return config
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Dict:
"""simple docstring"""
a = []
# fmt: off
# stem
rename_keys.append(('''backbone.downsample_layers.0.0.weight''', '''backbone.embeddings.patch_embeddings.weight''') )
rename_keys.append(('''backbone.downsample_layers.0.0.bias''', '''backbone.embeddings.patch_embeddings.bias''') )
rename_keys.append(('''backbone.downsample_layers.0.1.weight''', '''backbone.embeddings.layernorm.weight''') )
rename_keys.append(('''backbone.downsample_layers.0.1.bias''', '''backbone.embeddings.layernorm.bias''') )
# stages
for i in range(len(config.backbone_config.depths ) ):
for j in range(config.backbone_config.depths[i] ):
rename_keys.append((f"""backbone.stages.{i}.{j}.gamma""", f"""backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter""") )
rename_keys.append((f"""backbone.stages.{i}.{j}.depthwise_conv.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.dwconv.weight""") )
rename_keys.append((f"""backbone.stages.{i}.{j}.depthwise_conv.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.dwconv.bias""") )
rename_keys.append((f"""backbone.stages.{i}.{j}.norm.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.layernorm.weight""") )
rename_keys.append((f"""backbone.stages.{i}.{j}.norm.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.layernorm.bias""") )
rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv1.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight""") )
rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv1.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias""") )
rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv2.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight""") )
rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv2.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias""") )
if i > 0:
rename_keys.append((f"""backbone.downsample_layers.{i}.0.weight""", f"""backbone.encoder.stages.{i}.downsampling_layer.0.weight""") )
rename_keys.append((f"""backbone.downsample_layers.{i}.0.bias""", f"""backbone.encoder.stages.{i}.downsampling_layer.0.bias""") )
rename_keys.append((f"""backbone.downsample_layers.{i}.1.weight""", f"""backbone.encoder.stages.{i}.downsampling_layer.1.weight""") )
rename_keys.append((f"""backbone.downsample_layers.{i}.1.bias""", f"""backbone.encoder.stages.{i}.downsampling_layer.1.bias""") )
rename_keys.append((f"""backbone.norm{i}.weight""", f"""backbone.hidden_states_norms.stage{i+1}.weight""") )
rename_keys.append((f"""backbone.norm{i}.bias""", f"""backbone.hidden_states_norms.stage{i+1}.bias""") )
# decode head
rename_keys.extend(
[
('''decode_head.conv_seg.weight''', '''decode_head.classifier.weight'''),
('''decode_head.conv_seg.bias''', '''decode_head.classifier.bias'''),
('''auxiliary_head.conv_seg.weight''', '''auxiliary_head.classifier.weight'''),
('''auxiliary_head.conv_seg.bias''', '''auxiliary_head.classifier.bias'''),
] )
# fmt: on
return rename_keys
def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> Optional[Any]:
"""simple docstring"""
a = dct.pop(snake_case_ )
a = val
def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> Optional[int]:
"""simple docstring"""
a = {
'''upernet-convnext-tiny''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth''',
'''upernet-convnext-small''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth''',
'''upernet-convnext-base''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth''',
'''upernet-convnext-large''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth''',
'''upernet-convnext-xlarge''': '''https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth''',
}
a = model_name_to_url[model_name]
a = torch.hub.load_state_dict_from_url(snake_case_, map_location='''cpu''' )['''state_dict''']
a = get_upernet_config(snake_case_ )
a = UperNetForSemanticSegmentation(snake_case_ )
model.eval()
# replace "bn" => "batch_norm"
for key in state_dict.copy().keys():
a = state_dict.pop(snake_case_ )
if "bn" in key:
a = key.replace('''bn''', '''batch_norm''' )
a = val
# rename keys
a = create_rename_keys(snake_case_ )
for src, dest in rename_keys:
rename_key(snake_case_, snake_case_, snake_case_ )
model.load_state_dict(snake_case_ )
# verify on image
a = '''https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg'''
a = Image.open(requests.get(snake_case_, stream=snake_case_ ).raw ).convert('''RGB''' )
a = SegformerImageProcessor()
a = processor(snake_case_, return_tensors='''pt''' ).pixel_values
with torch.no_grad():
a = model(snake_case_ )
if model_name == "upernet-convnext-tiny":
a = torch.tensor(
[[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] )
elif model_name == "upernet-convnext-small":
a = torch.tensor(
[[-8.8236, -8.8236, -8.6771], [-8.8236, -8.8236, -8.6771], [-8.7638, -8.7638, -8.6240]] )
elif model_name == "upernet-convnext-base":
a = torch.tensor(
[[-8.8558, -8.8558, -8.6905], [-8.8558, -8.8558, -8.6905], [-8.7669, -8.7669, -8.6021]] )
elif model_name == "upernet-convnext-large":
a = torch.tensor(
[[-8.6660, -8.6660, -8.6210], [-8.6660, -8.6660, -8.6210], [-8.6310, -8.6310, -8.5964]] )
elif model_name == "upernet-convnext-xlarge":
a = torch.tensor(
[[-8.4980, -8.4980, -8.3977], [-8.4980, -8.4980, -8.3977], [-8.4379, -8.4379, -8.3412]] )
print('''Logits:''', outputs.logits[0, 0, :3, :3] )
assert torch.allclose(outputs.logits[0, 0, :3, :3], snake_case_, atol=1e-4 )
print('''Looks ok!''' )
if pytorch_dump_folder_path is not None:
print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" )
model.save_pretrained(snake_case_ )
print(f"""Saving processor to {pytorch_dump_folder_path}""" )
processor.save_pretrained(snake_case_ )
if push_to_hub:
print(f"""Pushing model and processor for {model_name} to hub""" )
model.push_to_hub(f"""openmmlab/{model_name}""" )
processor.push_to_hub(f"""openmmlab/{model_name}""" )
if __name__ == "__main__":
UpperCamelCase__ : List[Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--model_name""",
default="""upernet-convnext-tiny""",
type=str,
choices=[F"upernet-convnext-{size}" for size in ["""tiny""", """small""", """base""", """large""", """xlarge"""]],
help="""Name of the ConvNext UperNet model you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
)
parser.add_argument(
"""--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
)
UpperCamelCase__ : int = parser.parse_args()
convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 387
| 0
|
'''simple docstring'''
def a__ ( __UpperCamelCase ):
SCREAMING_SNAKE_CASE_ = [0] * len(__UpperCamelCase )
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
for values in graph.values():
for i in values:
indegree[i] += 1
for i in range(len(__UpperCamelCase ) ):
if indegree[i] == 0:
queue.append(__UpperCamelCase )
while queue:
SCREAMING_SNAKE_CASE_ = queue.pop(0 )
cnt += 1
topo.append(__UpperCamelCase )
for x in graph[vertex]:
indegree[x] -= 1
if indegree[x] == 0:
queue.append(__UpperCamelCase )
if cnt != len(__UpperCamelCase ):
print("Cycle exists" )
else:
print(__UpperCamelCase )
# Adjacency List of Graph
A : Any = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
topological_sort(graph)
| 706
|
from __future__ import annotations
def a__ ( __UpperCamelCase ):
SCREAMING_SNAKE_CASE_ = str(__UpperCamelCase )
return n == n[::-1]
def a__ ( __UpperCamelCase = 1_0_0_0_0_0_0 ):
SCREAMING_SNAKE_CASE_ = 0
for i in range(1 , __UpperCamelCase ):
if is_palindrome(__UpperCamelCase ) and is_palindrome(bin(__UpperCamelCase ).split("b" )[1] ):
total += i
return total
if __name__ == "__main__":
print(solution(int(str(input().strip()))))
| 356
| 0
|
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 lowerCAmelCase ( lowercase_ ):
def UpperCAmelCase ( self :Union[str, Any] ):
'''simple docstring'''
lowercase__ = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(_lowercase , "width_multiplier" ) )
class lowerCAmelCase :
def __init__( self :Any , _lowercase :str , _lowercase :Any=13 , _lowercase :Any=64 , _lowercase :Optional[int]=2 , _lowercase :List[str]=3 , _lowercase :Tuple="swish" , _lowercase :int=3 , _lowercase :str=32 , _lowercase :Tuple=0.1 , _lowercase :int=0.02 , _lowercase :str=True , _lowercase :Tuple=True , _lowercase :List[str]=10 , _lowercase :Optional[int]=None , _lowercase :Dict=0.25 , _lowercase :List[Any]=0.0 , _lowercase :str=0.0 , ):
'''simple docstring'''
lowercase__ = parent
lowercase__ = batch_size
lowercase__ = image_size
lowercase__ = patch_size
lowercase__ = num_channels
lowercase__ = make_divisible(5_12 * width_multiplier , divisor=8 )
lowercase__ = hidden_act
lowercase__ = conv_kernel_size
lowercase__ = output_stride
lowercase__ = classifier_dropout_prob
lowercase__ = use_labels
lowercase__ = is_training
lowercase__ = num_labels
lowercase__ = initializer_range
lowercase__ = scope
lowercase__ = width_multiplier
lowercase__ = ffn_dropout
lowercase__ = attn_dropout
def UpperCAmelCase ( self :Tuple ):
'''simple docstring'''
lowercase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowercase__ = None
lowercase__ = None
if self.use_labels:
lowercase__ = ids_tensor([self.batch_size] , self.num_labels )
lowercase__ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
lowercase__ = self.get_config()
return config, pixel_values, labels, pixel_labels
def UpperCAmelCase ( self :Dict ):
'''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 :Union[str, Any] , _lowercase :List[Any] , _lowercase :Optional[Any] , _lowercase :Tuple , _lowercase :Any ):
'''simple docstring'''
lowercase__ = MobileViTVaModel(config=_lowercase )
model.to(_lowercase )
model.eval()
lowercase__ = 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 UpperCAmelCase ( self :int , _lowercase :Union[str, Any] , _lowercase :str , _lowercase :Optional[Any] , _lowercase :Optional[int] ):
'''simple docstring'''
lowercase__ = self.num_labels
lowercase__ = MobileViTVaForImageClassification(_lowercase )
model.to(_lowercase )
model.eval()
lowercase__ = model(_lowercase , labels=_lowercase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def UpperCAmelCase ( self :str , _lowercase :List[str] , _lowercase :List[Any] , _lowercase :str , _lowercase :Optional[int] ):
'''simple docstring'''
lowercase__ = self.num_labels
lowercase__ = MobileViTVaForSemanticSegmentation(_lowercase )
model.to(_lowercase )
model.eval()
lowercase__ = 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,
) , )
lowercase__ = 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 UpperCAmelCase ( self :List[Any] ):
'''simple docstring'''
lowercase__ = self.prepare_config_and_inputs()
lowercase__ , lowercase__ , lowercase__ , lowercase__ = config_and_inputs
lowercase__ = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class lowerCAmelCase ( lowercase_ , lowercase_ , unittest.TestCase ):
__lowerCamelCase = (
(MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
if is_torch_available()
else ()
)
__lowerCamelCase = (
{
'feature-extraction': MobileViTVaModel,
'image-classification': MobileViTVaForImageClassification,
'image-segmentation': MobileViTVaForSemanticSegmentation,
}
if is_torch_available()
else {}
)
__lowerCamelCase = False
__lowerCamelCase = False
__lowerCamelCase = False
__lowerCamelCase = False
def UpperCAmelCase ( self :List[Any] ):
'''simple docstring'''
lowercase__ = MobileViTVaModelTester(self )
lowercase__ = MobileViTVaConfigTester(self , config_class=_lowercase , has_text_modality=_lowercase )
def UpperCAmelCase ( self :int ):
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason="MobileViTV2 does not use inputs_embeds" )
def UpperCAmelCase ( self :Optional[Any] ):
'''simple docstring'''
pass
@unittest.skip(reason="MobileViTV2 does not support input and output embeddings" )
def UpperCAmelCase ( self :List[str] ):
'''simple docstring'''
pass
@unittest.skip(reason="MobileViTV2 does not output attentions" )
def UpperCAmelCase ( self :int ):
'''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 :Any ):
'''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 :Union[str, Any] ):
'''simple docstring'''
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase__ = model_class(_lowercase )
lowercase__ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowercase__ = [*signature.parameters.keys()]
lowercase__ = ["pixel_values"]
self.assertListEqual(arg_names[:1] , _lowercase )
def UpperCAmelCase ( self :List[Any] ):
'''simple docstring'''
lowercase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_lowercase )
def UpperCAmelCase ( self :Any ):
'''simple docstring'''
def check_hidden_states_output(_lowercase :Any , _lowercase :Optional[int] , _lowercase :Union[str, Any] ):
lowercase__ = model_class(_lowercase )
model.to(_lowercase )
model.eval()
with torch.no_grad():
lowercase__ = model(**self._prepare_for_class(_lowercase , _lowercase ) )
lowercase__ = outputs.hidden_states
lowercase__ = 5
self.assertEqual(len(_lowercase ) , _lowercase )
# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
# with the width and height being successively divided by 2.
lowercase__ = 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 )
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase__ = True
check_hidden_states_output(_lowercase , _lowercase , _lowercase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowercase__ = True
check_hidden_states_output(_lowercase , _lowercase , _lowercase )
def UpperCAmelCase ( self :List[str] ):
'''simple docstring'''
lowercase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_lowercase )
def UpperCAmelCase ( self :Tuple ):
'''simple docstring'''
lowercase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*_lowercase )
@slow
def UpperCAmelCase ( self :List[Any] ):
'''simple docstring'''
for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowercase__ = MobileViTVaModel.from_pretrained(_lowercase )
self.assertIsNotNone(_lowercase )
def _A ( ):
lowercase__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
@require_vision
class lowerCAmelCase ( unittest.TestCase ):
@cached_property
def UpperCAmelCase ( self :Tuple ):
'''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'''
lowercase__ = MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256" ).to(
_lowercase )
lowercase__ = self.default_image_processor
lowercase__ = prepare_img()
lowercase__ = image_processor(images=_lowercase , return_tensors="pt" ).to(_lowercase )
# forward pass
with torch.no_grad():
lowercase__ = model(**_lowercase )
# verify the logits
lowercase__ = torch.Size((1, 10_00) )
self.assertEqual(outputs.logits.shape , _lowercase )
lowercase__ = torch.tensor([-1.63_36e00, -7.32_04e-02, -5.18_83e-01] ).to(_lowercase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowercase , atol=1e-4 ) )
@slow
def UpperCAmelCase ( self :Union[str, Any] ):
'''simple docstring'''
lowercase__ = MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3" )
lowercase__ = model.to(_lowercase )
lowercase__ = MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3" )
lowercase__ = prepare_img()
lowercase__ = image_processor(images=_lowercase , return_tensors="pt" ).to(_lowercase )
# forward pass
with torch.no_grad():
lowercase__ = model(**_lowercase )
lowercase__ = outputs.logits
# verify the logits
lowercase__ = torch.Size((1, 21, 32, 32) )
self.assertEqual(logits.shape , _lowercase )
lowercase__ = 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=_lowercase , )
self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _lowercase , atol=1e-4 ) )
@slow
def UpperCAmelCase ( self :Union[str, Any] ):
'''simple docstring'''
lowercase__ = MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3" )
lowercase__ = model.to(_lowercase )
lowercase__ = MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3" )
lowercase__ = prepare_img()
lowercase__ = image_processor(images=_lowercase , return_tensors="pt" ).to(_lowercase )
# forward pass
with torch.no_grad():
lowercase__ = model(**_lowercase )
lowercase__ = outputs.logits.detach().cpu()
lowercase__ = image_processor.post_process_semantic_segmentation(outputs=_lowercase , target_sizes=[(50, 60)] )
lowercase__ = torch.Size((50, 60) )
self.assertEqual(segmentation[0].shape , _lowercase )
lowercase__ = image_processor.post_process_semantic_segmentation(outputs=_lowercase )
lowercase__ = torch.Size((32, 32) )
self.assertEqual(segmentation[0].shape , _lowercase )
| 655
|
from ....configuration_utils import PretrainedConfig
from ....utils import logging
_snake_case = logging.get_logger(__name__)
_snake_case = {
"""Visual-Attention-Network/van-base""": (
"""https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json"""
),
}
class lowerCAmelCase ( lowercase_ ):
__lowerCamelCase = 'van'
def __init__( self :Optional[Any] , _lowercase :Dict=2_24 , _lowercase :Union[str, Any]=3 , _lowercase :List[Any]=[7, 3, 3, 3] , _lowercase :Any=[4, 2, 2, 2] , _lowercase :Union[str, Any]=[64, 1_28, 3_20, 5_12] , _lowercase :List[Any]=[3, 3, 12, 3] , _lowercase :Dict=[8, 8, 4, 4] , _lowercase :int="gelu" , _lowercase :List[Any]=0.02 , _lowercase :List[Any]=1e-6 , _lowercase :Any=1e-2 , _lowercase :int=0.0 , _lowercase :int=0.0 , **_lowercase :Dict , ):
'''simple docstring'''
super().__init__(**_lowercase )
lowercase__ = image_size
lowercase__ = num_channels
lowercase__ = patch_sizes
lowercase__ = strides
lowercase__ = hidden_sizes
lowercase__ = depths
lowercase__ = mlp_ratios
lowercase__ = hidden_act
lowercase__ = initializer_range
lowercase__ = layer_norm_eps
lowercase__ = layer_scale_init_value
lowercase__ = drop_path_rate
lowercase__ = dropout_rate
| 655
| 1
|
import inspect
import unittest
class _snake_case ( unittest.TestCase ):
def lowerCAmelCase_ ( self ) -> List[Any]:
try:
import diffusers # noqa: F401
except ImportError:
assert False
def lowerCAmelCase_ ( self ) -> Any:
import diffusers
from diffusers.dependency_versions_table import deps
snake_case__ :int = inspect.getmembers(UpperCamelCase ,inspect.isclass )
for cls_name, cls_module in all_classes:
if "dummy_" in cls_module.__module__:
for backend in cls_module._backends:
if backend == "k_diffusion":
snake_case__ :Optional[Any] = "k-diffusion"
elif backend == "invisible_watermark":
snake_case__ :Union[str, Any] = "invisible-watermark"
assert backend in deps, f'{backend} is not in the deps table!'
| 57
|
def lowercase_ ( __snake_case : str ) -> list:
'''simple docstring'''
return [
txt[:a] + txt[a].upper() + txt[a + 1 :]
for a in range(len(__snake_case ) )
if txt[a].isalpha()
]
if __name__ == "__main__":
__import__("doctest").testmod()
| 57
| 1
|
"""simple docstring"""
from operator import delitem, getitem, setitem
import pytest
from data_structures.hashing.hash_map import HashMap
def _lowerCamelCase ( lowerCamelCase__ : Tuple ):
return getitem, k
def _lowerCamelCase ( lowerCamelCase__ : Any , lowerCamelCase__ : Union[str, Any] ):
return setitem, k, v
def _lowerCamelCase ( lowerCamelCase__ : List[Any] ):
return delitem, k
def _lowerCamelCase ( lowerCamelCase__ : Dict , lowerCamelCase__ : List[str] , *lowerCamelCase__ : Dict ):
try:
return fun(lowerCamelCase__ , *lowerCamelCase__ ), None
except Exception as e:
return None, e
__snake_case = (
_set('key_a', 'val_a'),
_set('key_b', 'val_b'),
)
__snake_case = [
_set('key_a', 'val_a'),
_set('key_a', 'val_b'),
]
__snake_case = [
_set('key_a', 'val_a'),
_set('key_b', 'val_b'),
_del('key_a'),
_del('key_b'),
_set('key_a', 'val_a'),
_del('key_a'),
]
__snake_case = [
_get('key_a'),
_del('key_a'),
_set('key_a', 'val_a'),
_del('key_a'),
_del('key_a'),
_get('key_a'),
]
__snake_case = [
*[_set(x, x) for x in range(5)], # guaranteed upsize
]
__snake_case = [
*[_set(x, x) for x in range(5)], # guaranteed upsize
*[_del(x) for x in range(5)],
_set('key_a', 'val_b'),
]
@pytest.mark.parametrize(
"""operations""" , (
pytest.param(_add_items , id="""add items""" ),
pytest.param(_overwrite_items , id="""overwrite items""" ),
pytest.param(_delete_items , id="""delete items""" ),
pytest.param(_access_absent_items , id="""access absent items""" ),
pytest.param(_add_with_resize_up , id="""add with resize up""" ),
pytest.param(_add_with_resize_down , id="""add with resize down""" ),
) , )
def _lowerCamelCase ( lowerCamelCase__ : Optional[Any] ):
lowercase__ : Optional[int] = HashMap(initial_block_size=4 )
lowercase__ : Tuple = {}
for _, (fun, *args) in enumerate(lowerCamelCase__ ):
lowercase__ : Union[str, Any] = _run_operation(lowerCamelCase__ , lowerCamelCase__ , *lowerCamelCase__ )
lowercase__ : Dict = _run_operation(lowerCamelCase__ , lowerCamelCase__ , *lowerCamelCase__ )
assert my_res == py_res
assert str(lowerCamelCase__ ) == str(lowerCamelCase__ )
assert set(lowerCamelCase__ ) == set(lowerCamelCase__ )
assert len(lowerCamelCase__ ) == len(lowerCamelCase__ )
assert set(my.items() ) == set(py.items() )
def _lowerCamelCase ( ):
def is_public(lowerCamelCase__ : Any ) -> bool:
return not name.startswith("""_""" )
lowercase__ : int = {name for name in dir({} ) if is_public(lowerCamelCase__ )}
lowercase__ : List[str] = {name for name in dir(HashMap() ) if is_public(lowerCamelCase__ )}
assert dict_public_names > hash_public_names
| 200
|
'''simple docstring'''
from __future__ import annotations
import unittest
from transformers import is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import numpy as np
import tensorflow as tf
from transformers import (
TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
FlaubertConfig,
TFFlaubertForMultipleChoice,
TFFlaubertForQuestionAnsweringSimple,
TFFlaubertForSequenceClassification,
TFFlaubertForTokenClassification,
TFFlaubertModel,
TFFlaubertWithLMHeadModel,
)
class __A :
def __init__( self , UpperCamelCase_ , ):
__UpperCAmelCase : Any = parent
__UpperCAmelCase : Dict = 13
__UpperCAmelCase : Tuple = 7
__UpperCAmelCase : List[Any] = True
__UpperCAmelCase : Tuple = True
__UpperCAmelCase : Optional[Any] = True
__UpperCAmelCase : Optional[Any] = True
__UpperCAmelCase : List[Any] = True
__UpperCAmelCase : Optional[int] = False
__UpperCAmelCase : Union[str, Any] = False
__UpperCAmelCase : List[Any] = False
__UpperCAmelCase : Union[str, Any] = 2
__UpperCAmelCase : Dict = 99
__UpperCAmelCase : Dict = 0
__UpperCAmelCase : List[Any] = 32
__UpperCAmelCase : Any = 2
__UpperCAmelCase : str = 4
__UpperCAmelCase : List[Any] = 0.1
__UpperCAmelCase : Optional[int] = 0.1
__UpperCAmelCase : Union[str, Any] = 5_12
__UpperCAmelCase : int = 16
__UpperCAmelCase : List[Any] = 2
__UpperCAmelCase : int = 0.0_2
__UpperCAmelCase : Optional[int] = 3
__UpperCAmelCase : List[str] = 4
__UpperCAmelCase : List[Any] = "last"
__UpperCAmelCase : List[str] = True
__UpperCAmelCase : str = None
__UpperCAmelCase : Any = 0
def _snake_case ( self ):
__UpperCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__UpperCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa )
__UpperCAmelCase : Union[str, Any] = None
if self.use_input_lengths:
__UpperCAmelCase : str = (
ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2
) # small variation of seq_length
__UpperCAmelCase : Dict = None
if self.use_token_type_ids:
__UpperCAmelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.n_langs )
__UpperCAmelCase : Union[str, Any] = None
__UpperCAmelCase : Any = None
__UpperCAmelCase : Tuple = None
if self.use_labels:
__UpperCAmelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__UpperCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__UpperCAmelCase : Union[str, Any] = ids_tensor([self.batch_size] , 2 , dtype=tf.floataa )
__UpperCAmelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices )
__UpperCAmelCase : str = FlaubertConfig(
vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , bos_token_id=self.bos_token_id , )
return (
config,
input_ids,
token_type_ids,
input_lengths,
sequence_labels,
token_labels,
is_impossible_labels,
choice_labels,
input_mask,
)
def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , ):
__UpperCAmelCase : Dict = TFFlaubertModel(config=UpperCamelCase_ )
__UpperCAmelCase : int = {"input_ids": input_ids, "lengths": input_lengths, "langs": token_type_ids}
__UpperCAmelCase : List[str] = model(UpperCamelCase_ )
__UpperCAmelCase : Union[str, Any] = [input_ids, input_mask]
__UpperCAmelCase : List[Any] = model(UpperCamelCase_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , ):
__UpperCAmelCase : Dict = TFFlaubertWithLMHeadModel(UpperCamelCase_ )
__UpperCAmelCase : Tuple = {"input_ids": input_ids, "lengths": input_lengths, "langs": token_type_ids}
__UpperCAmelCase : Dict = model(UpperCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , ):
__UpperCAmelCase : Union[str, Any] = TFFlaubertForQuestionAnsweringSimple(UpperCamelCase_ )
__UpperCAmelCase : str = {"input_ids": input_ids, "lengths": input_lengths}
__UpperCAmelCase : Tuple = model(UpperCamelCase_ )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , ):
__UpperCAmelCase : Tuple = TFFlaubertForSequenceClassification(UpperCamelCase_ )
__UpperCAmelCase : List[Any] = {"input_ids": input_ids, "lengths": input_lengths}
__UpperCAmelCase : str = model(UpperCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , ):
__UpperCAmelCase : Optional[int] = self.num_labels
__UpperCAmelCase : Dict = TFFlaubertForTokenClassification(config=UpperCamelCase_ )
__UpperCAmelCase : Union[str, Any] = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
__UpperCAmelCase : Tuple = model(UpperCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , ):
__UpperCAmelCase : Tuple = self.num_choices
__UpperCAmelCase : Optional[int] = TFFlaubertForMultipleChoice(config=UpperCamelCase_ )
__UpperCAmelCase : Tuple = tf.tile(tf.expand_dims(UpperCamelCase_ , 1 ) , (1, self.num_choices, 1) )
__UpperCAmelCase : Optional[int] = tf.tile(tf.expand_dims(UpperCamelCase_ , 1 ) , (1, self.num_choices, 1) )
__UpperCAmelCase : List[str] = tf.tile(tf.expand_dims(UpperCamelCase_ , 1 ) , (1, self.num_choices, 1) )
__UpperCAmelCase : Optional[Any] = {
"input_ids": multiple_choice_inputs_ids,
"attention_mask": multiple_choice_input_mask,
"token_type_ids": multiple_choice_token_type_ids,
}
__UpperCAmelCase : Tuple = model(UpperCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def _snake_case ( self ):
__UpperCAmelCase : int = self.prepare_config_and_inputs()
(
(
__UpperCAmelCase
) , (
__UpperCAmelCase
) , (
__UpperCAmelCase
) , (
__UpperCAmelCase
) , (
__UpperCAmelCase
) , (
__UpperCAmelCase
) , (
__UpperCAmelCase
) , (
__UpperCAmelCase
) , (
__UpperCAmelCase
) ,
) : Optional[int] = config_and_inputs
__UpperCAmelCase : str = {
"input_ids": input_ids,
"token_type_ids": token_type_ids,
"langs": token_type_ids,
"lengths": input_lengths,
}
return config, inputs_dict
@require_tf
class __A (__magic_name__ , __magic_name__ , unittest.TestCase ):
snake_case :List[str] = (
(
TFFlaubertModel,
TFFlaubertWithLMHeadModel,
TFFlaubertForSequenceClassification,
TFFlaubertForQuestionAnsweringSimple,
TFFlaubertForTokenClassification,
TFFlaubertForMultipleChoice,
)
if is_tf_available()
else ()
)
snake_case :List[str] = (
(TFFlaubertWithLMHeadModel,) if is_tf_available() else ()
) # TODO (PVP): Check other models whether language generation is also applicable
snake_case :Optional[Any] = (
{
"feature-extraction": TFFlaubertModel,
"fill-mask": TFFlaubertWithLMHeadModel,
"question-answering": TFFlaubertForQuestionAnsweringSimple,
"text-classification": TFFlaubertForSequenceClassification,
"token-classification": TFFlaubertForTokenClassification,
"zero-shot": TFFlaubertForSequenceClassification,
}
if is_tf_available()
else {}
)
snake_case :Tuple = False
snake_case :Any = False
def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ):
if (
pipeline_test_casse_name == "QAPipelineTests"
and tokenizer_name is not None
and not tokenizer_name.endswith("Fast" )
):
# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
return True
return False
def _snake_case ( self ):
__UpperCAmelCase : List[str] = TFFlaubertModelTester(self )
__UpperCAmelCase : Dict = ConfigTester(self , config_class=UpperCamelCase_ , emb_dim=37 )
def _snake_case ( self ):
self.config_tester.run_common_tests()
def _snake_case ( self ):
__UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_model(*UpperCamelCase_ )
def _snake_case ( self ):
__UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_lm_head(*UpperCamelCase_ )
def _snake_case ( self ):
__UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_qa(*UpperCamelCase_ )
def _snake_case ( self ):
__UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_sequence_classif(*UpperCamelCase_ )
def _snake_case ( self ):
__UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_for_token_classification(*UpperCamelCase_ )
def _snake_case ( self ):
__UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_for_multiple_choice(*UpperCamelCase_ )
@slow
def _snake_case ( self ):
for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__UpperCAmelCase : Tuple = TFFlaubertModel.from_pretrained(UpperCamelCase_ )
self.assertIsNotNone(UpperCamelCase_ )
@require_tf
@require_sentencepiece
@require_tokenizers
class __A (unittest.TestCase ):
@slow
def _snake_case ( self ):
__UpperCAmelCase : str = TFFlaubertModel.from_pretrained("jplu/tf-flaubert-small-cased" )
__UpperCAmelCase : Tuple = tf.convert_to_tensor(
[[0, 1_58, 7_35, 25_92, 14_24, 67_27, 82, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !"
__UpperCAmelCase : int = model(UpperCamelCase_ )[0]
__UpperCAmelCase : str = tf.TensorShape((1, 8, 5_12) )
self.assertEqual(output.shape , UpperCamelCase_ )
# compare the actual values for a slice.
__UpperCAmelCase : Tuple = tf.convert_to_tensor(
[
[
[-1.8_7_6_8_7_7_3, -1.5_6_6_5_5_5, 0.2_7_0_7_2_4_1_8],
[-1.6_9_2_0_0_3_8, -0.5_8_7_3_5_0_5, 1.9_3_2_9_5_9_9],
[-2.9_5_6_3_9_8_5, -1.6_9_9_3_8_3_5, 1.7_9_7_2_0_5_2],
]
] , dtype=tf.floataa , )
self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
| 168
| 0
|
'''simple docstring'''
lowercase : str = tuple[float, float, float]
lowercase : List[Any] = tuple[float, float, float]
def lowerCAmelCase_ ( snake_case__ , snake_case__ ):
'''simple docstring'''
A : Optional[Any] = end_pointa[0] - end_pointa[0]
A : Optional[Any] = end_pointa[1] - end_pointa[1]
A : Optional[Any] = end_pointa[2] - end_pointa[2]
return (x, y, z)
def lowerCAmelCase_ ( snake_case__ , snake_case__ ):
'''simple docstring'''
A : Optional[int] = ab[1] * ac[2] - ab[2] * ac[1] # *i
A : List[str] = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j
A : Optional[int] = ab[0] * ac[1] - ab[1] * ac[0] # *k
return (x, y, z)
def lowerCAmelCase_ ( snake_case__ , snake_case__ ):
'''simple docstring'''
return tuple(round(snake_case__ , snake_case__ ) for x in vector ) == (0, 0, 0)
def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ = 10 ):
'''simple docstring'''
A : Optional[Any] = create_vector(snake_case__ , snake_case__ )
A : Optional[Any] = create_vector(snake_case__ , snake_case__ )
return is_zero_vector(get_ad_vectors_cross(snake_case__ , snake_case__ ) , snake_case__ )
| 705
|
'''simple docstring'''
import math_equivalence # From: git+https://github.com/hendrycks/math.git
import datasets
lowercase : Tuple = '\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n'
lowercase : List[str] = '\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy.\n'
lowercase : Any = R'\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting "1/2" to "\\frac{1}{2}")\n\nExamples:\n >>> metric = datasets.load_metric("competition_math")\n >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"])\n >>> print(results)\n {\'accuracy\': 1.0}\n'
@datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class A ( datasets.Metric ):
def __lowerCAmelCase ( self ) -> Tuple:
"""simple docstring"""
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Value('''string''' ),
'''references''': datasets.Value('''string''' ),
} ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , )
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str:
"""simple docstring"""
A : int = 0.0
for i, j in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
n_correct += 1.0 if math_equivalence.is_equiv(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else 0.0
A : Tuple = n_correct / len(SCREAMING_SNAKE_CASE )
return {
"accuracy": accuracy,
}
| 343
| 0
|
'''simple docstring'''
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError
from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
sys.path.append(str(Path(__file__).parent.parent / 'utils'))
from test_module.custom_image_processing import CustomImageProcessor # noqa E402
snake_case_ : Tuple = get_tests_dir('fixtures')
class lowercase__ ( unittest.TestCase ):
'''simple docstring'''
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = mock.Mock()
UpperCamelCase = 5_0_0
UpperCamelCase = {}
UpperCamelCase = HTTPError
UpperCamelCase = {}
# Download this model to make sure it's in the cache.
UpperCamelCase = ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit''' )
# Under the mock environment we get a 500 error when trying to reach the model.
with mock.patch('''requests.Session.request''' , return_value=lowerCamelCase__ ) as mock_head:
UpperCamelCase = ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit''' )
# This check we did call the fake head request
mock_head.assert_called()
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = ViTImageProcessor.from_pretrained(
'''https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json''' )
def UpperCAmelCase ( self ):
'''simple docstring'''
with self.assertRaises(lowerCamelCase__ ):
# config is in subfolder, the following should not work without specifying the subfolder
UpperCamelCase = AutoImageProcessor.from_pretrained('''hf-internal-testing/stable-diffusion-all-variants''' )
UpperCamelCase = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/stable-diffusion-all-variants''' , subfolder='''feature_extractor''' )
self.assertIsNotNone(lowerCamelCase__ )
@is_staging_test
class lowercase__ ( unittest.TestCase ):
'''simple docstring'''
@classmethod
def UpperCAmelCase ( cls ):
'''simple docstring'''
UpperCamelCase = TOKEN
HfFolder.save_token(lowerCamelCase__ )
@classmethod
def UpperCAmelCase ( cls ):
'''simple docstring'''
try:
delete_repo(token=cls._token , repo_id='''test-image-processor''' )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id='''valid_org/test-image-processor-org''' )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id='''test-dynamic-image-processor''' )
except HTTPError:
pass
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = ViTImageProcessor.from_pretrained(lowerCamelCase__ )
image_processor.push_to_hub('''test-image-processor''' , use_auth_token=self._token )
UpperCamelCase = ViTImageProcessor.from_pretrained(f'{USER}/test-image-processor' )
for k, v in image_processor.__dict__.items():
self.assertEqual(lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) )
# Reset repo
delete_repo(token=self._token , repo_id='''test-image-processor''' )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(
lowerCamelCase__ , repo_id='''test-image-processor''' , push_to_hub=lowerCamelCase__ , use_auth_token=self._token )
UpperCamelCase = ViTImageProcessor.from_pretrained(f'{USER}/test-image-processor' )
for k, v in image_processor.__dict__.items():
self.assertEqual(lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = ViTImageProcessor.from_pretrained(lowerCamelCase__ )
image_processor.push_to_hub('''valid_org/test-image-processor''' , use_auth_token=self._token )
UpperCamelCase = ViTImageProcessor.from_pretrained('''valid_org/test-image-processor''' )
for k, v in image_processor.__dict__.items():
self.assertEqual(lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) )
# Reset repo
delete_repo(token=self._token , repo_id='''valid_org/test-image-processor''' )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(
lowerCamelCase__ , repo_id='''valid_org/test-image-processor-org''' , push_to_hub=lowerCamelCase__ , use_auth_token=self._token )
UpperCamelCase = ViTImageProcessor.from_pretrained('''valid_org/test-image-processor-org''' )
for k, v in image_processor.__dict__.items():
self.assertEqual(lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) )
def UpperCAmelCase ( self ):
'''simple docstring'''
CustomImageProcessor.register_for_auto_class()
UpperCamelCase = CustomImageProcessor.from_pretrained(lowerCamelCase__ )
image_processor.push_to_hub('''test-dynamic-image-processor''' , use_auth_token=self._token )
# This has added the proper auto_map field to the config
self.assertDictEqual(
image_processor.auto_map , {'''AutoImageProcessor''': '''custom_image_processing.CustomImageProcessor'''} , )
UpperCamelCase = AutoImageProcessor.from_pretrained(
f'{USER}/test-dynamic-image-processor' , trust_remote_code=lowerCamelCase__ )
# Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
self.assertEqual(new_image_processor.__class__.__name__ , '''CustomImageProcessor''' )
| 212
|
'''simple docstring'''
import warnings
from ...utils import logging
from .image_processing_imagegpt import ImageGPTImageProcessor
snake_case_ : List[str] = logging.get_logger(__name__)
class lowercase__ ( snake_case_ ):
'''simple docstring'''
def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ):
'''simple docstring'''
warnings.warn(
'''The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'''
''' Please use ImageGPTImageProcessor instead.''' , lowerCamelCase__ , )
super().__init__(*lowerCamelCase__ , **lowerCamelCase__ )
| 212
| 1
|
import os
from glob import glob
import imageio
import torch
import torchvision
import wandb
from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan
from loaders import load_vqgan
from PIL import Image
from torch import nn
from transformers import CLIPModel, CLIPTokenizerFast
from utils import get_device, get_timestamp, show_pil
class UpperCamelCase :
"""simple docstring"""
def __init__( self : int ,_SCREAMING_SNAKE_CASE : str = "cpu" ,_SCREAMING_SNAKE_CASE : str = "openai/clip-vit-large-patch14" ) -> None:
'''simple docstring'''
A = device
A = CLIPTokenizerFast.from_pretrained(_SCREAMING_SNAKE_CASE )
A = [0.48145466, 0.4578275, 0.40821073]
A = [0.26862954, 0.26130258, 0.27577711]
A = torchvision.transforms.Normalize(self.image_mean ,self.image_std )
A = torchvision.transforms.Resize(2_2_4 )
A = torchvision.transforms.CenterCrop(2_2_4 )
def A( self : Tuple ,_SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]:
'''simple docstring'''
A = self.resize(_SCREAMING_SNAKE_CASE )
A = self.center_crop(_SCREAMING_SNAKE_CASE )
A = self.normalize(_SCREAMING_SNAKE_CASE )
return images
def __call__( self : Any ,_SCREAMING_SNAKE_CASE : Dict=None ,_SCREAMING_SNAKE_CASE : Any=None ,**_SCREAMING_SNAKE_CASE : int ) -> Any:
'''simple docstring'''
A = self.tokenizer(text=_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE )
A = self.preprocess_img(_SCREAMING_SNAKE_CASE )
A = {key: value.to(self.device ) for (key, value) in encoding.items()}
return encoding
class UpperCamelCase ( nn.Module ):
"""simple docstring"""
def __init__( self : Any ,_SCREAMING_SNAKE_CASE : Optional[int]=1_0 ,_SCREAMING_SNAKE_CASE : Tuple=0.01 ,_SCREAMING_SNAKE_CASE : int=None ,_SCREAMING_SNAKE_CASE : Union[str, Any]=None ,_SCREAMING_SNAKE_CASE : Tuple=None ,_SCREAMING_SNAKE_CASE : int=None ,_SCREAMING_SNAKE_CASE : Optional[int]=None ,_SCREAMING_SNAKE_CASE : Tuple=None ,_SCREAMING_SNAKE_CASE : str=False ,_SCREAMING_SNAKE_CASE : Union[str, Any]=True ,_SCREAMING_SNAKE_CASE : Any="image" ,_SCREAMING_SNAKE_CASE : Optional[Any]=True ,_SCREAMING_SNAKE_CASE : Dict=False ,_SCREAMING_SNAKE_CASE : Dict=False ,_SCREAMING_SNAKE_CASE : List[str]=False ,) -> None:
'''simple docstring'''
super().__init__()
A = None
A = device if device else get_device()
if vqgan:
A = vqgan
else:
A = load_vqgan(self.device ,conf_path=_SCREAMING_SNAKE_CASE ,ckpt_path=_SCREAMING_SNAKE_CASE )
self.vqgan.eval()
if clip:
A = clip
else:
A = CLIPModel.from_pretrained('openai/clip-vit-base-patch32' )
self.clip.to(self.device )
A = ProcessorGradientFlow(device=self.device )
A = iterations
A = lr
A = log
A = make_grid
A = return_val
A = quantize
A = self.vqgan.decoder.z_shape
def A( self : str ,_SCREAMING_SNAKE_CASE : str=None ,_SCREAMING_SNAKE_CASE : Tuple=None ,_SCREAMING_SNAKE_CASE : Dict=5 ,_SCREAMING_SNAKE_CASE : str=True ) -> Union[str, Any]:
'''simple docstring'''
A = []
if output_path is None:
A = './animation.gif'
if input_path is None:
A = self.save_path
A = sorted(glob(input_path + '/*' ) )
if not len(_SCREAMING_SNAKE_CASE ):
raise ValueError(
'No images found in save path, aborting (did you pass save_intermediate=True to the generate'
' function?)' )
if len(_SCREAMING_SNAKE_CASE ) == 1:
print('Only one image found in save path, (did you pass save_intermediate=True to the generate function?)' )
A = total_duration / len(_SCREAMING_SNAKE_CASE )
A = [frame_duration] * len(_SCREAMING_SNAKE_CASE )
if extend_frames:
A = 1.5
A = 3
for file_name in paths:
if file_name.endswith('.png' ):
images.append(imageio.imread(_SCREAMING_SNAKE_CASE ) )
imageio.mimsave(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,duration=_SCREAMING_SNAKE_CASE )
print(f'gif saved to {output_path}' )
def A( self : Tuple ,_SCREAMING_SNAKE_CASE : List[str]=None ,_SCREAMING_SNAKE_CASE : int=None ) -> Optional[Any]:
'''simple docstring'''
if not (path or img):
raise ValueError('Input either path or tensor' )
if img is not None:
raise NotImplementedError
A = preprocess(Image.open(_SCREAMING_SNAKE_CASE ) ,target_image_size=2_5_6 ).to(self.device )
A = preprocess_vqgan(_SCREAMING_SNAKE_CASE )
A , *A = self.vqgan.encode(_SCREAMING_SNAKE_CASE )
return z
def A( self : List[str] ,_SCREAMING_SNAKE_CASE : List[str] ) -> int:
'''simple docstring'''
A = self.latent.detach().requires_grad_()
A = base_latent + transform_vector
if self.quantize:
A , *A = self.vqgan.quantize(_SCREAMING_SNAKE_CASE )
else:
A = trans_latent
return self.vqgan.decode(_SCREAMING_SNAKE_CASE )
def A( self : Any ,_SCREAMING_SNAKE_CASE : int ,_SCREAMING_SNAKE_CASE : int ,_SCREAMING_SNAKE_CASE : int=None ) -> int:
'''simple docstring'''
A = self.clip_preprocessor(text=_SCREAMING_SNAKE_CASE ,images=_SCREAMING_SNAKE_CASE ,return_tensors='pt' ,padding=_SCREAMING_SNAKE_CASE )
A = self.clip(**_SCREAMING_SNAKE_CASE )
A = clip_outputs.logits_per_image
if weights is not None:
A = similarity_logits * weights
return similarity_logits.sum()
def A( self : Tuple ,_SCREAMING_SNAKE_CASE : Tuple ,_SCREAMING_SNAKE_CASE : Optional[Any] ,_SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Optional[Any]:
'''simple docstring'''
A = self._get_clip_similarity(pos_prompts['prompts'] ,_SCREAMING_SNAKE_CASE ,weights=(1 / pos_prompts['weights']) )
if neg_prompts:
A = self._get_clip_similarity(neg_prompts['prompts'] ,_SCREAMING_SNAKE_CASE ,weights=neg_prompts['weights'] )
else:
A = torch.tensor([1] ,device=self.device )
A = -torch.log(_SCREAMING_SNAKE_CASE ) + torch.log(_SCREAMING_SNAKE_CASE )
return loss
def A( self : Dict ,_SCREAMING_SNAKE_CASE : List[str] ,_SCREAMING_SNAKE_CASE : Union[str, Any] ,_SCREAMING_SNAKE_CASE : Tuple ) -> Dict:
'''simple docstring'''
A = torch.randn_like(self.latent ,requires_grad=_SCREAMING_SNAKE_CASE ,device=self.device )
A = torch.optim.Adam([vector] ,lr=self.lr )
for i in range(self.iterations ):
optim.zero_grad()
A = self._add_vector(_SCREAMING_SNAKE_CASE )
A = loop_post_process(_SCREAMING_SNAKE_CASE )
A = self._get_CLIP_loss(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
print('CLIP loss' ,_SCREAMING_SNAKE_CASE )
if self.log:
wandb.log({'CLIP Loss': clip_loss} )
clip_loss.backward(retain_graph=_SCREAMING_SNAKE_CASE )
optim.step()
if self.return_val == "image":
yield custom_to_pil(transformed_img[0] )
else:
yield vector
def A( self : str ,_SCREAMING_SNAKE_CASE : str ,_SCREAMING_SNAKE_CASE : Optional[int] ,_SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]:
'''simple docstring'''
wandb.init(reinit=_SCREAMING_SNAKE_CASE ,project='face-editor' )
wandb.config.update({'Positive Prompts': positive_prompts} )
wandb.config.update({'Negative Prompts': negative_prompts} )
wandb.config.update({'lr': self.lr, 'iterations': self.iterations} )
if image_path:
A = Image.open(_SCREAMING_SNAKE_CASE )
A = image.resize((2_5_6, 2_5_6) )
wandb.log('Original Image' ,wandb.Image(_SCREAMING_SNAKE_CASE ) )
def A( self : List[str] ,_SCREAMING_SNAKE_CASE : Tuple ) -> Union[str, Any]:
'''simple docstring'''
if not prompts:
return []
A = []
A = []
if isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ):
A = [prompt.strip() for prompt in prompts.split('|' )]
for prompt in prompts:
if isinstance(_SCREAMING_SNAKE_CASE ,(tuple, list) ):
A = prompt[0]
A = float(prompt[1] )
elif ":" in prompt:
A , A = prompt.split(':' )
A = float(_SCREAMING_SNAKE_CASE )
else:
A = prompt
A = 1.0
processed_prompts.append(_SCREAMING_SNAKE_CASE )
weights.append(_SCREAMING_SNAKE_CASE )
return {
"prompts": processed_prompts,
"weights": torch.tensor(_SCREAMING_SNAKE_CASE ,device=self.device ),
}
def A( self : List[Any] ,_SCREAMING_SNAKE_CASE : Any ,_SCREAMING_SNAKE_CASE : List[Any]=None ,_SCREAMING_SNAKE_CASE : Any=None ,_SCREAMING_SNAKE_CASE : Dict=True ,_SCREAMING_SNAKE_CASE : List[str]=False ,_SCREAMING_SNAKE_CASE : Tuple=True ,_SCREAMING_SNAKE_CASE : Any=True ,_SCREAMING_SNAKE_CASE : Optional[Any]=None ,) -> Union[str, Any]:
'''simple docstring'''
if image_path:
A = self._get_latent(_SCREAMING_SNAKE_CASE )
else:
A = torch.randn(self.latent_dim ,device=self.device )
if self.log:
self._init_logging(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
assert pos_prompts, "You must provide at least one positive prompt."
A = self.process_prompts(_SCREAMING_SNAKE_CASE )
A = self.process_prompts(_SCREAMING_SNAKE_CASE )
if save_final and save_path is None:
A = os.path.join('./outputs/' ,'_'.join(pos_prompts['prompts'] ) )
if not os.path.exists(_SCREAMING_SNAKE_CASE ):
os.makedirs(_SCREAMING_SNAKE_CASE )
else:
A = save_path + '_' + get_timestamp()
os.makedirs(_SCREAMING_SNAKE_CASE )
A = save_path
A = self.vqgan.decode(self.latent )[0]
if show_intermediate:
print('Original Image' )
show_pil(custom_to_pil(_SCREAMING_SNAKE_CASE ) )
A = loop_post_process(_SCREAMING_SNAKE_CASE )
for iter, transformed_img in enumerate(self._optimize_CLIP(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) ):
if show_intermediate:
show_pil(_SCREAMING_SNAKE_CASE )
if save_intermediate:
transformed_img.save(os.path.join(self.save_path ,f'iter_{iter:03d}.png' ) )
if self.log:
wandb.log({'Image': wandb.Image(_SCREAMING_SNAKE_CASE )} )
if show_final:
show_pil(_SCREAMING_SNAKE_CASE )
if save_final:
transformed_img.save(os.path.join(self.save_path ,f'iter_{iter:03d}_final.png' ) )
| 701
|
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 UpperCamelCase ( snake_case__ ):
"""simple docstring"""
snake_case = ["image_processor", "tokenizer"]
snake_case = "LayoutLMv2ImageProcessor"
snake_case = ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast")
def __init__( self : List[str] ,_SCREAMING_SNAKE_CASE : List[str]=None ,_SCREAMING_SNAKE_CASE : Optional[int]=None ,**_SCREAMING_SNAKE_CASE : Tuple ) -> List[str]:
'''simple docstring'''
if "feature_extractor" in kwargs:
warnings.warn(
'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
' instead.' ,_SCREAMING_SNAKE_CASE ,)
A = kwargs.pop('feature_extractor' )
A = 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__(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
def __call__( self : Union[str, Any] ,_SCREAMING_SNAKE_CASE : Optional[int] ,_SCREAMING_SNAKE_CASE : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,_SCREAMING_SNAKE_CASE : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None ,_SCREAMING_SNAKE_CASE : Union[List[List[int]], List[List[List[int]]]] = None ,_SCREAMING_SNAKE_CASE : Optional[Union[List[int], List[List[int]]]] = None ,_SCREAMING_SNAKE_CASE : bool = True ,_SCREAMING_SNAKE_CASE : Union[bool, str, PaddingStrategy] = False ,_SCREAMING_SNAKE_CASE : Union[bool, str, TruncationStrategy] = None ,_SCREAMING_SNAKE_CASE : Optional[int] = None ,_SCREAMING_SNAKE_CASE : int = 0 ,_SCREAMING_SNAKE_CASE : Optional[int] = None ,_SCREAMING_SNAKE_CASE : Optional[bool] = None ,_SCREAMING_SNAKE_CASE : Optional[bool] = None ,_SCREAMING_SNAKE_CASE : bool = False ,_SCREAMING_SNAKE_CASE : bool = False ,_SCREAMING_SNAKE_CASE : bool = False ,_SCREAMING_SNAKE_CASE : bool = False ,_SCREAMING_SNAKE_CASE : bool = True ,_SCREAMING_SNAKE_CASE : Optional[Union[str, TensorType]] = None ,**_SCREAMING_SNAKE_CASE : Tuple ,) -> BatchEncoding:
'''simple docstring'''
# 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.' )
if return_overflowing_tokens is True and return_offsets_mapping is False:
raise ValueError('You cannot return overflowing tokens without returning the offsets mapping.' )
# first, apply the image processor
A = self.image_processor(images=_SCREAMING_SNAKE_CASE ,return_tensors=_SCREAMING_SNAKE_CASE )
# second, apply the tokenizer
if text is not None and self.image_processor.apply_ocr and text_pair is None:
if isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ):
A = [text] # add batch dimension (as the image processor always adds a batch dimension)
A = features['words']
A = 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=_SCREAMING_SNAKE_CASE ,add_special_tokens=_SCREAMING_SNAKE_CASE ,padding=_SCREAMING_SNAKE_CASE ,truncation=_SCREAMING_SNAKE_CASE ,max_length=_SCREAMING_SNAKE_CASE ,stride=_SCREAMING_SNAKE_CASE ,pad_to_multiple_of=_SCREAMING_SNAKE_CASE ,return_token_type_ids=_SCREAMING_SNAKE_CASE ,return_attention_mask=_SCREAMING_SNAKE_CASE ,return_overflowing_tokens=_SCREAMING_SNAKE_CASE ,return_special_tokens_mask=_SCREAMING_SNAKE_CASE ,return_offsets_mapping=_SCREAMING_SNAKE_CASE ,return_length=_SCREAMING_SNAKE_CASE ,verbose=_SCREAMING_SNAKE_CASE ,return_tensors=_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ,)
# add pixel values
A = features.pop('pixel_values' )
if return_overflowing_tokens is True:
A = self.get_overflowing_images(_SCREAMING_SNAKE_CASE ,encoded_inputs['overflow_to_sample_mapping'] )
A = images
return encoded_inputs
def A( self : Dict ,_SCREAMING_SNAKE_CASE : Optional[Any] ,_SCREAMING_SNAKE_CASE : Optional[Any] ) -> Dict:
'''simple docstring'''
# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
A = []
for sample_idx in overflow_to_sample_mapping:
images_with_overflow.append(images[sample_idx] )
if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ):
raise ValueError(
'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'
f' {len(_SCREAMING_SNAKE_CASE )} and {len(_SCREAMING_SNAKE_CASE )}' )
return images_with_overflow
def A( self : List[str] ,*_SCREAMING_SNAKE_CASE : str ,**_SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Tuple:
'''simple docstring'''
return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE )
def A( self : Dict ,*_SCREAMING_SNAKE_CASE : Tuple ,**_SCREAMING_SNAKE_CASE : int ) -> int:
'''simple docstring'''
return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE )
@property
def A( self : Any ) -> Union[str, Any]:
'''simple docstring'''
return ["input_ids", "bbox", "attention_mask", "image"]
@property
def A( self : Dict ) -> int:
'''simple docstring'''
warnings.warn(
'`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,_SCREAMING_SNAKE_CASE ,)
return self.image_processor_class
@property
def A( self : Optional[int] ) -> Union[str, Any]:
'''simple docstring'''
warnings.warn(
'`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,_SCREAMING_SNAKE_CASE ,)
return self.image_processor
| 110
| 0
|
'''simple docstring'''
def lowerCAmelCase_ ( _lowerCamelCase: int ):
__SCREAMING_SNAKE_CASE : Tuple = int(__a )
if n_element < 1:
__SCREAMING_SNAKE_CASE : int = ValueError("""a should be a positive number""" )
raise my_error
__SCREAMING_SNAKE_CASE : int = [1]
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = (0, 0, 0)
__SCREAMING_SNAKE_CASE : List[Any] = 1
while index < n_element:
while hamming_list[i] * 2 <= hamming_list[-1]:
i += 1
while hamming_list[j] * 3 <= hamming_list[-1]:
j += 1
while hamming_list[k] * 5 <= hamming_list[-1]:
k += 1
hamming_list.append(
min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) )
index += 1
return hamming_list
if __name__ == "__main__":
UpperCamelCase__ : int = input('''Enter the last number (nth term) of the Hamming Number Series: ''')
print('''Formula of Hamming Number Series => 2^i * 3^j * 5^k''')
UpperCamelCase__ : List[Any] = hamming(int(n))
print('''-----------------------------------------------------''')
print(f"The list with nth numbers is: {hamming_numbers}")
print('''-----------------------------------------------------''')
| 578
|
from itertools import product
def A(__a: int , __a: int ):
lowerCAmelCase_ = sides_number
lowerCAmelCase_ = max_face_number * dice_number
lowerCAmelCase_ = [0] * (max_total + 1)
lowerCAmelCase_ = 1
lowerCAmelCase_ = range(__a , max_face_number + 1 )
for dice_numbers in product(__a , repeat=__a ):
lowerCAmelCase_ = sum(__a )
totals_frequencies[total] += 1
return totals_frequencies
def A():
lowerCAmelCase_ = total_frequency_distribution(
sides_number=4 , dice_number=9 )
lowerCAmelCase_ = total_frequency_distribution(
sides_number=6 , dice_number=6 )
lowerCAmelCase_ = 0
lowerCAmelCase_ = 9
lowerCAmelCase_ = 4 * 9
lowerCAmelCase_ = 6
for peter_total in range(__a , max_peter_total + 1 ):
peter_wins_count += peter_totals_frequencies[peter_total] * sum(
colin_totals_frequencies[min_colin_total:peter_total] )
lowerCAmelCase_ = (4**9) * (6**6)
lowerCAmelCase_ = peter_wins_count / total_games_number
lowerCAmelCase_ = round(__a , ndigits=7 )
return rounded_peter_win_probability
if __name__ == "__main__":
print(F'''{solution() = }''')
| 122
| 0
|
import unittest
import torch
from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel
from diffusers.training_utils import set_seed
from diffusers.utils.testing_utils import slow
__UpperCamelCase : Optional[Any] = False
class lowercase__ ( unittest.TestCase):
def __A ( self : Optional[int] , UpperCamelCase__ : List[Any]=32 ):
'''simple docstring'''
set_seed(0 )
SCREAMING_SNAKE_CASE : Any = UNetaDModel(sample_size=UpperCamelCase__ , in_channels=3 , out_channels=3 )
SCREAMING_SNAKE_CASE : Tuple = torch.optim.SGD(model.parameters() , lr=0.0001 )
return model, optimizer
@slow
def __A ( self : Union[str, Any] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : List[str] = '''cpu''' # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable
SCREAMING_SNAKE_CASE : int = DDPMScheduler(
num_train_timesteps=1000 , beta_start=0.0001 , beta_end=0.02 , beta_schedule='''linear''' , clip_sample=UpperCamelCase__ , )
SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler(
num_train_timesteps=1000 , beta_start=0.0001 , beta_end=0.02 , beta_schedule='''linear''' , clip_sample=UpperCamelCase__ , )
assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps
# shared batches for DDPM and DDIM
set_seed(0 )
SCREAMING_SNAKE_CASE : List[Any] = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(UpperCamelCase__ ) for _ in range(4 )]
SCREAMING_SNAKE_CASE : int = [torch.randn((4, 3, 32, 32) ).to(UpperCamelCase__ ) for _ in range(4 )]
SCREAMING_SNAKE_CASE : Optional[Any] = [torch.randint(0 , 1000 , (4,) ).long().to(UpperCamelCase__ ) for _ in range(4 )]
# train with a DDPM scheduler
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_model_optimizer(resolution=32 )
model.train().to(UpperCamelCase__ )
for i in range(4 ):
optimizer.zero_grad()
SCREAMING_SNAKE_CASE : Union[str, Any] = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] )
SCREAMING_SNAKE_CASE : Tuple = model(UpperCamelCase__ , timesteps[i] ).sample
SCREAMING_SNAKE_CASE : str = torch.nn.functional.mse_loss(UpperCamelCase__ , noise[i] )
loss.backward()
optimizer.step()
del model, optimizer
# recreate the model and optimizer, and retry with DDIM
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_model_optimizer(resolution=32 )
model.train().to(UpperCamelCase__ )
for i in range(4 ):
optimizer.zero_grad()
SCREAMING_SNAKE_CASE : int = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] )
SCREAMING_SNAKE_CASE : Any = model(UpperCamelCase__ , timesteps[i] ).sample
SCREAMING_SNAKE_CASE : Dict = torch.nn.functional.mse_loss(UpperCamelCase__ , noise[i] )
loss.backward()
optimizer.step()
del model, optimizer
self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1E-5 ) )
self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1E-5 ) )
| 34
|
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__UpperCamelCase : Tuple = {
'configuration_maskformer': ['MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MaskFormerConfig'],
'configuration_maskformer_swin': ['MaskFormerSwinConfig'],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase : Optional[Any] = ['MaskFormerFeatureExtractor']
__UpperCamelCase : List[Any] = ['MaskFormerImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase : Optional[int] = [
'MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'MaskFormerForInstanceSegmentation',
'MaskFormerModel',
'MaskFormerPreTrainedModel',
]
__UpperCamelCase : Union[str, Any] = [
'MaskFormerSwinBackbone',
'MaskFormerSwinModel',
'MaskFormerSwinPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig
from .configuration_maskformer_swin import MaskFormerSwinConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_maskformer import MaskFormerFeatureExtractor
from .image_processing_maskformer import MaskFormerImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_maskformer import (
MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
MaskFormerForInstanceSegmentation,
MaskFormerModel,
MaskFormerPreTrainedModel,
)
from .modeling_maskformer_swin import (
MaskFormerSwinBackbone,
MaskFormerSwinModel,
MaskFormerSwinPreTrainedModel,
)
else:
import sys
__UpperCamelCase : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure)
| 34
| 1
|
'''simple docstring'''
class lowerCAmelCase__ :
'''simple docstring'''
def __init__( self : Any , a__ : List[str] , a__ : str ):
UpperCAmelCase = name
UpperCAmelCase = val
def __str__( self : Optional[Any] ):
return f"{self.__class__.__name__}({self.name}, {self.val})"
def __lt__( self : Union[str, Any] , a__ : Union[str, Any] ):
return self.val < other.val
class lowerCAmelCase__ :
'''simple docstring'''
def __init__( self : List[Any] , a__ : Union[str, Any] ):
UpperCAmelCase = {}
UpperCAmelCase = {}
UpperCAmelCase = self.build_heap(a__ )
def __getitem__( self : int , a__ : Any ):
return self.get_value(a__ )
def __snake_case ( self : List[Any] , a__ : Optional[Any] ):
return (idx - 1) // 2
def __snake_case ( self : str , a__ : Optional[int] ):
return idx * 2 + 1
def __snake_case ( self : Optional[int] , a__ : Dict ):
return idx * 2 + 2
def __snake_case ( self : int , a__ : Dict ):
return self.heap_dict[key]
def __snake_case ( self : List[Any] , a__ : Optional[Any] ):
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 __snake_case ( self : List[Any] , a__ : Optional[Any] , a__ : Optional[Any] ):
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 __snake_case ( self : Union[str, Any] , a__ : Optional[int] ):
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 __snake_case ( self : Optional[Any] ):
return self.heap[0]
def __snake_case ( self : List[str] ):
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 __snake_case ( self : Optional[Any] , a__ : Optional[Any] ):
self.heap.append(a__ )
UpperCAmelCase = len(self.heap ) - 1
UpperCAmelCase = node.val
self.sift_up(len(self.heap ) - 1 )
def __snake_case ( self : Tuple ):
return len(self.heap ) == 0
def __snake_case ( self : Any , a__ : List[Any] , a__ : int ):
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__ : List[Any] = Node('R', -1)
a__ : List[Any] = Node('B', 6)
a__ : Optional[Any] = Node('A', 3)
a__ : Any = Node('X', 1)
a__ : Any = Node('E', 4)
# Use one of these two ways to generate Min-Heap
# Generating Min-Heap from array
a__ : Dict = 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()
| 51
|
"""simple docstring"""
from collections.abc import Generator
def __UpperCAmelCase ( ):
"""simple docstring"""
_UpperCAmelCase , _UpperCAmelCase = 0, 1
while True:
_UpperCAmelCase , _UpperCAmelCase = b, a + b
yield b
def __UpperCAmelCase ( lowercase = 10_00 ):
"""simple docstring"""
_UpperCAmelCase = 1
_UpperCAmelCase = fibonacci_generator()
while len(str(next(lowercase ) ) ) < n:
answer += 1
return answer + 1
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
| 277
| 0
|
'''simple docstring'''
def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
assert x is not None
assert y is not None
SCREAMING_SNAKE_CASE_ :Any = len(SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ :Union[str, Any] = len(SCREAMING_SNAKE_CASE )
# declaring the array for storing the dp values
SCREAMING_SNAKE_CASE_ :List[str] = [[0] * (n + 1) for _ in range(m + 1 )] # noqa: E741
for i in range(1 , m + 1 ):
for j in range(1 , n + 1 ):
SCREAMING_SNAKE_CASE_ :Union[str, Any] = 1 if x[i - 1] == y[j - 1] else 0
SCREAMING_SNAKE_CASE_ :Optional[Any] = max(l[i - 1][j] , l[i][j - 1] , l[i - 1][j - 1] + match )
SCREAMING_SNAKE_CASE_ :Optional[Any] = ''
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :Any = m, n
while i > 0 and j > 0:
SCREAMING_SNAKE_CASE_ :List[str] = 1 if x[i - 1] == y[j - 1] else 0
if l[i][j] == l[i - 1][j - 1] + match:
if match == 1:
SCREAMING_SNAKE_CASE_ :Union[str, Any] = x[i - 1] + seq
i -= 1
j -= 1
elif l[i][j] == l[i - 1][j]:
i -= 1
else:
j -= 1
return l[m][n], seq
if __name__ == "__main__":
SCREAMING_SNAKE_CASE__ : Tuple = """AGGTAB"""
SCREAMING_SNAKE_CASE__ : Dict = """GXTXAYB"""
SCREAMING_SNAKE_CASE__ : int = 4
SCREAMING_SNAKE_CASE__ : Union[str, Any] = """GTAB"""
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = longest_common_subsequence(a, b)
print("""len =""", ln, """, sub-sequence =""", subseq)
import doctest
doctest.testmod()
| 233
|
'''simple docstring'''
from __future__ import annotations
def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE ): # This function is recursive
SCREAMING_SNAKE_CASE_ :Union[str, Any] = len(SCREAMING_SNAKE_CASE )
# If the array contains only one element, we return it (it's the stop condition of
# recursion)
if array_length <= 1:
return array
# Else
SCREAMING_SNAKE_CASE_ :Optional[int] = array[0]
SCREAMING_SNAKE_CASE_ :Union[str, Any] = False
SCREAMING_SNAKE_CASE_ :List[Any] = 1
SCREAMING_SNAKE_CASE_ :list[int] = []
while not is_found and i < array_length:
if array[i] < pivot:
SCREAMING_SNAKE_CASE_ :List[Any] = True
SCREAMING_SNAKE_CASE_ :int = [element for element in array[i:] if element >= array[i]]
SCREAMING_SNAKE_CASE_ :Optional[Any] = longest_subsequence(SCREAMING_SNAKE_CASE )
if len(SCREAMING_SNAKE_CASE ) > len(SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ :int = temp_array
else:
i += 1
SCREAMING_SNAKE_CASE_ :List[Any] = [element for element in array[1:] if element >= pivot]
SCREAMING_SNAKE_CASE_ :Optional[Any] = [pivot, *longest_subsequence(SCREAMING_SNAKE_CASE )]
if len(SCREAMING_SNAKE_CASE ) > len(SCREAMING_SNAKE_CASE ):
return temp_array
else:
return longest_subseq
if __name__ == "__main__":
import doctest
doctest.testmod()
| 233
| 1
|
'''simple docstring'''
def __a(SCREAMING_SNAKE_CASE_ : str ):
'''simple docstring'''
_lowerCAmelCase = 0
_lowerCAmelCase = len(_SCREAMING_SNAKE_CASE )
for i in range(n - 1 ):
for j in range(i + 1 , _SCREAMING_SNAKE_CASE ):
if arr[i] > arr[j]:
num_inversions += 1
return num_inversions
def __a(SCREAMING_SNAKE_CASE_ : Any ):
'''simple docstring'''
if len(_SCREAMING_SNAKE_CASE ) <= 1:
return arr, 0
_lowerCAmelCase = len(_SCREAMING_SNAKE_CASE ) // 2
_lowerCAmelCase = arr[0:mid]
_lowerCAmelCase = arr[mid:]
_lowerCAmelCase , _lowerCAmelCase = count_inversions_recursive(_SCREAMING_SNAKE_CASE )
_lowerCAmelCase , _lowerCAmelCase = count_inversions_recursive(_SCREAMING_SNAKE_CASE )
_lowerCAmelCase , _lowerCAmelCase = _count_cross_inversions(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
_lowerCAmelCase = inversion_p + inversions_q + cross_inversions
return c, num_inversions
def __a(SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] ):
'''simple docstring'''
_lowerCAmelCase = []
_lowerCAmelCase = _lowerCAmelCase = _lowerCAmelCase = 0
while i < len(_SCREAMING_SNAKE_CASE ) and j < len(_SCREAMING_SNAKE_CASE ):
if p[i] > q[j]:
# if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P)
# These are all inversions. The claim emerges from the
# property that P is sorted.
num_inversion += len(_SCREAMING_SNAKE_CASE ) - i
r.append(q[j] )
j += 1
else:
r.append(p[i] )
i += 1
if i < len(_SCREAMING_SNAKE_CASE ):
r.extend(p[i:] )
else:
r.extend(q[j:] )
return r, num_inversion
def __a():
'''simple docstring'''
_lowerCAmelCase = [10, 2, 1, 5, 5, 2, 11]
# this arr has 8 inversions:
# (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2)
_lowerCAmelCase = count_inversions_bf(_SCREAMING_SNAKE_CASE )
_lowerCAmelCase , _lowerCAmelCase = count_inversions_recursive(_SCREAMING_SNAKE_CASE )
assert num_inversions_bf == num_inversions_recursive == 8
print("number of inversions = " , _SCREAMING_SNAKE_CASE )
# testing an array with zero inversion (a sorted arr_1)
arr_a.sort()
_lowerCAmelCase = count_inversions_bf(_SCREAMING_SNAKE_CASE )
_lowerCAmelCase , _lowerCAmelCase = count_inversions_recursive(_SCREAMING_SNAKE_CASE )
assert num_inversions_bf == num_inversions_recursive == 0
print("number of inversions = " , _SCREAMING_SNAKE_CASE )
# an empty list should also have zero inversions
_lowerCAmelCase = []
_lowerCAmelCase = count_inversions_bf(_SCREAMING_SNAKE_CASE )
_lowerCAmelCase , _lowerCAmelCase = count_inversions_recursive(_SCREAMING_SNAKE_CASE )
assert num_inversions_bf == num_inversions_recursive == 0
print("number of inversions = " , _SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
main()
| 18
|
import numpy as np
def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> np.array:
"""simple docstring"""
return (2 / (1 + np.exp(-2 * vector ))) - 1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 27
| 0
|
'''simple docstring'''
import importlib.metadata
import warnings
from copy import deepcopy
from packaging import version
from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available
if is_bitsandbytes_available():
import bitsandbytes as bnb
import torch
import torch.nn as nn
from ..pytorch_utils import ConvaD
if is_accelerate_available():
from accelerate import init_empty_weights
from accelerate.utils import find_tied_parameters
__snake_case = logging.get_logger(__name__)
def a ( __a , __a , __a , __a=None , __a=None ) -> str:
'''simple docstring'''
if "." in tensor_name:
UpperCamelCase__ :List[Any] = tensor_name.split('''.''' )
for split in splits[:-1]:
UpperCamelCase__ :int = getattr(__a , __a )
if new_module is None:
raise ValueError(f'''{module} has no attribute {split}.''' )
UpperCamelCase__ :List[Any] = new_module
UpperCamelCase__ :Union[str, Any] = splits[-1]
if tensor_name not in module._parameters and tensor_name not in module._buffers:
raise ValueError(f'''{module} does not have a parameter or a buffer named {tensor_name}.''' )
UpperCamelCase__ :str = tensor_name in module._buffers
UpperCamelCase__ :int = getattr(__a , __a )
if old_value.device == torch.device('''meta''' ) and device not in ["meta", torch.device('''meta''' )] and value is None:
raise ValueError(f'''{tensor_name} is on the meta device, we need a `value` to put in on {device}.''' )
UpperCamelCase__ :Optional[int] = False
UpperCamelCase__ :str = False
if is_buffer or not is_bitsandbytes_available():
UpperCamelCase__ :Union[str, Any] = False
UpperCamelCase__ :Any = False
else:
UpperCamelCase__ :int = hasattr(bnb.nn , '''Params4bit''' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit )
UpperCamelCase__ :Dict = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams )
if is_abit or is_abit:
UpperCamelCase__ :Optional[Any] = module._parameters[tensor_name]
if param.device.type != "cuda":
if value is None:
UpperCamelCase__ :List[str] = old_value.to(__a )
elif isinstance(__a , torch.Tensor ):
UpperCamelCase__ :Union[str, Any] = value.to('''cpu''' )
if value.dtype == torch.inta:
UpperCamelCase__ :Dict = version.parse(importlib.metadata.version('''bitsandbytes''' ) ) > version.parse(
'''0.37.2''' )
if not is_abit_serializable:
raise ValueError(
'''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. '''
'''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.''' )
else:
UpperCamelCase__ :Dict = torch.tensor(__a , device='''cpu''' )
# Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
# Since weights are saved in the correct "orientation", we skip transposing when loading.
if issubclass(module.source_cls , __a ) and fpaa_statistics is None:
UpperCamelCase__ :Any = new_value.T
UpperCamelCase__ :Tuple = old_value.__dict__
if is_abit:
UpperCamelCase__ :List[Any] = bnb.nn.IntaParams(__a , requires_grad=__a , **__a ).to(__a )
elif is_abit:
UpperCamelCase__ :int = bnb.nn.Paramsabit(__a , requires_grad=__a , **__a ).to(__a )
UpperCamelCase__ :int = new_value
if fpaa_statistics is not None:
setattr(module.weight , '''SCB''' , fpaa_statistics.to(__a ) )
else:
if value is None:
UpperCamelCase__ :Dict = old_value.to(__a )
elif isinstance(__a , torch.Tensor ):
UpperCamelCase__ :Union[str, Any] = value.to(__a )
else:
UpperCamelCase__ :Optional[int] = torch.tensor(__a , device=__a )
if is_buffer:
UpperCamelCase__ :str = new_value
else:
UpperCamelCase__ :List[Any] = nn.Parameter(__a , requires_grad=old_value.requires_grad )
UpperCamelCase__ :Optional[int] = new_value
def a ( __a , __a=None , __a=None , __a=None , __a=False ) -> int:
'''simple docstring'''
for name, module in model.named_children():
if current_key_name is None:
UpperCamelCase__ :Dict = []
current_key_name.append(__a )
if (isinstance(__a , nn.Linear ) or isinstance(__a , __a )) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
if not any(key in '''.'''.join(__a ) for key in modules_to_not_convert ):
with init_empty_weights():
if isinstance(__a , __a ):
UpperCamelCase__ :Tuple = module.weight.shape
else:
UpperCamelCase__ :str = module.in_features
UpperCamelCase__ :int = module.out_features
if quantization_config.quantization_method() == "llm_int8":
UpperCamelCase__ :str = bnb.nn.LinearabitLt(
__a , __a , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , )
UpperCamelCase__ :List[str] = True
else:
if (
quantization_config.llm_inta_skip_modules is not None
and name in quantization_config.llm_inta_skip_modules
):
pass
else:
UpperCamelCase__ :Union[str, Any] = bnb.nn.Linearabit(
__a , __a , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , )
UpperCamelCase__ :int = True
# Store the module class in case we need to transpose the weight later
UpperCamelCase__ :int = type(__a )
# Force requires grad to False to avoid unexpected errors
model._modules[name].requires_grad_(__a )
if len(list(module.children() ) ) > 0:
UpperCamelCase__ :Union[str, Any] = _replace_with_bnb_linear(
__a , __a , __a , __a , has_been_replaced=__a , )
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def a ( __a , __a=None , __a=None , __a=None ) -> Any:
'''simple docstring'''
UpperCamelCase__ :Any = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
UpperCamelCase__ :int = _replace_with_bnb_linear(
__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.'''
''' Please double check your model architecture, or submit an issue on github if you think this is'''
''' a bug.''' )
return model
def a ( *__a , **__a ) -> int:
'''simple docstring'''
warnings.warn(
'''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' , __a , )
return replace_with_bnb_linear(*__a , **__a )
def a ( *__a , **__a ) -> Dict:
'''simple docstring'''
warnings.warn(
'''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' , __a , )
return set_module_quantized_tensor_to_device(*__a , **__a )
def a ( __a ) -> Optional[Any]:
'''simple docstring'''
UpperCamelCase__ :int = deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
tied_model.tie_weights()
UpperCamelCase__ :Any = find_tied_parameters(__a )
# For compatibility with Accelerate < 0.18
if isinstance(__a , __a ):
UpperCamelCase__ :List[Any] = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
UpperCamelCase__ :Optional[int] = sum(__a , [] )
UpperCamelCase__ :Optional[int] = len(__a ) > 0
# Check if it is a base model
UpperCamelCase__ :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
UpperCamelCase__ :Tuple = list(model.named_children() )
UpperCamelCase__ :Dict = [list_modules[-1][0]]
# add last module together with tied weights
UpperCamelCase__ :List[str] = set(__a ) - set(__a )
UpperCamelCase__ :Dict = list(set(__a ) ) + list(__a )
# remove ".weight" from the keys
UpperCamelCase__ :List[Any] = ['''.weight''', '''.bias''']
UpperCamelCase__ :int = []
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
UpperCamelCase__ :List[str] = name.replace(__a , '''''' )
filtered_module_names.append(__a )
return filtered_module_names
| 713
|
'''simple docstring'''
import qiskit
def a ( __a , __a ) -> qiskit.result.counts.Counts:
'''simple docstring'''
UpperCamelCase__ :int = qiskit.Aer.get_backend('''aer_simulator''' )
# Create a Quantum Circuit acting on the q register
UpperCamelCase__ :Any = qiskit.QuantumCircuit(__a , __a )
# Map the quantum measurement to the classical bits
circuit.measure([0] , [0] )
# Execute the circuit on the simulator
UpperCamelCase__ :Optional[int] = qiskit.execute(__a , __a , shots=1000 )
# Return the histogram data of the results of the experiment.
return job.result().get_counts(__a )
if __name__ == "__main__":
print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
| 280
| 0
|
"""simple docstring"""
import time
from contextlib import contextmanager
from pathlib import Path
import pytest
import requests
from huggingface_hub.hf_api import HfApi, HfFolder
A = """__DUMMY_TRANSFORMERS_USER__"""
A = """Dummy User"""
A = """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"""
A = """https://hub-ci.huggingface.co"""
A = CI_HUB_ENDPOINT + """/datasets/{repo_id}/resolve/{revision}/{path}"""
A = CI_HUB_ENDPOINT + """/{repo_id}/resolve/{revision}/{filename}"""
A = Path("""~/.huggingface/hub_ci_token""").expanduser()
@pytest.fixture
def _UpperCamelCase ( UpperCamelCase ) -> Optional[Any]:
"""simple docstring"""
monkeypatch.setattr(
"huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE" , UpperCamelCase )
@pytest.fixture
def _UpperCamelCase ( UpperCamelCase ) -> Any:
"""simple docstring"""
monkeypatch.setattr("datasets.config.HF_ENDPOINT" , UpperCamelCase )
monkeypatch.setattr("datasets.config.HUB_DATASETS_URL" , UpperCamelCase )
@pytest.fixture
def _UpperCamelCase ( UpperCamelCase ) -> List[Any]:
"""simple docstring"""
monkeypatch.setattr("huggingface_hub.hf_api.HfFolder.path_token" , UpperCamelCase )
@pytest.fixture
def _UpperCamelCase ( UpperCamelCase , UpperCamelCase ) -> Union[str, Any]:
"""simple docstring"""
HfFolder.save_token(UpperCamelCase )
yield
HfFolder.delete_token()
@pytest.fixture(scope="session" )
def _UpperCamelCase ( ) -> Tuple:
"""simple docstring"""
return HfApi(endpoint=UpperCamelCase )
@pytest.fixture(scope="session" )
def _UpperCamelCase ( UpperCamelCase ) -> Tuple:
"""simple docstring"""
__UpperCAmelCase : int = HfFolder.get_token()
HfFolder.save_token(UpperCamelCase )
yield CI_HUB_USER_TOKEN
if previous_token is not None:
HfFolder.save_token(UpperCamelCase )
@pytest.fixture
def _UpperCamelCase ( UpperCamelCase ) -> Union[str, Any]:
"""simple docstring"""
def _cleanup_repo(UpperCamelCase ):
hf_api.delete_repo(UpperCamelCase , token=UpperCamelCase , repo_type="dataset" )
return _cleanup_repo
@pytest.fixture
def _UpperCamelCase ( UpperCamelCase ) -> Dict:
"""simple docstring"""
@contextmanager
def _temporary_repo(UpperCamelCase ):
try:
yield repo_id
finally:
cleanup_repo(UpperCamelCase )
return _temporary_repo
@pytest.fixture(scope="session" )
def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> int:
"""simple docstring"""
__UpperCAmelCase : str = f"repo_txt_data-{int(time.time() * 1_0e3 )}"
__UpperCAmelCase : List[Any] = f"{CI_HUB_USER}/{repo_name}"
hf_api.create_repo(UpperCamelCase , token=UpperCamelCase , repo_type="dataset" , private=UpperCamelCase )
hf_api.upload_file(
token=UpperCamelCase , path_or_fileobj=str(UpperCamelCase ) , path_in_repo="data/text_data.txt" , repo_id=UpperCamelCase , repo_type="dataset" , )
yield repo_id
try:
hf_api.delete_repo(UpperCamelCase , token=UpperCamelCase , repo_type="dataset" )
except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error
pass
@pytest.fixture()
def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Union[str, Any]:
"""simple docstring"""
return hf_private_dataset_repo_txt_data_
@pytest.fixture(scope="session" )
def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Optional[int]:
"""simple docstring"""
__UpperCAmelCase : Dict = f"repo_zipped_txt_data-{int(time.time() * 1_0e3 )}"
__UpperCAmelCase : Dict = f"{CI_HUB_USER}/{repo_name}"
hf_api.create_repo(UpperCamelCase , token=UpperCamelCase , repo_type="dataset" , private=UpperCamelCase )
hf_api.upload_file(
token=UpperCamelCase , path_or_fileobj=str(UpperCamelCase ) , path_in_repo="data.zip" , repo_id=UpperCamelCase , repo_type="dataset" , )
yield repo_id
try:
hf_api.delete_repo(UpperCamelCase , token=UpperCamelCase , repo_type="dataset" )
except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error
pass
@pytest.fixture()
def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Optional[Any]:
"""simple docstring"""
return hf_private_dataset_repo_zipped_txt_data_
@pytest.fixture(scope="session" )
def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Union[str, Any]:
"""simple docstring"""
__UpperCAmelCase : Any = f"repo_zipped_img_data-{int(time.time() * 1_0e3 )}"
__UpperCAmelCase : List[Any] = f"{CI_HUB_USER}/{repo_name}"
hf_api.create_repo(UpperCamelCase , token=UpperCamelCase , repo_type="dataset" , private=UpperCamelCase )
hf_api.upload_file(
token=UpperCamelCase , path_or_fileobj=str(UpperCamelCase ) , path_in_repo="data.zip" , repo_id=UpperCamelCase , repo_type="dataset" , )
yield repo_id
try:
hf_api.delete_repo(UpperCamelCase , token=UpperCamelCase , repo_type="dataset" )
except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error
pass
@pytest.fixture()
def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Any:
"""simple docstring"""
return hf_private_dataset_repo_zipped_img_data_
| 77
|
"""simple docstring"""
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.models import Sequential
if __name__ == "__main__":
A = pd.read_csv("""sample_data.csv""", header=None)
A = df.shape[:1][0]
# If you're using some other dataset input the target column
A = df.iloc[:, 1:2]
A = actual_data.values.reshape(len_data, 1)
A = MinMaxScaler().fit_transform(actual_data)
A = 10
A = 5
A = 20
A = len_data - periods * look_back
A = actual_data[:division]
A = actual_data[division - look_back :]
A , A = [], []
A , A = [], []
for i in range(0, len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
A = np.array(train_x)
A = np.array(test_x)
A = np.array([list(i.ravel()) for i in train_y])
A = np.array([list(i.ravel()) for i in test_y])
A = Sequential()
model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True))
model.add(LSTM(64, input_shape=(128, 1)))
model.add(Dense(forward_days))
model.compile(loss="""mean_squared_error""", optimizer="""adam""")
A = model.fit(
x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4
)
A = model.predict(x_test)
| 77
| 1
|
from __future__ import annotations
def lowercase ( __magic_name__ ):
'''simple docstring'''
if not nums:
raise ValueError("List is empty" )
return sum(__magic_name__ ) / len(__magic_name__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 706
|
'''simple docstring'''
from argparse import ArgumentParser
from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline
from ..utils import logging
from . import BaseTransformersCLICommand
a : Any = logging.get_logger(__name__) # pylint: disable=invalid-name
def lowercase ( __magic_name__ ):
'''simple docstring'''
if not path:
return "pipe"
for ext in PipelineDataFormat.SUPPORTED_FORMATS:
if path.endswith(__magic_name__ ):
return ext
raise Exception(
F"Unable to determine file format from file extension {path}. "
F"Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}" )
def lowercase ( __magic_name__ ):
'''simple docstring'''
UpperCAmelCase : Dict = pipeline(
task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , )
UpperCAmelCase : Any = try_infer_format_from_ext(args.input ) if args.format == "infer" else args.format
UpperCAmelCase : Tuple = PipelineDataFormat.from_str(
format=__magic_name__ , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , )
return RunCommand(__magic_name__ , __magic_name__ )
class UpperCamelCase__ ( lowercase__ ):
"""simple docstring"""
def __init__( self , snake_case , snake_case ):
'''simple docstring'''
UpperCAmelCase : Dict = nlp
UpperCAmelCase : str = reader
@staticmethod
def A_ ( snake_case ):
'''simple docstring'''
UpperCAmelCase : str = parser.add_parser("run" , help="Run a pipeline through the CLI" )
run_parser.add_argument("--task" , choices=get_supported_tasks() , help="Task to run" )
run_parser.add_argument("--input" , type=snake_case , help="Path to the file to use for inference" )
run_parser.add_argument("--output" , type=snake_case , help="Path to the file that will be used post to write results." )
run_parser.add_argument("--model" , type=snake_case , help="Name or path to the model to instantiate." )
run_parser.add_argument("--config" , type=snake_case , help="Name or path to the model's config to instantiate." )
run_parser.add_argument(
"--tokenizer" , type=snake_case , help="Name of the tokenizer to use. (default: same as the model name)" )
run_parser.add_argument(
"--column" , type=snake_case , help="Name of the column to use as input. (For multi columns input as QA use column1,columns2)" , )
run_parser.add_argument(
"--format" , type=snake_case , default="infer" , choices=PipelineDataFormat.SUPPORTED_FORMATS , help="Input format to read from" , )
run_parser.add_argument(
"--device" , type=snake_case , default=-1 , help="Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)" , )
run_parser.add_argument("--overwrite" , action="store_true" , help="Allow overwriting the output file." )
run_parser.set_defaults(func=snake_case )
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase , UpperCAmelCase : Union[str, Any] = self._nlp, []
for entry in self._reader:
UpperCAmelCase : Dict = nlp(**snake_case ) if self._reader.is_multi_columns else nlp(snake_case )
if isinstance(snake_case , snake_case ):
outputs.append(snake_case )
else:
outputs += output
# Saving data
if self._nlp.binary_output:
UpperCAmelCase : str = self._reader.save_binary(snake_case )
logger.warning(f"Current pipeline requires output to be in binary format, saving at {binary_path}" )
else:
self._reader.save(snake_case )
| 609
| 0
|
from typing import Dict, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends
if is_vision_available():
import PIL
# soft dependency
if is_pytesseract_available():
import pytesseract
UpperCAmelCase__ = logging.get_logger(__name__)
def _a ( a :Union[str, Any] , a :Union[str, Any] , a :Dict ) -> Tuple:
return [
int(1_000 * (box[0] / width) ),
int(1_000 * (box[1] / height) ),
int(1_000 * (box[2] / width) ),
int(1_000 * (box[3] / height) ),
]
def _a ( a :np.ndarray , a :Optional[str] , a :Optional[str] = None ) -> Optional[Any]:
a = tesseract_config if tesseract_config is not None else ''''''
# apply OCR
a = to_pil_image(SCREAMING_SNAKE_CASE__ )
a = pil_image.size
a = pytesseract.image_to_data(SCREAMING_SNAKE_CASE__ , lang=SCREAMING_SNAKE_CASE__ , output_type='''dict''' , config=SCREAMING_SNAKE_CASE__ )
a = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height''']
# filter empty words and corresponding coordinates
a = [idx for idx, word in enumerate(SCREAMING_SNAKE_CASE__ ) if not word.strip()]
a = [word for idx, word in enumerate(SCREAMING_SNAKE_CASE__ ) if idx not in irrelevant_indices]
a = [coord for idx, coord in enumerate(SCREAMING_SNAKE_CASE__ ) if idx not in irrelevant_indices]
a = [coord for idx, coord in enumerate(SCREAMING_SNAKE_CASE__ ) if idx not in irrelevant_indices]
a = [coord for idx, coord in enumerate(SCREAMING_SNAKE_CASE__ ) if idx not in irrelevant_indices]
a = [coord for idx, coord in enumerate(SCREAMING_SNAKE_CASE__ ) if idx not in irrelevant_indices]
# turn coordinates into (left, top, left+width, top+height) format
a = []
for x, y, w, h in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
a = [x, y, x + w, y + h]
actual_boxes.append(SCREAMING_SNAKE_CASE__ )
# finally, normalize the bounding boxes
a = []
for box in actual_boxes:
normalized_boxes.append(normalize_box(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ), "Not as many words as there are bounding boxes"
return words, normalized_boxes
class lowercase_ ( lowercase ):
'''simple docstring'''
__snake_case = ['pixel_values']
def __init__( self : List[Any] , __UpperCAmelCase : int = True , __UpperCAmelCase : Optional[Any] = None , __UpperCAmelCase : int = PILImageResampling.BILINEAR , __UpperCAmelCase : Optional[Any] = True , __UpperCAmelCase : Any = None , __UpperCAmelCase : List[str] = "" , **__UpperCAmelCase : List[Any] , ) ->None:
"""simple docstring"""
super().__init__(**SCREAMING_SNAKE_CASE_ )
a = size if size is not None else {'''height''': 224, '''width''': 224}
a = get_size_dict(SCREAMING_SNAKE_CASE_ )
a = do_resize
a = size
a = resample
a = apply_ocr
a = ocr_lang
a = tesseract_config
def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : Any , __UpperCAmelCase : Dict , __UpperCAmelCase : List[Any] = PILImageResampling.BILINEAR , __UpperCAmelCase : List[str] = None , **__UpperCAmelCase : List[str] , ) ->np.ndarray:
"""simple docstring"""
a = get_size_dict(SCREAMING_SNAKE_CASE_ )
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()}""" )
a = (size['''height'''], size['''width'''])
return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
def __lowerCAmelCase ( self : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : str = None , __UpperCAmelCase : Optional[Any] = None , __UpperCAmelCase : Any = None , __UpperCAmelCase : List[str] = None , __UpperCAmelCase : Tuple = None , __UpperCAmelCase : List[str] = None , __UpperCAmelCase : List[Any] = None , __UpperCAmelCase : Optional[int] = ChannelDimension.FIRST , **__UpperCAmelCase : Tuple , ) ->PIL.Image.Image:
"""simple docstring"""
a = do_resize if do_resize is not None else self.do_resize
a = size if size is not None else self.size
a = get_size_dict(SCREAMING_SNAKE_CASE_ )
a = resample if resample is not None else self.resample
a = apply_ocr if apply_ocr is not None else self.apply_ocr
a = ocr_lang if ocr_lang is not None else self.ocr_lang
a = tesseract_config if tesseract_config is not None else self.tesseract_config
a = make_list_of_images(SCREAMING_SNAKE_CASE_ )
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.''' )
if do_resize and size is None:
raise ValueError('''Size must be specified if do_resize is True.''' )
# All transformations expect numpy arrays.
a = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images]
if apply_ocr:
requires_backends(self , '''pytesseract''' )
a = []
a = []
for image in images:
a = apply_tesseract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
words_batch.append(SCREAMING_SNAKE_CASE_ )
boxes_batch.append(SCREAMING_SNAKE_CASE_ )
if do_resize:
a = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images]
# flip color channels from RGB to BGR (as Detectron2 requires this)
a = [flip_channel_order(SCREAMING_SNAKE_CASE_ ) for image in images]
a = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images]
a = BatchFeature(data={'''pixel_values''': images} , tensor_type=SCREAMING_SNAKE_CASE_ )
if apply_ocr:
a = words_batch
a = boxes_batch
return data
| 117
|
def _A ( SCREAMING_SNAKE_CASE__ : int ):
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError('''check_bouncy() accepts only integer arguments''' )
UpperCamelCase :int = str(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Optional[Any] = ''''''.join(sorted(SCREAMING_SNAKE_CASE__ ) )
return sorted_str_n != str_n and sorted_str_n[::-1] != str_n
def _A ( SCREAMING_SNAKE_CASE__ : float = 99 ):
if not 0 < percent < 100:
raise ValueError('''solution() only accepts values from 0 to 100''' )
UpperCamelCase :Tuple = 0
UpperCamelCase :str = 1
while True:
if check_bouncy(SCREAMING_SNAKE_CASE__ ):
bouncy_num += 1
if (bouncy_num / num) * 100 >= percent:
return num
num += 1
if __name__ == "__main__":
from doctest import testmod
testmod()
print(f'''{solution(99)}''')
| 658
| 0
|
'''simple docstring'''
import shutil
import tempfile
import unittest
import numpy as np
from transformers.testing_utils import (
is_pt_tf_cross_test,
require_tf,
require_torch,
require_torchvision,
require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import AutoProcessor, SamImageProcessor, SamProcessor
if is_torch_available():
import torch
if is_tf_available():
import tensorflow as tf
@require_vision
@require_torchvision
class lowerCamelCase_ ( unittest.TestCase ):
def lowercase_ ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase__ : Tuple = tempfile.mkdtemp()
UpperCAmelCase__ : List[str] = SamImageProcessor()
UpperCAmelCase__ : Dict = SamProcessor(_A )
processor.save_pretrained(self.tmpdirname )
def lowercase_ ( self : str , **_A : List[str] ):
'''simple docstring'''
return AutoProcessor.from_pretrained(self.tmpdirname , **_A ).image_processor
def lowercase_ ( self : Any ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def lowercase_ ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase__ : Any = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
UpperCAmelCase__ : Dict = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def lowercase_ ( self : int ):
'''simple docstring'''
UpperCAmelCase__ : Any = SamProcessor(image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
UpperCAmelCase__ : Union[str, Any] = self.get_image_processor(do_normalize=_A , padding_value=1.0 )
UpperCAmelCase__ : str = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_A , padding_value=1.0 )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _A )
def lowercase_ ( self : Any ):
'''simple docstring'''
UpperCAmelCase__ : Optional[int] = self.get_image_processor()
UpperCAmelCase__ : int = SamProcessor(image_processor=_A )
UpperCAmelCase__ : Optional[Any] = self.prepare_image_inputs()
UpperCAmelCase__ : Dict = image_processor(_A , return_tensors='''np''' )
UpperCAmelCase__ : List[str] = processor(images=_A , return_tensors='''np''' )
input_feat_extract.pop('''original_sizes''' ) # pop original_sizes as it is popped in the processor
input_feat_extract.pop('''reshaped_input_sizes''' ) # pop original_sizes as it is popped in the processor
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 )
@require_torch
def lowercase_ ( self : List[Any] ):
'''simple docstring'''
UpperCAmelCase__ : Dict = self.get_image_processor()
UpperCAmelCase__ : Any = SamProcessor(image_processor=_A )
UpperCAmelCase__ : Optional[Any] = [torch.ones((1, 3, 5, 5) )]
UpperCAmelCase__ : str = [[1_764, 2_646]]
UpperCAmelCase__ : Optional[int] = [[683, 1_024]]
UpperCAmelCase__ : int = processor.post_process_masks(_A , _A , _A )
self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) )
UpperCAmelCase__ : List[Any] = processor.post_process_masks(
_A , torch.tensor(_A ) , torch.tensor(_A ) )
self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) )
# should also work with np
UpperCAmelCase__ : Any = [np.ones((1, 3, 5, 5) )]
UpperCAmelCase__ : Any = processor.post_process_masks(_A , np.array(_A ) , np.array(_A ) )
self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) )
UpperCAmelCase__ : List[str] = [[1, 0], [0, 1]]
with self.assertRaises(_A ):
UpperCAmelCase__ : Tuple = processor.post_process_masks(_A , np.array(_A ) , np.array(_A ) )
@require_vision
@require_tf
class lowerCamelCase_ ( unittest.TestCase ):
def lowercase_ ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase__ : Any = tempfile.mkdtemp()
UpperCAmelCase__ : List[str] = SamImageProcessor()
UpperCAmelCase__ : Optional[Any] = SamProcessor(_A )
processor.save_pretrained(self.tmpdirname )
def lowercase_ ( self : Optional[Any] , **_A : List[str] ):
'''simple docstring'''
return AutoProcessor.from_pretrained(self.tmpdirname , **_A ).image_processor
def lowercase_ ( self : List[str] ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def lowercase_ ( self : List[str] ):
'''simple docstring'''
UpperCAmelCase__ : Dict = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
UpperCAmelCase__ : Optional[Any] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def lowercase_ ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
UpperCAmelCase__ : Optional[Any] = self.get_image_processor(do_normalize=_A , padding_value=1.0 )
UpperCAmelCase__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_A , padding_value=1.0 )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _A )
def lowercase_ ( self : int ):
'''simple docstring'''
UpperCAmelCase__ : Optional[int] = self.get_image_processor()
UpperCAmelCase__ : Dict = SamProcessor(image_processor=_A )
UpperCAmelCase__ : Optional[int] = self.prepare_image_inputs()
UpperCAmelCase__ : Optional[int] = image_processor(_A , return_tensors='''np''' )
UpperCAmelCase__ : Union[str, Any] = processor(images=_A , return_tensors='''np''' )
input_feat_extract.pop('''original_sizes''' ) # pop original_sizes as it is popped in the processor
input_feat_extract.pop('''reshaped_input_sizes''' ) # pop reshaped_input_sizes as it is popped in the processor
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 )
@require_tf
def lowercase_ ( self : Any ):
'''simple docstring'''
UpperCAmelCase__ : Dict = self.get_image_processor()
UpperCAmelCase__ : List[Any] = SamProcessor(image_processor=_A )
UpperCAmelCase__ : Optional[int] = [tf.ones((1, 3, 5, 5) )]
UpperCAmelCase__ : List[str] = [[1_764, 2_646]]
UpperCAmelCase__ : Tuple = [[683, 1_024]]
UpperCAmelCase__ : Tuple = processor.post_process_masks(_A , _A , _A , return_tensors='''tf''' )
self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) )
UpperCAmelCase__ : Union[str, Any] = processor.post_process_masks(
_A , tf.convert_to_tensor(_A ) , tf.convert_to_tensor(_A ) , return_tensors='''tf''' , )
self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) )
# should also work with np
UpperCAmelCase__ : Union[str, Any] = [np.ones((1, 3, 5, 5) )]
UpperCAmelCase__ : Optional[Any] = processor.post_process_masks(
_A , np.array(_A ) , np.array(_A ) , return_tensors='''tf''' )
self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) )
UpperCAmelCase__ : str = [[1, 0], [0, 1]]
with self.assertRaises(tf.errors.InvalidArgumentError ):
UpperCAmelCase__ : Optional[int] = processor.post_process_masks(
_A , np.array(_A ) , np.array(_A ) , return_tensors='''tf''' )
@require_vision
@require_torchvision
class lowerCamelCase_ ( unittest.TestCase ):
def lowercase_ ( self : List[Any] ):
'''simple docstring'''
UpperCAmelCase__ : List[str] = tempfile.mkdtemp()
UpperCAmelCase__ : Optional[Any] = SamImageProcessor()
UpperCAmelCase__ : str = SamProcessor(_A )
processor.save_pretrained(self.tmpdirname )
def lowercase_ ( self : Optional[Any] , **_A : List[Any] ):
'''simple docstring'''
return AutoProcessor.from_pretrained(self.tmpdirname , **_A ).image_processor
def lowercase_ ( self : List[str] ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def lowercase_ ( self : str ):
'''simple docstring'''
UpperCAmelCase__ : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
UpperCAmelCase__ : Optional[Any] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs]
return image_inputs
@is_pt_tf_cross_test
def lowercase_ ( self : int ):
'''simple docstring'''
UpperCAmelCase__ : Union[str, Any] = self.get_image_processor()
UpperCAmelCase__ : List[Any] = SamProcessor(image_processor=_A )
UpperCAmelCase__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa )
UpperCAmelCase__ : str = [tf.convert_to_tensor(_A )]
UpperCAmelCase__ : Optional[Any] = [torch.tensor(_A )]
UpperCAmelCase__ : Optional[Any] = [[1_764, 2_646]]
UpperCAmelCase__ : Optional[Any] = [[683, 1_024]]
UpperCAmelCase__ : List[str] = processor.post_process_masks(
_A , _A , _A , return_tensors='''tf''' )
UpperCAmelCase__ : str = processor.post_process_masks(
_A , _A , _A , return_tensors='''pt''' )
self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) )
@is_pt_tf_cross_test
def lowercase_ ( self : int ):
'''simple docstring'''
UpperCAmelCase__ : Optional[Any] = self.get_image_processor()
UpperCAmelCase__ : Optional[int] = SamProcessor(image_processor=_A )
UpperCAmelCase__ : List[Any] = self.prepare_image_inputs()
UpperCAmelCase__ : List[Any] = image_processor(_A , return_tensors='''pt''' )['''pixel_values'''].numpy()
UpperCAmelCase__ : Dict = processor(images=_A , return_tensors='''pt''' )['''pixel_values'''].numpy()
UpperCAmelCase__ : str = image_processor(_A , return_tensors='''tf''' )['''pixel_values'''].numpy()
UpperCAmelCase__ : int = processor(images=_A , return_tensors='''tf''' )['''pixel_values'''].numpy()
self.assertTrue(np.allclose(_A , _A ) )
self.assertTrue(np.allclose(_A , _A ) )
self.assertTrue(np.allclose(_A , _A ) )
| 312
|
'''simple docstring'''
def a__ ( lowerCAmelCase__ ) -> bool:
UpperCAmelCase__ : List[Any] = n ** (1 / 3)
return (val * val * val) == n
if __name__ == "__main__":
print(perfect_cube(2_7))
print(perfect_cube(4))
| 312
| 1
|
import argparse
import os
from . import (
ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
BART_PRETRAINED_MODEL_ARCHIVE_LIST,
BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP,
DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP,
FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP,
ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
T5_PRETRAINED_CONFIG_ARCHIVE_MAP,
TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,
XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
AlbertConfig,
BartConfig,
BertConfig,
CamembertConfig,
CTRLConfig,
DistilBertConfig,
DPRConfig,
ElectraConfig,
FlaubertConfig,
GPTaConfig,
LayoutLMConfig,
LxmertConfig,
OpenAIGPTConfig,
RobertaConfig,
TaConfig,
TFAlbertForPreTraining,
TFBartForConditionalGeneration,
TFBartForSequenceClassification,
TFBertForPreTraining,
TFBertForQuestionAnswering,
TFBertForSequenceClassification,
TFCamembertForMaskedLM,
TFCTRLLMHeadModel,
TFDistilBertForMaskedLM,
TFDistilBertForQuestionAnswering,
TFDPRContextEncoder,
TFDPRQuestionEncoder,
TFDPRReader,
TFElectraForPreTraining,
TFFlaubertWithLMHeadModel,
TFGPTaLMHeadModel,
TFLayoutLMForMaskedLM,
TFLxmertForPreTraining,
TFLxmertVisualFeatureEncoder,
TFOpenAIGPTLMHeadModel,
TFRobertaForCausalLM,
TFRobertaForMaskedLM,
TFRobertaForSequenceClassification,
TFTaForConditionalGeneration,
TFTransfoXLLMHeadModel,
TFWavaVecaModel,
TFXLMRobertaForMaskedLM,
TFXLMWithLMHeadModel,
TFXLNetLMHeadModel,
TransfoXLConfig,
WavaVecaConfig,
WavaVecaModel,
XLMConfig,
XLMRobertaConfig,
XLNetConfig,
is_torch_available,
load_pytorch_checkpoint_in_tfa_model,
)
from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging
if is_torch_available():
import numpy as np
import torch
from . import (
AlbertForPreTraining,
BartForConditionalGeneration,
BertForPreTraining,
BertForQuestionAnswering,
BertForSequenceClassification,
CamembertForMaskedLM,
CTRLLMHeadModel,
DistilBertForMaskedLM,
DistilBertForQuestionAnswering,
DPRContextEncoder,
DPRQuestionEncoder,
DPRReader,
ElectraForPreTraining,
FlaubertWithLMHeadModel,
GPTaLMHeadModel,
LayoutLMForMaskedLM,
LxmertForPreTraining,
LxmertVisualFeatureEncoder,
OpenAIGPTLMHeadModel,
RobertaForMaskedLM,
RobertaForSequenceClassification,
TaForConditionalGeneration,
TransfoXLLMHeadModel,
XLMRobertaForMaskedLM,
XLMWithLMHeadModel,
XLNetLMHeadModel,
)
logging.set_verbosity_info()
snake_case__ : int = {
"""bart""": (
BartConfig,
TFBartForConditionalGeneration,
TFBartForSequenceClassification,
BartForConditionalGeneration,
BART_PRETRAINED_MODEL_ARCHIVE_LIST,
),
"""bert""": (
BertConfig,
TFBertForPreTraining,
BertForPreTraining,
BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""bert-large-uncased-whole-word-masking-finetuned-squad""": (
BertConfig,
TFBertForQuestionAnswering,
BertForQuestionAnswering,
BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""bert-large-cased-whole-word-masking-finetuned-squad""": (
BertConfig,
TFBertForQuestionAnswering,
BertForQuestionAnswering,
BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""bert-base-cased-finetuned-mrpc""": (
BertConfig,
TFBertForSequenceClassification,
BertForSequenceClassification,
BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""dpr""": (
DPRConfig,
TFDPRQuestionEncoder,
TFDPRContextEncoder,
TFDPRReader,
DPRQuestionEncoder,
DPRContextEncoder,
DPRReader,
DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
),
"""gpt2""": (
GPTaConfig,
TFGPTaLMHeadModel,
GPTaLMHeadModel,
GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""xlnet""": (
XLNetConfig,
TFXLNetLMHeadModel,
XLNetLMHeadModel,
XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""xlm""": (
XLMConfig,
TFXLMWithLMHeadModel,
XLMWithLMHeadModel,
XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""xlm-roberta""": (
XLMRobertaConfig,
TFXLMRobertaForMaskedLM,
XLMRobertaForMaskedLM,
XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""transfo-xl""": (
TransfoXLConfig,
TFTransfoXLLMHeadModel,
TransfoXLLMHeadModel,
TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""openai-gpt""": (
OpenAIGPTConfig,
TFOpenAIGPTLMHeadModel,
OpenAIGPTLMHeadModel,
OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""roberta""": (
RobertaConfig,
TFRobertaForCausalLM,
TFRobertaForMaskedLM,
RobertaForMaskedLM,
ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""layoutlm""": (
LayoutLMConfig,
TFLayoutLMForMaskedLM,
LayoutLMForMaskedLM,
LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
),
"""roberta-large-mnli""": (
RobertaConfig,
TFRobertaForSequenceClassification,
RobertaForSequenceClassification,
ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""camembert""": (
CamembertConfig,
TFCamembertForMaskedLM,
CamembertForMaskedLM,
CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""flaubert""": (
FlaubertConfig,
TFFlaubertWithLMHeadModel,
FlaubertWithLMHeadModel,
FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""distilbert""": (
DistilBertConfig,
TFDistilBertForMaskedLM,
DistilBertForMaskedLM,
DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""distilbert-base-distilled-squad""": (
DistilBertConfig,
TFDistilBertForQuestionAnswering,
DistilBertForQuestionAnswering,
DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""lxmert""": (
LxmertConfig,
TFLxmertForPreTraining,
LxmertForPreTraining,
LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""lxmert-visual-feature-encoder""": (
LxmertConfig,
TFLxmertVisualFeatureEncoder,
LxmertVisualFeatureEncoder,
LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""ctrl""": (
CTRLConfig,
TFCTRLLMHeadModel,
CTRLLMHeadModel,
CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""albert""": (
AlbertConfig,
TFAlbertForPreTraining,
AlbertForPreTraining,
ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""t5""": (
TaConfig,
TFTaForConditionalGeneration,
TaForConditionalGeneration,
T5_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""electra""": (
ElectraConfig,
TFElectraForPreTraining,
ElectraForPreTraining,
ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
"""wav2vec2""": (
WavaVecaConfig,
TFWavaVecaModel,
WavaVecaModel,
WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
),
}
def snake_case_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True ):
if model_type not in MODEL_CLASSES:
raise ValueError(F"""Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.""" )
__lowercase , __lowercase , __lowercase , __lowercase = MODEL_CLASSES[model_type]
# Initialise TF model
if config_file in aws_config_map:
__lowercase = cached_file(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , force_download=not use_cached_models )
__lowercase = config_class.from_json_file(_SCREAMING_SNAKE_CASE )
__lowercase = True
__lowercase = True
print(F"""Building TensorFlow model from configuration: {config}""" )
__lowercase = model_class(_SCREAMING_SNAKE_CASE )
# Load weights from tf checkpoint
if pytorch_checkpoint_path in aws_config_map.keys():
__lowercase = cached_file(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , force_download=not use_cached_models )
# Load PyTorch checkpoint in tf2 model:
__lowercase = load_pytorch_checkpoint_in_tfa_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if compare_with_pt_model:
__lowercase = tf_model(tf_model.dummy_inputs , training=_SCREAMING_SNAKE_CASE ) # build the network
__lowercase = torch.load(_SCREAMING_SNAKE_CASE , map_location="cpu" )
__lowercase = pt_model_class.from_pretrained(
pretrained_model_name_or_path=_SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE , state_dict=_SCREAMING_SNAKE_CASE )
with torch.no_grad():
__lowercase = pt_model(**pt_model.dummy_inputs )
__lowercase = pto[0].numpy()
__lowercase = tfo[0].numpy()
__lowercase = np.amax(np.abs(np_pt - np_tf ) )
print(F"""Max absolute difference between models outputs {diff}""" )
assert diff <= 2E-2, F"""Error, model absolute difference is >2e-2: {diff}"""
# Save pytorch-model
print(F"""Save TensorFlow model to {tf_dump_path}""" )
tf_model.save_weights(_SCREAMING_SNAKE_CASE , save_format="h5" )
def snake_case_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , ):
if args_model_type is None:
__lowercase = list(MODEL_CLASSES.keys() )
else:
__lowercase = [args_model_type]
for j, model_type in enumerate(_SCREAMING_SNAKE_CASE , start=1 ):
print("=" * 1_0_0 )
print(F""" Converting model type {j}/{len(_SCREAMING_SNAKE_CASE )}: {model_type}""" )
print("=" * 1_0_0 )
if model_type not in MODEL_CLASSES:
raise ValueError(F"""Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.""" )
__lowercase , __lowercase , __lowercase , __lowercase , __lowercase = MODEL_CLASSES[model_type]
if model_shortcut_names_or_path is None:
__lowercase = list(aws_model_maps.keys() )
if config_shortcut_names_or_path is None:
__lowercase = model_shortcut_names_or_path
for i, (model_shortcut_name, config_shortcut_name) in enumerate(
zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , start=1 ):
print("-" * 1_0_0 )
if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name:
if not only_convert_finetuned_models:
print(F""" Skipping finetuned checkpoint {model_shortcut_name}""" )
continue
__lowercase = model_shortcut_name
elif only_convert_finetuned_models:
print(F""" Skipping not finetuned checkpoint {model_shortcut_name}""" )
continue
print(
F""" Converting checkpoint {i}/{len(_SCREAMING_SNAKE_CASE )}: {model_shortcut_name} - model_type {model_type}""" )
print("-" * 1_0_0 )
if config_shortcut_name in aws_config_map:
__lowercase = cached_file(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , force_download=not use_cached_models )
else:
__lowercase = config_shortcut_name
if model_shortcut_name in aws_model_maps:
__lowercase = cached_file(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , force_download=not use_cached_models )
else:
__lowercase = model_shortcut_name
if os.path.isfile(_SCREAMING_SNAKE_CASE ):
__lowercase = "converted_model"
convert_pt_checkpoint_to_tf(
model_type=_SCREAMING_SNAKE_CASE , pytorch_checkpoint_path=_SCREAMING_SNAKE_CASE , config_file=_SCREAMING_SNAKE_CASE , tf_dump_path=os.path.join(_SCREAMING_SNAKE_CASE , model_shortcut_name + "-tf_model.h5" ) , compare_with_pt_model=_SCREAMING_SNAKE_CASE , )
if remove_cached_files:
os.remove(_SCREAMING_SNAKE_CASE )
os.remove(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
snake_case__ : Optional[int] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--tf_dump_path""", default=None, type=str, required=True, help="""Path to the output Tensorflow dump file."""
)
parser.add_argument(
"""--model_type""",
default=None,
type=str,
help=(
F'''Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and '''
"""convert all the models from AWS."""
),
)
parser.add_argument(
"""--pytorch_checkpoint_path""",
default=None,
type=str,
help=(
"""Path to the PyTorch checkpoint path or shortcut name to download from AWS. """
"""If not given, will download and convert all the checkpoints from AWS."""
),
)
parser.add_argument(
"""--config_file""",
default=None,
type=str,
help=(
"""The config json file corresponding to the pre-trained model. \n"""
"""This specifies the model architecture. If not given and """
"""--pytorch_checkpoint_path is not given or is a shortcut name """
"""use the configuration associated to the shortcut name on the AWS"""
),
)
parser.add_argument(
"""--compare_with_pt_model""", action="""store_true""", help="""Compare Tensorflow and PyTorch model predictions."""
)
parser.add_argument(
"""--use_cached_models""",
action="""store_true""",
help="""Use cached models if possible instead of updating to latest checkpoint versions.""",
)
parser.add_argument(
"""--remove_cached_files""",
action="""store_true""",
help="""Remove pytorch models after conversion (save memory when converting in batches).""",
)
parser.add_argument("""--only_convert_finetuned_models""", action="""store_true""", help="""Only convert finetuned models.""")
snake_case__ : Dict = parser.parse_args()
# if args.pytorch_checkpoint_path is not None:
# convert_pt_checkpoint_to_tf(args.model_type.lower(),
# args.pytorch_checkpoint_path,
# args.config_file if args.config_file is not None else args.pytorch_checkpoint_path,
# args.tf_dump_path,
# compare_with_pt_model=args.compare_with_pt_model,
# use_cached_models=args.use_cached_models)
# else:
convert_all_pt_checkpoints_to_tf(
args.model_type.lower() if args.model_type is not None else None,
args.tf_dump_path,
model_shortcut_names_or_path=[args.pytorch_checkpoint_path]
if args.pytorch_checkpoint_path is not None
else None,
config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None,
compare_with_pt_model=args.compare_with_pt_model,
use_cached_models=args.use_cached_models,
remove_cached_files=args.remove_cached_files,
only_convert_finetuned_models=args.only_convert_finetuned_models,
)
| 402
|
from typing import TYPE_CHECKING
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
snake_case__ : List[Any] = {"""configuration_van""": ["""VAN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VanConfig"""]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case__ : Union[str, Any] = [
"""VAN_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""VanForImageClassification""",
"""VanModel""",
"""VanPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_van import (
VAN_PRETRAINED_MODEL_ARCHIVE_LIST,
VanForImageClassification,
VanModel,
VanPreTrainedModel,
)
else:
import sys
snake_case__ : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
| 402
| 1
|
# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
# and https://github.com/hojonathanho/diffusion
import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.schedulers.scheduling_utils import SchedulerMixin
from diffusers.utils import BaseOutput, deprecate
@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
class lowerCAmelCase_ ( __snake_case ):
_UpperCamelCase : torch.FloatTensor
_UpperCamelCase : Optional[torch.FloatTensor] = None
def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0.999 , SCREAMING_SNAKE_CASE="cosine" , ) -> Union[str, Any]:
if alpha_transform_type == "cosine":
def alpha_bar_fn(SCREAMING_SNAKE_CASE ):
return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2
elif alpha_transform_type == "exp":
def alpha_bar_fn(SCREAMING_SNAKE_CASE ):
return math.exp(t * -12.0 )
else:
raise ValueError(F"""Unsupported alpha_tranform_type: {alpha_transform_type}""" )
_lowercase : Optional[int] = []
for i in range(SCREAMING_SNAKE_CASE ):
_lowercase : Tuple = i / num_diffusion_timesteps
_lowercase : str = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar_fn(SCREAMING_SNAKE_CASE ) / alpha_bar_fn(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) )
return torch.tensor(SCREAMING_SNAKE_CASE , dtype=torch.floataa )
class lowerCAmelCase_ ( __snake_case , __snake_case ):
_UpperCamelCase : Optional[int] = 1
@register_to_config
def __init__( self , _lowerCAmelCase = 1_0_0_0 , _lowerCAmelCase = 0.00_01 , _lowerCAmelCase = 0.02 , _lowerCAmelCase = "linear" , _lowerCAmelCase = None , _lowerCAmelCase = True , _lowerCAmelCase = True , _lowerCAmelCase = 0 , _lowerCAmelCase = "epsilon" , _lowerCAmelCase = 1.0 , **_lowerCAmelCase , ):
if kwargs.get('set_alpha_to_one' , _lowerCAmelCase ) is not None:
_lowercase : Tuple = (
'The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.'
)
deprecate('set_alpha_to_one' , '1.0.0' , _lowerCAmelCase , standard_warn=_lowerCAmelCase )
_lowercase : Optional[int] = kwargs['set_alpha_to_one']
if trained_betas is not None:
_lowercase : List[Any] = torch.tensor(_lowerCAmelCase , dtype=torch.floataa )
elif beta_schedule == "linear":
_lowercase : int = torch.linspace(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , dtype=torch.floataa )
elif beta_schedule == "scaled_linear":
# this schedule is very specific to the latent diffusion model.
_lowercase : Tuple = (
torch.linspace(beta_start**0.5 , beta_end**0.5 , _lowerCAmelCase , dtype=torch.floataa ) ** 2
)
elif beta_schedule == "squaredcos_cap_v2":
# Glide cosine schedule
_lowercase : Union[str, Any] = betas_for_alpha_bar(_lowerCAmelCase )
else:
raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}""" )
_lowercase : Optional[int] = 1.0 - self.betas
_lowercase : List[str] = torch.cumprod(self.alphas , dim=0 )
# At every step in inverted ddim, we are looking into the next alphas_cumprod
# For the final step, there is no next alphas_cumprod, and the index is out of bounds
# `set_alpha_to_zero` decides whether we set this parameter simply to zero
# in this case, self.step() just output the predicted noise
# or whether we use the final alpha of the "non-previous" one.
_lowercase : Tuple = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1]
# standard deviation of the initial noise distribution
_lowercase : Optional[int] = 1.0
# setable values
_lowercase : str = None
_lowercase : str = torch.from_numpy(np.arange(0 , _lowerCAmelCase ).copy().astype(np.intaa ) )
def __a ( self , _lowerCAmelCase , _lowerCAmelCase = None ):
return sample
def __a ( self , _lowerCAmelCase , _lowerCAmelCase = None ):
if num_inference_steps > self.config.num_train_timesteps:
raise ValueError(
F"""`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"""
F""" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"""
F""" maximal {self.config.num_train_timesteps} timesteps.""" )
_lowercase : Optional[Any] = num_inference_steps
_lowercase : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
_lowercase : str = (np.arange(0 , _lowerCAmelCase ) * step_ratio).round().copy().astype(np.intaa )
_lowercase : Optional[Any] = torch.from_numpy(_lowerCAmelCase ).to(_lowerCAmelCase )
self.timesteps += self.config.steps_offset
def __a ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = 0.0 , _lowerCAmelCase = False , _lowerCAmelCase = None , _lowerCAmelCase = True , ):
# 1. get previous step value (=t+1)
_lowercase : Union[str, Any] = timestep + self.config.num_train_timesteps // self.num_inference_steps
# 2. compute alphas, betas
# change original implementation to exactly match noise levels for analogous forward process
_lowercase : List[str] = self.alphas_cumprod[timestep]
_lowercase : int = (
self.alphas_cumprod[prev_timestep]
if prev_timestep < self.config.num_train_timesteps
else self.final_alpha_cumprod
)
_lowercase : int = 1 - alpha_prod_t
# 3. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
if self.config.prediction_type == "epsilon":
_lowercase : List[Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
_lowercase : int = model_output
elif self.config.prediction_type == "sample":
_lowercase : Optional[int] = model_output
_lowercase : Optional[int] = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5
elif self.config.prediction_type == "v_prediction":
_lowercase : Any = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
_lowercase : Union[str, Any] = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
else:
raise ValueError(
F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"""
' `v_prediction`' )
# 4. Clip or threshold "predicted x_0"
if self.config.clip_sample:
_lowercase : List[str] = pred_original_sample.clamp(
-self.config.clip_sample_range , self.config.clip_sample_range )
# 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
_lowercase : Optional[int] = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon
# 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
_lowercase : List[str] = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction
if not return_dict:
return (prev_sample, pred_original_sample)
return DDIMSchedulerOutput(prev_sample=_lowerCAmelCase , pred_original_sample=_lowerCAmelCase )
def __len__( self ):
return self.config.num_train_timesteps
| 677
|
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
UpperCamelCase = {
"configuration_blenderbot": [
"BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP",
"BlenderbotConfig",
"BlenderbotOnnxConfig",
],
"tokenization_blenderbot": ["BlenderbotTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase = ["BlenderbotTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase = [
"BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST",
"BlenderbotForCausalLM",
"BlenderbotForConditionalGeneration",
"BlenderbotModel",
"BlenderbotPreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase = [
"TFBlenderbotForConditionalGeneration",
"TFBlenderbotModel",
"TFBlenderbotPreTrainedModel",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase = [
"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
UpperCamelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 677
| 1
|
import argparse
import json
import os
import torch
from transformers.file_utils import has_file
from diffusers import UNetaDConditionModel, UNetaDModel
a__ : int = False
a__ : str = True
a__ : Any = False
if __name__ == "__main__":
a__ : List[Any] = 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__ : Dict = parser.parse_args()
a__ : Optional[int] = {
'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__ : Optional[int] = {
'time_steps': 'time_proj',
'mid': 'mid_block',
'downsample_blocks': 'down_blocks',
'upsample_blocks': 'up_blocks',
}
a__ : Any = '' 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__ : List[Any] = reader.read()
a__ : List[str] = 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__ : Union[str, Any] = UNetaDModel(**config)
else:
a__ : Optional[Any] = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel
a__ : Any = class_name(**config)
if do_only_config:
model.save_config(os.path.join(args.repo_path, subfolder))
a__ : List[str] = dict(model.config)
if do_only_renaming:
for key, value in config_parameters_to_change.items():
if key in config:
a__ : Optional[int] = config[key]
del config[key]
a__ : str = [k.replace('UNetRes', '') for k in config['down_block_types']]
a__ : List[Any] = [k.replace('UNetRes', '') for k in config['up_block_types']]
if do_only_weights:
a__ : int = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin'))
a__ : int = {}
for param_key, param_value in state_dict.items():
if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'):
continue
a__ : List[str] = False
for key, new_key in key_parameters_to_change.items():
if not has_changed and param_key.split('.')[0] == key:
a__ : List[Any] = param_value
a__ : List[str] = True
if not has_changed:
a__ : Optional[int] = param_value
model.load_state_dict(new_state_dict)
model.save_pretrained(os.path.join(args.repo_path, subfolder))
| 188
|
import unittest
import numpy as np
import torch
from diffusers import VersatileDiffusionImageVariationPipeline
from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device
a__ : Optional[int] = False
class UpperCAmelCase_ ( unittest.TestCase ):
pass
@slow
@require_torch_gpu
class UpperCAmelCase_ ( unittest.TestCase ):
def __UpperCAmelCase ( self ):
"""simple docstring"""
A_ = VersatileDiffusionImageVariationPipeline.from_pretrained('''shi-labs/versatile-diffusion''' )
pipe.to(__snake_case )
pipe.set_progress_bar_config(disable=__snake_case )
A_ = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' )
A_ = torch.manual_seed(0 )
A_ = pipe(
image=__snake_case ,generator=__snake_case ,guidance_scale=7.5 ,num_inference_steps=5_0 ,output_type='''numpy''' ,).images
A_ = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]
assert image.shape == (1, 5_1_2, 5_1_2, 3)
A_ = np.array([0.0441, 0.0469, 0.0507, 0.0575, 0.0632, 0.0650, 0.0865, 0.0909, 0.0945] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
| 188
| 1
|
"""simple docstring"""
import fire
from utils import calculate_rouge, save_json
def _snake_case ( UpperCamelCase : Dict , UpperCamelCase : List[str] , UpperCamelCase : Any=None , **UpperCamelCase : Any ):
UpperCAmelCase : List[str] = [x.strip() for x in open(_A ).readlines()]
UpperCAmelCase : Optional[int] = [x.strip() for x in open(_A ).readlines()][: len(_A )]
UpperCAmelCase : Union[str, Any] = calculate_rouge(_A , _A , **_A )
if save_path is not None:
save_json(_A , _A , indent=_A )
return metrics # these print nicely
if __name__ == "__main__":
fire.Fire(calculate_rouge_path)
| 719
|
"""simple docstring"""
import dataclasses
import re
import string
from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple
import numpy as np
from . import residue_constants
A: List[str] = Mapping[str, np.ndarray]
A: Union[str, Any] = Mapping[str, Any] # Is a nested dict.
A: Any = 0.01
@dataclasses.dataclass(frozen=UpperCAmelCase__ )
class SCREAMING_SNAKE_CASE__ :
__lowerCAmelCase : np.ndarray # [num_res, num_atom_type, 3]
# Amino-acid type for each residue represented as an integer between 0 and
# 20, where 20 is 'X'.
__lowerCAmelCase : np.ndarray # [num_res]
# Binary float mask to indicate presence of a particular atom. 1.0 if an atom
# is present and 0.0 if not. This should be used for loss masking.
__lowerCAmelCase : np.ndarray # [num_res, num_atom_type]
# Residue index as used in PDB. It is not necessarily continuous or 0-indexed.
__lowerCAmelCase : np.ndarray # [num_res]
# B-factors, or temperature factors, of each residue (in sq. angstroms units),
# representing the displacement of the residue from its ground truth mean
# value.
__lowerCAmelCase : np.ndarray # [num_res, num_atom_type]
# Chain indices for multi-chain predictions
__lowerCAmelCase : Optional[np.ndarray] = None
# Optional remark about the protein. Included as a comment in output PDB
# files
__lowerCAmelCase : Optional[str] = None
# Templates used to generate this protein (prediction-only)
__lowerCAmelCase : Optional[Sequence[str]] = None
# Chain corresponding to each parent
__lowerCAmelCase : Optional[Sequence[int]] = None
def _snake_case ( UpperCamelCase : str ):
UpperCAmelCase : str = R"""(\[[A-Z]+\]\n)"""
UpperCAmelCase : List[str] = [tag.strip() for tag in re.split(UpperCamelCase , UpperCamelCase ) if len(UpperCamelCase ) > 0]
UpperCAmelCase : Iterator[Tuple[str, List[str]]] = zip(tags[0::2] , [l.split("""\n""" ) for l in tags[1::2]] )
UpperCAmelCase : List[str] = ["N", "CA", "C"]
UpperCAmelCase : List[str] = None
UpperCAmelCase : Tuple = None
UpperCAmelCase : Tuple = None
for g in groups:
if "[PRIMARY]" == g[0]:
UpperCAmelCase : Any = g[1][0].strip()
for i in range(len(UpperCamelCase ) ):
if seq[i] not in residue_constants.restypes:
UpperCAmelCase : int = """X""" # FIXME: strings are immutable
UpperCAmelCase : Optional[int] = np.array(
[residue_constants.restype_order.get(UpperCamelCase , residue_constants.restype_num ) for res_symbol in seq] )
elif "[TERTIARY]" == g[0]:
UpperCAmelCase : List[List[float]] = []
for axis in range(3 ):
tertiary.append(list(map(UpperCamelCase , g[1][axis].split() ) ) )
UpperCAmelCase : Optional[Any] = np.array(UpperCamelCase )
UpperCAmelCase : Any = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa )
for i, atom in enumerate(UpperCamelCase ):
UpperCAmelCase : Any = np.transpose(tertiary_np[:, i::3] )
atom_positions *= PICO_TO_ANGSTROM
elif "[MASK]" == g[0]:
UpperCAmelCase : Union[str, Any] = np.array(list(map({"""-""": 0, """+""": 1}.get , g[1][0].strip() ) ) )
UpperCAmelCase : Union[str, Any] = np.zeros(
(
len(UpperCamelCase ),
residue_constants.atom_type_num,
) ).astype(np.floataa )
for i, atom in enumerate(UpperCamelCase ):
UpperCAmelCase : Any = 1
atom_mask *= mask[..., None]
assert aatype is not None
return Protein(
atom_positions=UpperCamelCase , atom_mask=UpperCamelCase , aatype=UpperCamelCase , residue_index=np.arange(len(UpperCamelCase ) ) , b_factors=UpperCamelCase , )
def _snake_case ( UpperCamelCase : Protein , UpperCamelCase : int = 0 ):
UpperCAmelCase : List[str] = []
UpperCAmelCase : List[Any] = prot.remark
if remark is not None:
pdb_headers.append(F"REMARK {remark}" )
UpperCAmelCase : List[str] = prot.parents
UpperCAmelCase : List[Any] = prot.parents_chain_index
if parents is not None and parents_chain_index is not None:
UpperCAmelCase : int = [p for i, p in zip(UpperCamelCase , UpperCamelCase ) if i == chain_id]
if parents is None or len(UpperCamelCase ) == 0:
UpperCAmelCase : Tuple = ["""N/A"""]
pdb_headers.append(F"PARENT {' '.join(UpperCamelCase )}" )
return pdb_headers
def _snake_case ( UpperCamelCase : Protein , UpperCamelCase : str ):
UpperCAmelCase : List[str] = []
UpperCAmelCase : Tuple = pdb_str.split("""\n""" )
UpperCAmelCase : List[Any] = prot.remark
if remark is not None:
out_pdb_lines.append(F"REMARK {remark}" )
UpperCAmelCase : List[List[str]]
if prot.parents is not None and len(prot.parents ) > 0:
UpperCAmelCase : Tuple = []
if prot.parents_chain_index is not None:
UpperCAmelCase : Dict[str, List[str]] = {}
for p, i in zip(prot.parents , prot.parents_chain_index ):
parent_dict.setdefault(str(UpperCamelCase ) , [] )
parent_dict[str(UpperCamelCase )].append(UpperCamelCase )
UpperCAmelCase : Tuple = max([int(UpperCamelCase ) for chain_idx in parent_dict] )
for i in range(max_idx + 1 ):
UpperCAmelCase : int = parent_dict.get(str(UpperCamelCase ) , ["""N/A"""] )
parents_per_chain.append(UpperCamelCase )
else:
parents_per_chain.append(list(prot.parents ) )
else:
UpperCAmelCase : Union[str, Any] = [["""N/A"""]]
def make_parent_line(UpperCamelCase : Sequence[str] ) -> str:
return F"PARENT {' '.join(UpperCamelCase )}"
out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) )
UpperCAmelCase : Any = 0
for i, l in enumerate(UpperCamelCase ):
if "PARENT" not in l and "REMARK" not in l:
out_pdb_lines.append(UpperCamelCase )
if "TER" in l and "END" not in lines[i + 1]:
chain_counter += 1
if not chain_counter >= len(UpperCamelCase ):
UpperCAmelCase : List[Any] = parents_per_chain[chain_counter]
else:
UpperCAmelCase : Optional[Any] = ["""N/A"""]
out_pdb_lines.append(make_parent_line(UpperCamelCase ) )
return "\n".join(UpperCamelCase )
def _snake_case ( UpperCamelCase : Protein ):
UpperCAmelCase : int = residue_constants.restypes + ["""X"""]
def res_atoa(UpperCamelCase : int ) -> str:
return residue_constants.restype_atoa.get(restypes[r] , """UNK""" )
UpperCAmelCase : List[str] = residue_constants.atom_types
UpperCAmelCase : List[str] = []
UpperCAmelCase : Dict = prot.atom_mask
UpperCAmelCase : Optional[int] = prot.aatype
UpperCAmelCase : Optional[int] = prot.atom_positions
UpperCAmelCase : str = prot.residue_index.astype(np.intaa )
UpperCAmelCase : Tuple = prot.b_factors
UpperCAmelCase : str = prot.chain_index
if np.any(aatype > residue_constants.restype_num ):
raise ValueError("""Invalid aatypes.""" )
UpperCAmelCase : Any = get_pdb_headers(UpperCamelCase )
if len(UpperCamelCase ) > 0:
pdb_lines.extend(UpperCamelCase )
UpperCAmelCase : List[str] = aatype.shape[0]
UpperCAmelCase : int = 1
UpperCAmelCase : Optional[Any] = 0
UpperCAmelCase : str = string.ascii_uppercase
UpperCAmelCase : Tuple = None
# Add all atom sites.
for i in range(UpperCamelCase ):
UpperCAmelCase : Optional[int] = res_atoa(aatype[i] )
for atom_name, pos, mask, b_factor in zip(UpperCamelCase , atom_positions[i] , atom_mask[i] , b_factors[i] ):
if mask < 0.5:
continue
UpperCAmelCase : List[Any] = """ATOM"""
UpperCAmelCase : Dict = atom_name if len(UpperCamelCase ) == 4 else F" {atom_name}"
UpperCAmelCase : Union[str, Any] = """"""
UpperCAmelCase : Dict = """"""
UpperCAmelCase : Optional[int] = 1.00
UpperCAmelCase : Union[str, Any] = atom_name[0] # Protein supports only C, N, O, S, this works.
UpperCAmelCase : Any = """"""
UpperCAmelCase : List[Any] = """A"""
if chain_index is not None:
UpperCAmelCase : List[str] = chain_tags[chain_index[i]]
# PDB is a columnar format, every space matters here!
UpperCAmelCase : Dict = (
F"{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}"
F"{res_name_a:>3} {chain_tag:>1}"
F"{residue_index[i]:>4}{insertion_code:>1} "
F"{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}"
F"{occupancy:>6.2f}{b_factor:>6.2f} "
F"{element:>2}{charge:>2}"
)
pdb_lines.append(UpperCamelCase )
atom_index += 1
UpperCAmelCase : Union[str, Any] = i == n - 1
if chain_index is not None:
if i != n - 1 and chain_index[i + 1] != prev_chain_index:
UpperCAmelCase : Any = True
UpperCAmelCase : List[str] = chain_index[i + 1]
if should_terminate:
# Close the chain.
UpperCAmelCase : Optional[int] = """TER"""
UpperCAmelCase : Union[str, Any] = (
F"{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}"
)
pdb_lines.append(UpperCamelCase )
atom_index += 1
if i != n - 1:
# "prev" is a misnomer here. This happens at the beginning of
# each new chain.
pdb_lines.extend(get_pdb_headers(UpperCamelCase , UpperCamelCase ) )
pdb_lines.append("""END""" )
pdb_lines.append("""""" )
return "\n".join(UpperCamelCase )
def _snake_case ( UpperCamelCase : Protein ):
return residue_constants.STANDARD_ATOM_MASK[prot.aatype]
def _snake_case ( UpperCamelCase : FeatureDict , UpperCamelCase : ModelOutput , UpperCamelCase : Optional[np.ndarray] = None , UpperCamelCase : Optional[np.ndarray] = None , UpperCamelCase : Optional[str] = None , UpperCamelCase : Optional[Sequence[str]] = None , UpperCamelCase : Optional[Sequence[int]] = None , ):
return Protein(
aatype=features["""aatype"""] , atom_positions=result["""final_atom_positions"""] , atom_mask=result["""final_atom_mask"""] , residue_index=features["""residue_index"""] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result["""final_atom_mask"""] ) , chain_index=UpperCamelCase , remark=UpperCamelCase , parents=UpperCamelCase , parents_chain_index=UpperCamelCase , )
| 359
| 0
|
def _lowerCamelCase ( __lowerCamelCase ) -> list:
'''simple docstring'''
UpperCAmelCase__ : List[Any] = [0] * len(__lowerCamelCase )
for i in range(1 , len(__lowerCamelCase ) ):
# use last results for better performance - dynamic programming
UpperCAmelCase__ : List[Any] = prefix_result[i - 1]
while j > 0 and input_string[i] != input_string[j]:
UpperCAmelCase__ : List[str] = prefix_result[j - 1]
if input_string[i] == input_string[j]:
j += 1
UpperCAmelCase__ : int = j
return prefix_result
def _lowerCamelCase ( __lowerCamelCase ) -> int:
'''simple docstring'''
return max(prefix_function(__lowerCamelCase ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 79
|
import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union
import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn
import transformers
from transformers import (
HfArgumentParser,
Trainer,
TrainingArguments,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaForCTC,
WavaVecaProcessor,
is_apex_available,
set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process
if is_apex_available():
from apex import amp
if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'):
UpperCamelCase__ = True
from torch.cuda.amp import autocast
UpperCamelCase__ = logging.getLogger(__name__)
def UpperCamelCase__ ( UpperCAmelCase_=None , UpperCAmelCase_=None ) -> List[str]:
'''simple docstring'''
return field(default_factory=lambda: default , metadata=UpperCAmelCase_ )
@dataclass
class UpperCAmelCase__ :
'''simple docstring'''
UpperCAmelCase_ = field(
metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} )
UpperCAmelCase_ = field(
default=A_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , )
UpperCAmelCase_ = field(
default=A_ , metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''} )
UpperCAmelCase_ = field(
default=0.1 , metadata={'''help''': '''The dropout ratio for the attention probabilities.'''} )
UpperCAmelCase_ = field(
default=0.1 , metadata={'''help''': '''The dropout ratio for activations inside the fully connected layer.'''} )
UpperCAmelCase_ = field(
default=0.1 , metadata={
'''help''': '''The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'''
} , )
UpperCAmelCase_ = field(
default=0.1 , metadata={'''help''': '''The dropout probabilitiy for all 1D convolutional layers in feature extractor.'''} , )
UpperCAmelCase_ = field(
default=0.05 , metadata={
'''help''': (
'''Propability of each feature vector along the time axis to be chosen as the start of the vector'''
'''span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'''
'''vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'''
)
} , )
UpperCAmelCase_ = field(default=0.0 , metadata={'''help''': '''The LayerDrop probability.'''} )
@dataclass
class UpperCAmelCase__ :
'''simple docstring'''
UpperCAmelCase_ = field(
default=A_ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} )
UpperCAmelCase_ = field(
default='''train+validation''' , metadata={
'''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\''''
} , )
UpperCAmelCase_ = field(
default=A_ , metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''} )
UpperCAmelCase_ = field(
default=A_ , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , )
UpperCAmelCase_ = field(
default=A_ , metadata={
'''help''': (
'''For debugging purposes or quicker training, truncate the number of training examples to this '''
'''value if set.'''
)
} , )
UpperCAmelCase_ = field(
default=A_ , metadata={
'''help''': (
'''For debugging purposes or quicker training, truncate the number of validation examples to this '''
'''value if set.'''
)
} , )
UpperCAmelCase_ = list_field(
default=[''',''', '''?''', '''.''', '''!''', '''-''', ''';''', ''':''', '''""''', '''%''', '''\'''', '''"''', '''�'''] , metadata={'''help''': '''A list of characters to remove from the transcripts.'''} , )
@dataclass
class UpperCAmelCase__ :
'''simple docstring'''
UpperCAmelCase_ = 42
UpperCAmelCase_ = True
UpperCAmelCase_ = None
UpperCAmelCase_ = None
UpperCAmelCase_ = None
UpperCAmelCase_ = None
def __call__( self : List[Any] , UpperCamelCase : List[Dict[str, Union[List[int], torch.Tensor]]] ):
"""simple docstring"""
_lowercase : int = [{'''input_values''': feature['''input_values''']} for feature in features]
_lowercase : Dict = [{'''input_ids''': feature['''labels''']} for feature in features]
_lowercase : int = self.processor.pad(
UpperCamelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' , )
_lowercase : Union[str, Any] = self.processor.pad(
labels=UpperCamelCase , padding=self.padding , max_length=self.max_length_labels , pad_to_multiple_of=self.pad_to_multiple_of_labels , return_tensors='''pt''' , )
# replace padding with -100 to ignore loss correctly
_lowercase : Optional[Any] = labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1 ) , -1_00 )
_lowercase : Optional[Any] = labels
return batch
class UpperCAmelCase__ ( A_ ):
'''simple docstring'''
def lowerCAmelCase_ ( self : List[str] , UpperCamelCase : nn.Module , UpperCamelCase : Dict[str, Union[torch.Tensor, Any]] ):
"""simple docstring"""
model.train()
_lowercase : Tuple = self._prepare_inputs(UpperCamelCase )
if self.use_amp:
with autocast():
_lowercase : Union[str, Any] = self.compute_loss(UpperCamelCase , UpperCamelCase )
else:
_lowercase : List[str] = self.compute_loss(UpperCamelCase , UpperCamelCase )
if self.args.n_gpu > 1:
if model.module.config.ctc_loss_reduction == "mean":
_lowercase : str = loss.mean()
elif model.module.config.ctc_loss_reduction == "sum":
_lowercase : Optional[Any] = loss.sum() / (inputs['''labels'''] >= 0).sum()
else:
raise ValueError(F'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']' )
if self.args.gradient_accumulation_steps > 1:
_lowercase : Optional[int] = loss / self.args.gradient_accumulation_steps
if self.use_amp:
self.scaler.scale(UpperCamelCase ).backward()
elif self.use_apex:
with amp.scale_loss(UpperCamelCase , self.optimizer ) as scaled_loss:
scaled_loss.backward()
elif self.deepspeed:
self.deepspeed.backward(UpperCamelCase )
else:
loss.backward()
return loss.detach()
def UpperCamelCase__ ( ) -> Optional[Any]:
'''simple docstring'''
_lowercase : List[str] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
_lowercase , _lowercase , _lowercase : Any = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
_lowercase , _lowercase , _lowercase : int = parser.parse_args_into_dataclasses()
# Detecting last checkpoint.
_lowercase : Dict = None
if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
_lowercase : Optional[int] = get_last_checkpoint(training_args.output_dir )
if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0:
raise ValueError(
F'Output directory ({training_args.output_dir}) already exists and is not empty. '
'''Use --overwrite_output_dir to overcome.''' )
elif last_checkpoint is not None:
logger.info(
F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '
'''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' )
# Setup logging
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , )
logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN )
# Log on each process the small summary:
logger.warning(
F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'
+ F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' )
# Set the verbosity to info of the Transformers logger (on main process only):
if is_main_process(training_args.local_rank ):
transformers.utils.logging.set_verbosity_info()
logger.info('''Training/evaluation parameters %s''' , UpperCAmelCase_ )
# Set seed before initializing model.
set_seed(training_args.seed )
# Get the datasets:
_lowercase : Tuple = datasets.load_dataset(
'''common_voice''' , data_args.dataset_config_name , split=data_args.train_split_name )
_lowercase : Dict = datasets.load_dataset('''common_voice''' , data_args.dataset_config_name , split='''test''' )
# Create and save tokenizer
_lowercase : Tuple = F'[{"".join(data_args.chars_to_ignore )}]'
def remove_special_characters(UpperCAmelCase_ ):
_lowercase : List[Any] = re.sub(UpperCAmelCase_ , '''''' , batch['''sentence'''] ).lower() + ''' '''
return batch
_lowercase : Tuple = train_dataset.map(UpperCAmelCase_ , remove_columns=['''sentence'''] )
_lowercase : int = eval_dataset.map(UpperCAmelCase_ , remove_columns=['''sentence'''] )
def extract_all_chars(UpperCAmelCase_ ):
_lowercase : int = ''' '''.join(batch['''text'''] )
_lowercase : int = list(set(UpperCAmelCase_ ) )
return {"vocab": [vocab], "all_text": [all_text]}
_lowercase : List[Any] = train_dataset.map(
UpperCAmelCase_ , batched=UpperCAmelCase_ , batch_size=-1 , keep_in_memory=UpperCAmelCase_ , remove_columns=train_dataset.column_names , )
_lowercase : Any = train_dataset.map(
UpperCAmelCase_ , batched=UpperCAmelCase_ , batch_size=-1 , keep_in_memory=UpperCAmelCase_ , remove_columns=eval_dataset.column_names , )
_lowercase : Optional[int] = list(set(vocab_train['''vocab'''][0] ) | set(vocab_test['''vocab'''][0] ) )
_lowercase : str = {v: k for k, v in enumerate(UpperCAmelCase_ )}
_lowercase : Dict = vocab_dict[''' ''']
del vocab_dict[" "]
_lowercase : Any = len(UpperCAmelCase_ )
_lowercase : str = len(UpperCAmelCase_ )
with open('''vocab.json''' , '''w''' ) as vocab_file:
json.dump(UpperCAmelCase_ , UpperCAmelCase_ )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
_lowercase : List[str] = WavaVecaCTCTokenizer(
'''vocab.json''' , unk_token='''[UNK]''' , pad_token='''[PAD]''' , word_delimiter_token='''|''' , )
_lowercase : str = WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=16000 , padding_value=0.0 , do_normalize=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ )
_lowercase : int = WavaVecaProcessor(feature_extractor=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ )
_lowercase : str = WavaVecaForCTC.from_pretrained(
model_args.model_name_or_path , cache_dir=model_args.cache_dir , activation_dropout=model_args.activation_dropout , attention_dropout=model_args.attention_dropout , hidden_dropout=model_args.hidden_dropout , feat_proj_dropout=model_args.feat_proj_dropout , mask_time_prob=model_args.mask_time_prob , gradient_checkpointing=training_args.gradient_checkpointing , layerdrop=model_args.layerdrop , ctc_loss_reduction='''mean''' , pad_token_id=processor.tokenizer.pad_token_id , vocab_size=len(processor.tokenizer ) , )
if data_args.max_train_samples is not None:
_lowercase : List[str] = min(len(UpperCAmelCase_ ) , data_args.max_train_samples )
_lowercase : Tuple = train_dataset.select(range(UpperCAmelCase_ ) )
if data_args.max_val_samples is not None:
_lowercase : List[str] = eval_dataset.select(range(data_args.max_val_samples ) )
_lowercase : Tuple = torchaudio.transforms.Resample(48000 , 16000 )
# Preprocessing the datasets.
# We need to read the aduio files as arrays and tokenize the targets.
def speech_file_to_array_fn(UpperCAmelCase_ ):
_lowercase , _lowercase : List[Any] = torchaudio.load(batch['''path'''] )
_lowercase : Optional[int] = resampler(UpperCAmelCase_ ).squeeze().numpy()
_lowercase : Any = 16000
_lowercase : List[str] = batch['''text''']
return batch
_lowercase : Union[str, Any] = train_dataset.map(
UpperCAmelCase_ , remove_columns=train_dataset.column_names , num_proc=data_args.preprocessing_num_workers , )
_lowercase : Union[str, Any] = eval_dataset.map(
UpperCAmelCase_ , remove_columns=eval_dataset.column_names , num_proc=data_args.preprocessing_num_workers , )
def prepare_dataset(UpperCAmelCase_ ):
# check that all files have the correct sampling rate
assert (
len(set(batch['''sampling_rate'''] ) ) == 1
), F'Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'
_lowercase : Dict = processor(
audio=batch['''speech'''] , text=batch['''target_text'''] , sampling_rate=batch['''sampling_rate'''][0] )
batch.update(UpperCAmelCase_ )
return batch
_lowercase : Any = train_dataset.map(
UpperCAmelCase_ , remove_columns=train_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=UpperCAmelCase_ , num_proc=data_args.preprocessing_num_workers , )
_lowercase : Optional[Any] = eval_dataset.map(
UpperCAmelCase_ , remove_columns=eval_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=UpperCAmelCase_ , num_proc=data_args.preprocessing_num_workers , )
# Metric
_lowercase : Any = datasets.load_metric('''wer''' )
def compute_metrics(UpperCAmelCase_ ):
_lowercase : Optional[Any] = pred.predictions
_lowercase : Dict = np.argmax(UpperCAmelCase_ , axis=-1 )
_lowercase : Optional[int] = processor.tokenizer.pad_token_id
_lowercase : List[Any] = processor.batch_decode(UpperCAmelCase_ )
# we do not want to group tokens when computing the metrics
_lowercase : str = processor.batch_decode(pred.label_ids , group_tokens=UpperCAmelCase_ )
_lowercase : Union[str, Any] = wer_metric.compute(predictions=UpperCAmelCase_ , references=UpperCAmelCase_ )
return {"wer": wer}
if model_args.freeze_feature_extractor:
model.freeze_feature_extractor()
# Data collator
_lowercase : List[str] = DataCollatorCTCWithPadding(processor=UpperCAmelCase_ , padding=UpperCAmelCase_ )
# Initialize our Trainer
_lowercase : Dict = CTCTrainer(
model=UpperCAmelCase_ , data_collator=UpperCAmelCase_ , args=UpperCAmelCase_ , compute_metrics=UpperCAmelCase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=processor.feature_extractor , )
# Training
if training_args.do_train:
if last_checkpoint is not None:
_lowercase : Optional[Any] = last_checkpoint
elif os.path.isdir(model_args.model_name_or_path ):
_lowercase : Tuple = model_args.model_name_or_path
else:
_lowercase : Tuple = None
# Save the feature_extractor and the tokenizer
if is_main_process(training_args.local_rank ):
processor.save_pretrained(training_args.output_dir )
_lowercase : Union[str, Any] = trainer.train(resume_from_checkpoint=UpperCAmelCase_ )
trainer.save_model()
_lowercase : Any = train_result.metrics
_lowercase : str = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(UpperCAmelCase_ )
)
_lowercase : Dict = min(UpperCAmelCase_ , len(UpperCAmelCase_ ) )
trainer.log_metrics('''train''' , UpperCAmelCase_ )
trainer.save_metrics('''train''' , UpperCAmelCase_ )
trainer.save_state()
# Evaluation
_lowercase : Optional[Any] = {}
if training_args.do_eval:
logger.info('''*** Evaluate ***''' )
_lowercase : Any = trainer.evaluate()
_lowercase : Union[str, Any] = data_args.max_val_samples if data_args.max_val_samples is not None else len(UpperCAmelCase_ )
_lowercase : str = min(UpperCAmelCase_ , len(UpperCAmelCase_ ) )
trainer.log_metrics('''eval''' , UpperCAmelCase_ )
trainer.save_metrics('''eval''' , UpperCAmelCase_ )
return results
if __name__ == "__main__":
main()
| 322
| 0
|
from ..utils import is_flax_available, is_torch_available
if is_torch_available():
from .autoencoder_kl import AutoencoderKL
from .controlnet import ControlNetModel
from .dual_transformer_ad import DualTransformeraDModel
from .modeling_utils import ModelMixin
from .prior_transformer import PriorTransformer
from .ta_film_transformer import TaFilmDecoder
from .transformer_ad import TransformeraDModel
from .unet_ad import UNetaDModel
from .unet_ad import UNetaDModel
from .unet_ad_condition import UNetaDConditionModel
from .unet_ad_condition import UNetaDConditionModel
from .vq_model import VQModel
if is_flax_available():
from .controlnet_flax import FlaxControlNetModel
from .unet_ad_condition_flax import FlaxUNetaDConditionModel
from .vae_flax import FlaxAutoencoderKL
| 382
|
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a = logging.get_logger(__name__)
a = {
"""facebook/s2t-wav2vec2-large-en-de""": (
"""https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json"""
),
# See all Speech2Text models at https://huggingface.co/models?filter=speech2text2
}
class UpperCAmelCase_ (snake_case__ ):
"""simple docstring"""
lowerCamelCase : Tuple = 'speech_to_text_2'
lowerCamelCase : int = ['past_key_values']
lowerCamelCase : int = {'num_attention_heads': 'decoder_attention_heads', 'hidden_size': 'd_model'}
def __init__( self: Optional[Any] , _UpperCAmelCase: Optional[Any]=1_0000 , _UpperCAmelCase: Union[str, Any]=6 , _UpperCAmelCase: Optional[int]=2048 , _UpperCAmelCase: Optional[Any]=4 , _UpperCAmelCase: Any=0.0 , _UpperCAmelCase: Optional[int]=True , _UpperCAmelCase: Any="relu" , _UpperCAmelCase: Dict=256 , _UpperCAmelCase: int=0.1 , _UpperCAmelCase: List[str]=0.0 , _UpperCAmelCase: str=0.0 , _UpperCAmelCase: List[Any]=0.0_2 , _UpperCAmelCase: int=2 , _UpperCAmelCase: Optional[int]=True , _UpperCAmelCase: Optional[Any]=1 , _UpperCAmelCase: Dict=0 , _UpperCAmelCase: Optional[Any]=2 , _UpperCAmelCase: Tuple=1024 , **_UpperCAmelCase: str , ):
_lowerCAmelCase :List[Any] = vocab_size
_lowerCAmelCase :Tuple = d_model
_lowerCAmelCase :Any = decoder_ffn_dim
_lowerCAmelCase :List[str] = decoder_layers
_lowerCAmelCase :Optional[int] = decoder_attention_heads
_lowerCAmelCase :List[str] = dropout
_lowerCAmelCase :Optional[int] = attention_dropout
_lowerCAmelCase :Tuple = activation_dropout
_lowerCAmelCase :List[Any] = activation_function
_lowerCAmelCase :List[str] = init_std
_lowerCAmelCase :Dict = decoder_layerdrop
_lowerCAmelCase :List[Any] = use_cache
_lowerCAmelCase :List[Any] = decoder_layers
_lowerCAmelCase :Any = scale_embedding # scale factor will be sqrt(d_model) if True
_lowerCAmelCase :Tuple = max_target_positions
super().__init__(
pad_token_id=_UpperCAmelCase , bos_token_id=_UpperCAmelCase , eos_token_id=_UpperCAmelCase , decoder_start_token_id=_UpperCAmelCase , **_UpperCAmelCase , )
| 382
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.