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'''
from typing import Any, Callable, Dict, List, Optional, Union
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DiffusionPipeline,
LMSDiscreteScheduler,
PNDMScheduler,
StableDiffusionPipeline,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
UpperCamelCase__ = '''CompVis/stable-diffusion-v1-1'''
UpperCamelCase__ = '''CompVis/stable-diffusion-v1-2'''
UpperCamelCase__ = '''CompVis/stable-diffusion-v1-3'''
UpperCamelCase__ = '''CompVis/stable-diffusion-v1-4'''
class lowerCamelCase_ ( __a ):
def __init__( self : Dict , _A : str , _A : Union[str, Any] , _A : str , _A : Optional[int] , _A : Optional[Any] , _A : Tuple , _A : Optional[int] , _A : List[str] = True , ):
'''simple docstring'''
super()._init_()
UpperCAmelCase__ : Union[str, Any] = StableDiffusionPipeline.from_pretrained(A__ )
UpperCAmelCase__ : Any = StableDiffusionPipeline.from_pretrained(A__ )
UpperCAmelCase__ : List[Any] = StableDiffusionPipeline.from_pretrained(A__ )
UpperCAmelCase__ : List[Any] = StableDiffusionPipeline(
vae=A__ , text_encoder=A__ , tokenizer=A__ , unet=A__ , scheduler=A__ , safety_checker=A__ , feature_extractor=A__ , requires_safety_checker=A__ , )
self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea )
@property
def lowercase_ ( self : Dict ):
'''simple docstring'''
return {k: getattr(self , A__ ) for k in self.config.keys() if not k.startswith('''_''' )}
def lowercase_ ( self : List[Any] , _A : Optional[int] = "auto" ):
'''simple docstring'''
if slice_size == "auto":
# half the attention head size is usually a good trade-off between
# speed and memory
UpperCAmelCase__ : Optional[int] = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(A__ )
def lowercase_ ( self : str ):
'''simple docstring'''
self.enable_attention_slicing(A__ )
@torch.no_grad()
def lowercase_ ( self : List[str] , _A : Any , _A : Any = 512 , _A : Optional[Any] = 512 , _A : Optional[Any] = 50 , _A : Any = 7.5 , _A : List[Any] = None , _A : Dict = 1 , _A : Union[str, Any] = 0.0 , _A : List[str] = None , _A : List[Any] = None , _A : Any = "pil" , _A : Optional[int] = True , _A : List[str] = None , _A : Optional[int] = 1 , **_A : int , ):
'''simple docstring'''
return self.pipea(
prompt=A__ , height=A__ , width=A__ , num_inference_steps=A__ , guidance_scale=A__ , negative_prompt=A__ , num_images_per_prompt=A__ , eta=A__ , generator=A__ , latents=A__ , output_type=A__ , return_dict=A__ , callback=A__ , callback_steps=A__ , **A__ , )
@torch.no_grad()
def lowercase_ ( self : List[str] , _A : Optional[Any] , _A : List[Any] = 512 , _A : Optional[Any] = 512 , _A : Dict = 50 , _A : str = 7.5 , _A : List[Any] = None , _A : List[str] = 1 , _A : str = 0.0 , _A : str = None , _A : List[Any] = None , _A : Optional[int] = "pil" , _A : List[Any] = True , _A : List[Any] = None , _A : List[str] = 1 , **_A : List[Any] , ):
'''simple docstring'''
return self.pipea(
prompt=A__ , height=A__ , width=A__ , num_inference_steps=A__ , guidance_scale=A__ , negative_prompt=A__ , num_images_per_prompt=A__ , eta=A__ , generator=A__ , latents=A__ , output_type=A__ , return_dict=A__ , callback=A__ , callback_steps=A__ , **A__ , )
@torch.no_grad()
def lowercase_ ( self : Union[str, Any] , _A : int , _A : List[Any] = 512 , _A : Union[str, Any] = 512 , _A : Tuple = 50 , _A : Union[str, Any] = 7.5 , _A : Any = None , _A : Union[str, Any] = 1 , _A : str = 0.0 , _A : Optional[int] = None , _A : List[Any] = None , _A : Optional[Any] = "pil" , _A : List[str] = True , _A : Union[str, Any] = None , _A : str = 1 , **_A : List[Any] , ):
'''simple docstring'''
return self.pipea(
prompt=A__ , height=A__ , width=A__ , num_inference_steps=A__ , guidance_scale=A__ , negative_prompt=A__ , num_images_per_prompt=A__ , eta=A__ , generator=A__ , latents=A__ , output_type=A__ , return_dict=A__ , callback=A__ , callback_steps=A__ , **A__ , )
@torch.no_grad()
def lowercase_ ( self : List[Any] , _A : Optional[Any] , _A : int = 512 , _A : Tuple = 512 , _A : Optional[int] = 50 , _A : List[Any] = 7.5 , _A : str = None , _A : Optional[Any] = 1 , _A : int = 0.0 , _A : str = None , _A : Optional[Any] = None , _A : List[Any] = "pil" , _A : str = True , _A : Tuple = None , _A : Tuple = 1 , **_A : str , ):
'''simple docstring'''
return self.pipea(
prompt=A__ , height=A__ , width=A__ , num_inference_steps=A__ , guidance_scale=A__ , negative_prompt=A__ , num_images_per_prompt=A__ , eta=A__ , generator=A__ , latents=A__ , output_type=A__ , return_dict=A__ , callback=A__ , callback_steps=A__ , **A__ , )
@torch.no_grad()
def lowercase_ ( self : Optional[int] , _A : Tuple , _A : Optional[Any] = 512 , _A : List[str] = 512 , _A : Tuple = 50 , _A : Optional[int] = 7.5 , _A : Optional[int] = None , _A : Optional[Any] = 1 , _A : Tuple = 0.0 , _A : Optional[int] = None , _A : Optional[Any] = None , _A : str = "pil" , _A : Dict = True , _A : List[Any] = None , _A : Optional[int] = 1 , **_A : Optional[int] , ):
'''simple docstring'''
UpperCAmelCase__ : List[Any] = '''cuda''' if torch.cuda.is_available() else '''cpu'''
self.to(A__ )
# Checks if the height and width are divisible by 8 or not
if height % 8 != 0 or width % 8 != 0:
raise ValueError(f"""`height` and `width` must be divisible by 8 but are {height} and {width}.""" )
# Get first result from Stable Diffusion Checkpoint v1.1
UpperCAmelCase__ : str = self.textaimg_sda_a(
prompt=A__ , height=A__ , width=A__ , num_inference_steps=A__ , guidance_scale=A__ , negative_prompt=A__ , num_images_per_prompt=A__ , eta=A__ , generator=A__ , latents=A__ , output_type=A__ , return_dict=A__ , callback=A__ , callback_steps=A__ , **A__ , )
# Get first result from Stable Diffusion Checkpoint v1.2
UpperCAmelCase__ : Any = self.textaimg_sda_a(
prompt=A__ , height=A__ , width=A__ , num_inference_steps=A__ , guidance_scale=A__ , negative_prompt=A__ , num_images_per_prompt=A__ , eta=A__ , generator=A__ , latents=A__ , output_type=A__ , return_dict=A__ , callback=A__ , callback_steps=A__ , **A__ , )
# Get first result from Stable Diffusion Checkpoint v1.3
UpperCAmelCase__ : Optional[Any] = self.textaimg_sda_a(
prompt=A__ , height=A__ , width=A__ , num_inference_steps=A__ , guidance_scale=A__ , negative_prompt=A__ , num_images_per_prompt=A__ , eta=A__ , generator=A__ , latents=A__ , output_type=A__ , return_dict=A__ , callback=A__ , callback_steps=A__ , **A__ , )
# Get first result from Stable Diffusion Checkpoint v1.4
UpperCAmelCase__ : Dict = self.textaimg_sda_a(
prompt=A__ , height=A__ , width=A__ , num_inference_steps=A__ , guidance_scale=A__ , negative_prompt=A__ , num_images_per_prompt=A__ , eta=A__ , generator=A__ , latents=A__ , output_type=A__ , return_dict=A__ , callback=A__ , callback_steps=A__ , **A__ , )
# Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
| 75 |
'''simple docstring'''
from typing import List, Optional, Union
import numpy as np
import tensorflow as tf
from .utils import logging
_lowercase = logging.get_logger(__name__)
def __UpperCamelCase ( a : Union[tf.Tensor, np.ndarray] ) ->List[int]:
if isinstance(a , np.ndarray ):
return list(tensor.shape )
snake_case = tf.shape(a )
if tensor.shape == tf.TensorShape(a ):
return dynamic
snake_case = tensor.shape.as_list()
return [dynamic[i] if s is None else s for i, s in enumerate(a )]
def __UpperCamelCase ( a : tf.Tensor , a : Optional[int] = None , a : Optional[str] = None ) ->tf.Tensor:
return tf.nn.softmax(logits=logits + 1e-9 , axis=a , name=a )
def __UpperCamelCase ( a : List[str] , a : Union[str, Any] , a : Tuple , a : List[str]=1e-5 , a : Any=-1 ) ->Dict:
# This is a very simplified functional layernorm, designed to duplicate
# the functionality of PyTorch nn.functional.layer_norm when this is needed to port
# models in Transformers.
if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(a , a ):
raise NotImplementedError('''Only 1D weight and bias tensors are supported for now, with only a single axis.''' )
# Get mean and variance on the axis to be normalized
snake_case , snake_case = tf.nn.moments(a , axes=[axis] , keepdims=a )
if axis != -1:
# Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
# on every dimension except axis
snake_case = [1] * inputs.shape.rank
snake_case = shape_list(a )[axis]
snake_case = tf.reshape(a , a )
snake_case = tf.reshape(a , a )
# Compute layer normalization using the batch_normalization
# function.
snake_case = tf.nn.batch_normalization(
a , a , a , offset=a , scale=a , variance_epsilon=a , )
return outputs
def __UpperCamelCase ( a : Tuple , a : Union[str, Any]=0 , a : List[str]=-1 ) ->int:
# Replicates the behavior of torch.flatten in TF
# If end_dim or start_dim is negative, count them from the end
if end_dim < 0:
end_dim += input.shape.rank
if start_dim < 0:
start_dim += input.shape.rank
if start_dim == end_dim:
return input
snake_case = tf.shape(a )
snake_case = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] )
snake_case = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 )
return tf.reshape(a , a )
def __UpperCamelCase ( a : tf.Tensor ) ->tf.Tensor:
if not isinstance(a , tf.Tensor ):
snake_case = tf.convert_to_tensor(a ) # Catches stray NumPy inputs
if encoder_attention_mask.shape.rank == 3:
snake_case = encoder_attention_mask[:, None, :, :]
if encoder_attention_mask.shape.rank == 2:
snake_case = encoder_attention_mask[:, None, None, :]
# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
# /transformer/transformer_layers.py#L270
# encoder_extended_attention_mask = (encoder_extended_attention_mask ==
# encoder_extended_attention_mask.transpose(-1, -2))
snake_case = (
tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask
) * encoder_extended_attention_mask.dtype.min
return encoder_extended_attention_mask
def __UpperCamelCase ( a : tf.Tensor , a : int , a : str = "input_ids" ) ->None:
tf.debugging.assert_less(
a , tf.cast(a , dtype=tensor.dtype ) , message=(
f"""The maximum value of {tensor_name} ({tf.math.reduce_max(a )}) must be smaller than the embedding """
f"""layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time."""
) , )
def __UpperCamelCase ( a : Tuple , a : List[str] , a : Tuple ) ->Dict:
snake_case = 6_4512
# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
# because in that case even chunking the array would not make the saving
# possible.
snake_case = [x for x in data if len(a ) > HDF5_OBJECT_HEADER_LIMIT]
# Expecting this to never be true.
if bad_attributes:
raise RuntimeError(
'''The following attributes cannot be saved to HDF5 file because '''
f"""they are larger than {HDF5_OBJECT_HEADER_LIMIT} """
f"""bytes: {bad_attributes}""" )
snake_case = np.asarray(a )
snake_case = 1
snake_case = np.array_split(a , a )
# This will never loop forever thanks to the test above.
while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ):
num_chunks += 1
snake_case = np.array_split(a , a )
if num_chunks > 1:
for chunk_id, chunk_data in enumerate(a ):
snake_case = chunk_data
else:
snake_case = data
def __UpperCamelCase ( a : Optional[int] , a : Tuple ) ->Tuple:
if name in group.attrs:
snake_case = [n.decode('''utf8''' ) if hasattr(a , '''decode''' ) else n for n in group.attrs[name]]
else:
snake_case = []
snake_case = 0
while "%s%d" % (name, chunk_id) in group.attrs:
data.extend(
[n.decode('''utf8''' ) if hasattr(a , '''decode''' ) else n for n in group.attrs['''%s%d''' % (name, chunk_id)]] )
chunk_id += 1
return data
def __UpperCamelCase ( a : Any ) ->List[Any]:
def _expand_single_ad_tensor(a : List[Any] ):
if isinstance(a , tf.Tensor ) and t.shape.rank == 1:
return tf.expand_dims(a , axis=-1 )
return t
return tf.nest.map_structure(_expand_single_ad_tensor , a )
| 342 | 0 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__a = logging.get_logger(__name__)
__a = {
'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json',
'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json',
'junnyu/roformer_chinese_char_small': (
'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json'
),
'junnyu/roformer_chinese_char_base': (
'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json'
),
'junnyu/roformer_small_discriminator': (
'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json'
),
'junnyu/roformer_small_generator': (
'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json'
),
# See all RoFormer models at https://huggingface.co/models?filter=roformer
}
class A__ ( _UpperCamelCase ):
"""simple docstring"""
UpperCamelCase_ : Dict = "roformer"
def __init__( self : Tuple , lowerCAmelCase__ : List[str]=5_0_0_0_0 , lowerCAmelCase__ : Union[str, Any]=None , lowerCAmelCase__ : Tuple=7_6_8 , lowerCAmelCase__ : Union[str, Any]=1_2 , lowerCAmelCase__ : Optional[Any]=1_2 , lowerCAmelCase__ : List[Any]=3_0_7_2 , lowerCAmelCase__ : Dict="gelu" , lowerCAmelCase__ : Optional[Any]=0.1 , lowerCAmelCase__ : Dict=0.1 , lowerCAmelCase__ : int=1_5_3_6 , lowerCAmelCase__ : Union[str, Any]=2 , lowerCAmelCase__ : Optional[int]=0.02 , lowerCAmelCase__ : int=1e-12 , lowerCAmelCase__ : List[str]=0 , lowerCAmelCase__ : Any=False , lowerCAmelCase__ : str=True , **lowerCAmelCase__ : Union[str, Any] , ) -> Optional[int]:
"""simple docstring"""
super().__init__(pad_token_id=__a , **__a )
_UpperCAmelCase : Any = vocab_size
_UpperCAmelCase : Optional[Any] = hidden_size if embedding_size is None else embedding_size
_UpperCAmelCase : str = hidden_size
_UpperCAmelCase : Optional[Any] = num_hidden_layers
_UpperCAmelCase : List[str] = num_attention_heads
_UpperCAmelCase : Optional[Any] = hidden_act
_UpperCAmelCase : Union[str, Any] = intermediate_size
_UpperCAmelCase : List[str] = hidden_dropout_prob
_UpperCAmelCase : Tuple = attention_probs_dropout_prob
_UpperCAmelCase : Any = max_position_embeddings
_UpperCAmelCase : Optional[Any] = type_vocab_size
_UpperCAmelCase : List[str] = initializer_range
_UpperCAmelCase : int = layer_norm_eps
_UpperCAmelCase : Optional[int] = rotary_value
_UpperCAmelCase : int = use_cache
class A__ ( _UpperCamelCase ):
"""simple docstring"""
@property
def _lowerCAmelCase ( self : str ) -> Mapping[str, Mapping[int, str]]:
"""simple docstring"""
if self.task == "multiple-choice":
_UpperCAmelCase : List[Any] = {0: "batch", 1: "choice", 2: "sequence"}
else:
_UpperCAmelCase : int = {0: "batch", 1: "sequence"}
_UpperCAmelCase : str = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
("token_type_ids", dynamic_axis),
] ) | 707 | '''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.
from argparse import ArgumentParser
from accelerate.commands.config import get_config_parser
from accelerate.commands.env import env_command_parser
from accelerate.commands.launch import launch_command_parser
from accelerate.commands.test import test_command_parser
from accelerate.commands.tpu import tpu_command_parser
def __UpperCAmelCase ( ):
_UpperCAmelCase : int = ArgumentParser("Accelerate CLI tool", usage="accelerate <command> [<args>]", allow_abbrev=a_ )
_UpperCAmelCase : Union[str, Any] = parser.add_subparsers(help="accelerate command helpers" )
# Register commands
get_config_parser(subparsers=a_ )
env_command_parser(subparsers=a_ )
launch_command_parser(subparsers=a_ )
tpu_command_parser(subparsers=a_ )
test_command_parser(subparsers=a_ )
# Let's go
_UpperCAmelCase : List[Any] = parser.parse_args()
if not hasattr(a_, "func" ):
parser.print_help()
exit(1 )
# Run
args.func(a_ )
if __name__ == "__main__":
main() | 257 | 0 |
import os
from typing import Dict, List, Tuple, TypeVar, Union
__magic_name__ = TypeVar("T")
__magic_name__ = Union[List[T], Tuple[T, ...]]
__magic_name__ = Union[T, List[T], Dict[str, T]]
__magic_name__ = Union[str, bytes, os.PathLike]
| 254 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bert import BertTokenizer
__magic_name__ = logging.get_logger(__name__)
__magic_name__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
__magic_name__ = {
"vocab_file": {
"bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt",
"bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt",
"bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/vocab.txt",
"bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/vocab.txt",
"bert-base-multilingual-uncased": (
"https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt"
),
"bert-base-multilingual-cased": "https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt",
"bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt",
"bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt",
"bert-large-uncased-whole-word-masking": (
"https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt"
),
"bert-large-cased-whole-word-masking": (
"https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt"
),
"bert-large-uncased-whole-word-masking-finetuned-squad": (
"https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"
),
"bert-large-cased-whole-word-masking-finetuned-squad": (
"https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"
),
"bert-base-cased-finetuned-mrpc": (
"https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt"
),
"bert-base-german-dbmdz-cased": "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt",
"bert-base-german-dbmdz-uncased": (
"https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt"
),
"TurkuNLP/bert-base-finnish-cased-v1": (
"https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt"
),
"TurkuNLP/bert-base-finnish-uncased-v1": (
"https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt"
),
"wietsedv/bert-base-dutch-cased": (
"https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json",
"bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json",
"bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json",
"bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json",
"bert-base-multilingual-uncased": (
"https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json"
),
"bert-base-multilingual-cased": (
"https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json"
),
"bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json",
"bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json",
"bert-large-uncased-whole-word-masking": (
"https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json"
),
"bert-large-cased-whole-word-masking": (
"https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json"
),
"bert-large-uncased-whole-word-masking-finetuned-squad": (
"https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"
),
"bert-large-cased-whole-word-masking-finetuned-squad": (
"https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"
),
"bert-base-cased-finetuned-mrpc": (
"https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json"
),
"bert-base-german-dbmdz-cased": (
"https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json"
),
"bert-base-german-dbmdz-uncased": (
"https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json"
),
"TurkuNLP/bert-base-finnish-cased-v1": (
"https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json"
),
"TurkuNLP/bert-base-finnish-uncased-v1": (
"https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json"
),
"wietsedv/bert-base-dutch-cased": (
"https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json"
),
},
}
__magic_name__ = {
"bert-base-uncased": 512,
"bert-large-uncased": 512,
"bert-base-cased": 512,
"bert-large-cased": 512,
"bert-base-multilingual-uncased": 512,
"bert-base-multilingual-cased": 512,
"bert-base-chinese": 512,
"bert-base-german-cased": 512,
"bert-large-uncased-whole-word-masking": 512,
"bert-large-cased-whole-word-masking": 512,
"bert-large-uncased-whole-word-masking-finetuned-squad": 512,
"bert-large-cased-whole-word-masking-finetuned-squad": 512,
"bert-base-cased-finetuned-mrpc": 512,
"bert-base-german-dbmdz-cased": 512,
"bert-base-german-dbmdz-uncased": 512,
"TurkuNLP/bert-base-finnish-cased-v1": 512,
"TurkuNLP/bert-base-finnish-uncased-v1": 512,
"wietsedv/bert-base-dutch-cased": 512,
}
__magic_name__ = {
"bert-base-uncased": {"do_lower_case": True},
"bert-large-uncased": {"do_lower_case": True},
"bert-base-cased": {"do_lower_case": False},
"bert-large-cased": {"do_lower_case": False},
"bert-base-multilingual-uncased": {"do_lower_case": True},
"bert-base-multilingual-cased": {"do_lower_case": False},
"bert-base-chinese": {"do_lower_case": False},
"bert-base-german-cased": {"do_lower_case": False},
"bert-large-uncased-whole-word-masking": {"do_lower_case": True},
"bert-large-cased-whole-word-masking": {"do_lower_case": False},
"bert-large-uncased-whole-word-masking-finetuned-squad": {"do_lower_case": True},
"bert-large-cased-whole-word-masking-finetuned-squad": {"do_lower_case": False},
"bert-base-cased-finetuned-mrpc": {"do_lower_case": False},
"bert-base-german-dbmdz-cased": {"do_lower_case": False},
"bert-base-german-dbmdz-uncased": {"do_lower_case": True},
"TurkuNLP/bert-base-finnish-cased-v1": {"do_lower_case": False},
"TurkuNLP/bert-base-finnish-uncased-v1": {"do_lower_case": True},
"wietsedv/bert-base-dutch-cased": {"do_lower_case": False},
}
class lowercase ( A__ ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE = PRETRAINED_INIT_CONFIGURATION
__SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__SCREAMING_SNAKE_CASE = BertTokenizer
def __init__( self , _snake_case=None , _snake_case=None , _snake_case=True , _snake_case="[UNK]" , _snake_case="[SEP]" , _snake_case="[PAD]" , _snake_case="[CLS]" , _snake_case="[MASK]" , _snake_case=True , _snake_case=None , **_snake_case , ) -> List[Any]:
"""simple docstring"""
super().__init__(
_snake_case , tokenizer_file=_snake_case , do_lower_case=_snake_case , unk_token=_snake_case , sep_token=_snake_case , pad_token=_snake_case , cls_token=_snake_case , mask_token=_snake_case , tokenize_chinese_chars=_snake_case , strip_accents=_snake_case , **_snake_case , )
UpperCAmelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get('''lowercase''' , _snake_case ) != do_lower_case
or normalizer_state.get('''strip_accents''' , _snake_case ) != strip_accents
or normalizer_state.get('''handle_chinese_chars''' , _snake_case ) != tokenize_chinese_chars
):
UpperCAmelCase = getattr(_snake_case , normalizer_state.pop('''type''' ) )
UpperCAmelCase = do_lower_case
UpperCAmelCase = strip_accents
UpperCAmelCase = tokenize_chinese_chars
UpperCAmelCase = normalizer_class(**_snake_case )
UpperCAmelCase = do_lower_case
def snake_case_ ( self , _snake_case , _snake_case=None ) -> Union[str, Any]:
"""simple docstring"""
UpperCAmelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def snake_case_ ( self , _snake_case , _snake_case = None ) -> List[int]:
"""simple docstring"""
UpperCAmelCase = [self.sep_token_id]
UpperCAmelCase = [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 snake_case_ ( self , _snake_case , _snake_case = None ) -> Tuple[str]:
"""simple docstring"""
UpperCAmelCase = self._tokenizer.model.save(_snake_case , name=_snake_case )
return tuple(_snake_case )
| 254 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
lowerCamelCase__ = {
"""configuration_chinese_clip""": [
"""CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""ChineseCLIPConfig""",
"""ChineseCLIPOnnxConfig""",
"""ChineseCLIPTextConfig""",
"""ChineseCLIPVisionConfig""",
],
"""processing_chinese_clip""": ["""ChineseCLIPProcessor"""],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase__ = ["""ChineseCLIPFeatureExtractor"""]
lowerCamelCase__ = ["""ChineseCLIPImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase__ = [
"""CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""ChineseCLIPModel""",
"""ChineseCLIPPreTrainedModel""",
"""ChineseCLIPTextModel""",
"""ChineseCLIPVisionModel""",
]
if TYPE_CHECKING:
from .configuration_chinese_clip import (
CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
ChineseCLIPConfig,
ChineseCLIPOnnxConfig,
ChineseCLIPTextConfig,
ChineseCLIPVisionConfig,
)
from .processing_chinese_clip import ChineseCLIPProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_chinese_clip import (
CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
ChineseCLIPModel,
ChineseCLIPPreTrainedModel,
ChineseCLIPTextModel,
ChineseCLIPVisionModel,
)
else:
import sys
lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 291 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
lowerCamelCase__ = {
"""configuration_canine""": ["""CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CanineConfig"""],
"""tokenization_canine""": ["""CanineTokenizer"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase__ = [
"""CANINE_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""CanineForMultipleChoice""",
"""CanineForQuestionAnswering""",
"""CanineForSequenceClassification""",
"""CanineForTokenClassification""",
"""CanineLayer""",
"""CanineModel""",
"""CaninePreTrainedModel""",
"""load_tf_weights_in_canine""",
]
if TYPE_CHECKING:
from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig
from .tokenization_canine import CanineTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_canine import (
CANINE_PRETRAINED_MODEL_ARCHIVE_LIST,
CanineForMultipleChoice,
CanineForQuestionAnswering,
CanineForSequenceClassification,
CanineForTokenClassification,
CanineLayer,
CanineModel,
CaninePreTrainedModel,
load_tf_weights_in_canine,
)
else:
import sys
lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 291 | 1 |
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available
if is_vision_available():
from PIL import Image
from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast
@require_vision
class a ( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase ( self : List[str] ) -> str:
__UpperCAmelCase : List[str] = tempfile.mkdtemp()
__UpperCAmelCase : Optional[int] = BlipImageProcessor()
__UpperCAmelCase : Any = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-BertModel""" )
__UpperCAmelCase : Optional[Any] = BlipProcessor(__lowercase , __lowercase )
processor.save_pretrained(self.tmpdirname )
def UpperCAmelCase ( self : int , **__lowercase : Optional[Any] ) -> Any:
return AutoProcessor.from_pretrained(self.tmpdirname , **__lowercase ).tokenizer
def UpperCAmelCase ( self : Optional[Any] , **__lowercase : int ) -> str:
return AutoProcessor.from_pretrained(self.tmpdirname , **__lowercase ).image_processor
def UpperCAmelCase ( self : int ) -> int:
shutil.rmtree(self.tmpdirname )
def UpperCAmelCase ( self : Union[str, Any] ) -> Dict:
__UpperCAmelCase : List[str] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
__UpperCAmelCase : List[Any] = [Image.fromarray(np.moveaxis(__lowercase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def UpperCAmelCase ( self : int ) -> Any:
__UpperCAmelCase : int = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
__UpperCAmelCase : str = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" )
__UpperCAmelCase : Optional[Any] = self.get_image_processor(do_normalize=__lowercase , padding_value=1.0 )
__UpperCAmelCase : List[str] = BlipProcessor.from_pretrained(
self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__lowercase , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , __lowercase )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , __lowercase )
def UpperCAmelCase ( self : List[Any] ) -> int:
__UpperCAmelCase : List[Any] = self.get_image_processor()
__UpperCAmelCase : Dict = self.get_tokenizer()
__UpperCAmelCase : Optional[Any] = BlipProcessor(tokenizer=__lowercase , image_processor=__lowercase )
__UpperCAmelCase : Dict = self.prepare_image_inputs()
__UpperCAmelCase : str = image_processor(__lowercase , return_tensors="""np""" )
__UpperCAmelCase : Dict = processor(images=__lowercase , return_tensors="""np""" )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 )
def UpperCAmelCase ( self : Union[str, Any] ) -> Dict:
__UpperCAmelCase : Optional[Any] = self.get_image_processor()
__UpperCAmelCase : Dict = self.get_tokenizer()
__UpperCAmelCase : Union[str, Any] = BlipProcessor(tokenizer=__lowercase , image_processor=__lowercase )
__UpperCAmelCase : str = """lower newer"""
__UpperCAmelCase : int = processor(text=__lowercase )
__UpperCAmelCase : Any = tokenizer(__lowercase , return_token_type_ids=__lowercase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def UpperCAmelCase ( self : Dict ) -> Any:
__UpperCAmelCase : Tuple = self.get_image_processor()
__UpperCAmelCase : Any = self.get_tokenizer()
__UpperCAmelCase : Dict = BlipProcessor(tokenizer=__lowercase , image_processor=__lowercase )
__UpperCAmelCase : Union[str, Any] = """lower newer"""
__UpperCAmelCase : Tuple = self.prepare_image_inputs()
__UpperCAmelCase : int = processor(text=__lowercase , images=__lowercase )
self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] )
# test if it raises when no input is passed
with pytest.raises(__lowercase ):
processor()
def UpperCAmelCase ( self : str ) -> List[Any]:
__UpperCAmelCase : Optional[Any] = self.get_image_processor()
__UpperCAmelCase : List[str] = self.get_tokenizer()
__UpperCAmelCase : Union[str, Any] = BlipProcessor(tokenizer=__lowercase , image_processor=__lowercase )
__UpperCAmelCase : str = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
__UpperCAmelCase : str = processor.batch_decode(__lowercase )
__UpperCAmelCase : Dict = tokenizer.batch_decode(__lowercase )
self.assertListEqual(__lowercase , __lowercase )
def UpperCAmelCase ( self : Tuple ) -> Optional[Any]:
__UpperCAmelCase : int = self.get_image_processor()
__UpperCAmelCase : List[str] = self.get_tokenizer()
__UpperCAmelCase : Dict = BlipProcessor(tokenizer=__lowercase , image_processor=__lowercase )
__UpperCAmelCase : List[Any] = """lower newer"""
__UpperCAmelCase : List[str] = self.prepare_image_inputs()
__UpperCAmelCase : Optional[Any] = processor(text=__lowercase , images=__lowercase )
# For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] )
| 63 |
from sklearn.metrics import matthews_corrcoef
import datasets
SCREAMING_SNAKE_CASE = '\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction. The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n'
SCREAMING_SNAKE_CASE = '\nArgs:\n predictions (list of int): Predicted labels, as returned by a model.\n references (list of int): Ground truth labels.\n sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n Example 1, a basic example with only predictions and references as inputs:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3])\n >>> print(round(results[\'matthews_correlation\'], 2))\n 0.54\n\n Example 2, the same example as above, but also including sample weights:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 3, 1, 1, 1, 2])\n >>> print(round(results[\'matthews_correlation\'], 2))\n 0.1\n\n Example 3, the same example as above, but with sample weights that cause a negative correlation:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 1, 0, 0, 0, 1])\n >>> print(round(results[\'matthews_correlation\'], 2))\n -0.25\n'
SCREAMING_SNAKE_CASE = '\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class A_ ( datasets.Metric ):
'''simple docstring'''
def snake_case__ ( self) -> Any:
"""simple docstring"""
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Value('''int32'''),
'''references''': datasets.Value('''int32'''),
}) , reference_urls=[
'''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html'''
] , )
def snake_case__ ( self , _A , _A , _A=None) -> Any:
"""simple docstring"""
return {
"matthews_correlation": float(matthews_corrcoef(_A , _A , sample_weight=_A)),
}
| 485 | 0 |
# This script creates a super tiny model that is useful inside tests, when we just want to test that
# the machinery works, without needing to the check the quality of the outcomes.
#
# This version creates a tiny model through reduction of a normal pre-trained model, but keeping the
# full vocab, merges file, and thus also resulting in a larger model due to a large vocab size.
# This gives ~3MB in total for all files.
#
# If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated
#
#
# It will be used then as "stas/tiny-wmt19-en-de"
# Build
from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration
A : Optional[int] = '''facebook/wmt19-en-de'''
A : Optional[Any] = FSMTTokenizer.from_pretrained(mname)
# get the correct vocab sizes, etc. from the master model
A : str = FSMTConfig.from_pretrained(mname)
config.update(
dict(
d_model=4,
encoder_layers=1,
decoder_layers=1,
encoder_ffn_dim=4,
decoder_ffn_dim=4,
encoder_attention_heads=1,
decoder_attention_heads=1,
)
)
A : Optional[Any] = FSMTForConditionalGeneration(config)
print(F'''num of params {tiny_model.num_parameters()}''')
# Test
A : Union[str, Any] = tokenizer(['''Making tiny model'''], return_tensors='''pt''')
A : Dict = tiny_model(**batch)
print('''test output:''', len(outputs.logits[0]))
# Save
A : int = '''tiny-wmt19-en-de'''
tiny_model.half() # makes it smaller
tiny_model.save_pretrained(mname_tiny)
tokenizer.save_pretrained(mname_tiny)
print(F'''Generated {mname_tiny}''')
# Upload
# transformers-cli upload tiny-wmt19-en-de
| 247 |
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
from accelerate import PartialState
from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce
def __lowerCamelCase ( __a :Dict ) -> List[Any]:
"""simple docstring"""
return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device )
def __lowerCamelCase ( __a :str ) -> int:
"""simple docstring"""
A__ = create_tensor(__a )
A__ = gather(__a )
assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) )
def __lowerCamelCase ( __a :Optional[Any] ) -> Optional[int]:
"""simple docstring"""
A__ = [state.process_index]
A__ = gather_object(__a )
assert len(__a ) == state.num_processes, F'{gathered_obj}, {len(__a )} != {state.num_processes}'
assert gathered_obj == list(range(state.num_processes ) ), F'{gathered_obj} != {list(range(state.num_processes ) )}'
def __lowerCamelCase ( __a :Optional[int] ) -> Dict:
"""simple docstring"""
A__ = create_tensor(__a )
A__ = broadcast(__a )
assert broadcasted_tensor.shape == torch.Size([state.num_processes] )
assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) )
def __lowerCamelCase ( __a :List[str] ) -> Tuple:
"""simple docstring"""
if state.is_main_process:
A__ = torch.arange(state.num_processes + 1 ).to(state.device )
else:
A__ = torch.arange(state.num_processes ).to(state.device )
A__ = pad_across_processes(__a )
assert padded_tensor.shape == torch.Size([state.num_processes + 1] )
if not state.is_main_process:
assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0]
def __lowerCamelCase ( __a :Optional[int] ) -> Tuple:
"""simple docstring"""
if state.num_processes != 2:
return
A__ = create_tensor(__a )
A__ = reduce(__a , """sum""" )
A__ = torch.tensor([4.0, 6] ).to(state.device )
assert torch.allclose(__a , __a ), F'{reduced_tensor} != {truth_tensor}'
def __lowerCamelCase ( __a :str ) -> List[str]:
"""simple docstring"""
if state.num_processes != 2:
return
A__ = create_tensor(__a )
A__ = reduce(__a , """mean""" )
A__ = torch.tensor([2.0, 3] ).to(state.device )
assert torch.allclose(__a , __a ), F'{reduced_tensor} != {truth_tensor}'
def __lowerCamelCase ( __a :List[Any] ) -> Union[str, Any]:
"""simple docstring"""
main()
def __lowerCamelCase ( ) -> List[str]:
"""simple docstring"""
A__ = PartialState()
state.print(F'State: {state}' )
state.print("""testing gather""" )
test_gather(__a )
state.print("""testing gather_object""" )
test_gather_object(__a )
state.print("""testing broadcast""" )
test_broadcast(__a )
state.print("""testing pad_across_processes""" )
test_pad_across_processes(__a )
state.print("""testing reduce_sum""" )
test_reduce_sum(__a )
state.print("""testing reduce_mean""" )
test_reduce_mean(__a )
if __name__ == "__main__":
main()
| 247 | 1 |
"""simple docstring"""
import json
import os
import torch
from diffusers import UNetaDModel
os.makedirs('hub/hopper-medium-v2/unet/hor32', exist_ok=True)
os.makedirs('hub/hopper-medium-v2/unet/hor128', exist_ok=True)
os.makedirs('hub/hopper-medium-v2/value_function', exist_ok=True)
def lowerCamelCase ( _UpperCamelCase : List[str] ) -> int:
'''simple docstring'''
if hor == 1_2_8:
__UpperCAmelCase : Optional[int] = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""")
__UpperCAmelCase : Tuple = (3_2, 1_2_8, 2_5_6)
__UpperCAmelCase : Optional[int] = ("""UpResnetBlock1D""", """UpResnetBlock1D""")
elif hor == 3_2:
__UpperCAmelCase : Union[str, Any] = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""")
__UpperCAmelCase : Any = (3_2, 6_4, 1_2_8, 2_5_6)
__UpperCAmelCase : str = ("""UpResnetBlock1D""", """UpResnetBlock1D""", """UpResnetBlock1D""")
__UpperCAmelCase : str = torch.load(f'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''' )
__UpperCAmelCase : Any = model.state_dict()
__UpperCAmelCase : Optional[int] = {
"""down_block_types""": down_block_types,
"""block_out_channels""": block_out_channels,
"""up_block_types""": up_block_types,
"""layers_per_block""": 1,
"""use_timestep_embedding""": True,
"""out_block_type""": """OutConv1DBlock""",
"""norm_num_groups""": 8,
"""downsample_each_block""": False,
"""in_channels""": 1_4,
"""out_channels""": 1_4,
"""extra_in_channels""": 0,
"""time_embedding_type""": """positional""",
"""flip_sin_to_cos""": False,
"""freq_shift""": 1,
"""sample_size""": 6_5_5_3_6,
"""mid_block_type""": """MidResTemporalBlock1D""",
"""act_fn""": """mish""",
}
__UpperCAmelCase : List[str] = UNetaDModel(**_UpperCamelCase )
print(f'''length of state dict: {len(state_dict.keys() )}''' )
print(f'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__UpperCAmelCase : List[str] = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__UpperCAmelCase : Tuple = state_dict.pop(_UpperCamelCase )
hf_value_function.load_state_dict(_UpperCamelCase )
torch.save(hf_value_function.state_dict() , f'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''' )
with open(f'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' , """w""" ) as f:
json.dump(_UpperCamelCase , _UpperCamelCase )
def lowerCamelCase ( ) -> Union[str, Any]:
'''simple docstring'''
__UpperCAmelCase : Dict = {
"""in_channels""": 1_4,
"""down_block_types""": ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D"""),
"""up_block_types""": (),
"""out_block_type""": """ValueFunction""",
"""mid_block_type""": """ValueFunctionMidBlock1D""",
"""block_out_channels""": (3_2, 6_4, 1_2_8, 2_5_6),
"""layers_per_block""": 1,
"""downsample_each_block""": True,
"""sample_size""": 6_5_5_3_6,
"""out_channels""": 1_4,
"""extra_in_channels""": 0,
"""time_embedding_type""": """positional""",
"""use_timestep_embedding""": True,
"""flip_sin_to_cos""": False,
"""freq_shift""": 1,
"""norm_num_groups""": 8,
"""act_fn""": """mish""",
}
__UpperCAmelCase : Any = torch.load("""/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch""" )
__UpperCAmelCase : int = model
__UpperCAmelCase : str = UNetaDModel(**_UpperCamelCase )
print(f'''length of state dict: {len(state_dict.keys() )}''' )
print(f'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__UpperCAmelCase : str = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__UpperCAmelCase : Optional[Any] = state_dict.pop(_UpperCamelCase )
hf_value_function.load_state_dict(_UpperCamelCase )
torch.save(hf_value_function.state_dict() , """hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin""" )
with open("""hub/hopper-medium-v2/value_function/config.json""" , """w""" ) as f:
json.dump(_UpperCamelCase , _UpperCamelCase )
if __name__ == "__main__":
unet(32)
# unet(128)
value_function()
| 139 |
"""simple docstring"""
import logging
import os
import sys
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional, Union
import datasets
import numpy as np
import torch
from datasets import load_dataset
import transformers
from transformers import (
AutoConfig,
AutoModelForMultipleChoice,
AutoTokenizer,
HfArgumentParser,
Trainer,
TrainingArguments,
default_data_collator,
set_seed,
)
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('4.31.0')
UpperCAmelCase : Dict = logging.getLogger(__name__)
@dataclass
class lowerCamelCase__ :
"""simple docstring"""
__a = field(
metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} )
__a = field(
default=A , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} )
__a = field(
default=A , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} )
__a = field(
default=A , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , )
__a = field(
default=A , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , )
__a = field(
default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , )
__a = field(
default=A , metadata={
"""help""": (
"""Will use the token generated when running `huggingface-cli login` (necessary to use this script """
"""with private models)."""
)
} , )
@dataclass
class lowerCamelCase__ :
"""simple docstring"""
__a = field(default=A , metadata={"""help""": """The input training data file (a text file)."""} )
__a = field(
default=A , metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""} , )
__a = field(
default=A , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} )
__a = field(
default=A , metadata={"""help""": """The number of processes to use for the preprocessing."""} , )
__a = field(
default=A , metadata={
"""help""": (
"""The maximum total input sequence length after tokenization. If passed, sequences longer """
"""than this will be truncated, sequences shorter will be padded."""
)
} , )
__a = field(
default=A , metadata={
"""help""": (
"""Whether to pad all samples to the maximum sentence length. """
"""If False, will pad the samples dynamically when batching to the maximum length in the batch. More """
"""efficient on GPU but very bad for TPU."""
)
} , )
__a = field(
default=A , metadata={
"""help""": (
"""For debugging purposes or quicker training, truncate the number of training examples to this """
"""value if set."""
)
} , )
__a = field(
default=A , metadata={
"""help""": (
"""For debugging purposes or quicker training, truncate the number of evaluation examples to this """
"""value if set."""
)
} , )
def lowerCamelCase__ ( self : Union[str, Any] ):
'''simple docstring'''
if self.train_file is not None:
__UpperCAmelCase : List[Any] = self.train_file.split(""".""" )[-1]
assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
if self.validation_file is not None:
__UpperCAmelCase : List[str] = self.validation_file.split(""".""" )[-1]
assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
@dataclass
class lowerCamelCase__ :
"""simple docstring"""
__a = 42
__a = True
__a = None
__a = None
def __call__( self : Tuple , UpperCamelCase : str ):
'''simple docstring'''
__UpperCAmelCase : List[str] = """label""" if """label""" in features[0].keys() else """labels"""
__UpperCAmelCase : Union[str, Any] = [feature.pop(UpperCamelCase ) for feature in features]
__UpperCAmelCase : str = len(UpperCamelCase )
__UpperCAmelCase : Dict = len(features[0]["""input_ids"""] )
__UpperCAmelCase : int = [
[{k: v[i] for k, v in feature.items()} for i in range(UpperCamelCase )] for feature in features
]
__UpperCAmelCase : str = list(chain(*UpperCamelCase ) )
__UpperCAmelCase : int = self.tokenizer.pad(
UpperCamelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="""pt""" , )
# Un-flatten
__UpperCAmelCase : Optional[Any] = {k: v.view(UpperCamelCase , UpperCamelCase , -1 ) for k, v in batch.items()}
# Add back labels
__UpperCAmelCase : int = torch.tensor(UpperCamelCase , dtype=torch.intaa )
return batch
def lowerCamelCase ( ) -> Any:
'''simple docstring'''
__UpperCAmelCase : List[Any] = 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.
__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase : Optional[int] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase : Dict = parser.parse_args_into_dataclasses()
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("""run_swag""" , _UpperCamelCase , _UpperCamelCase )
# 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 )] , )
if training_args.should_log:
# The default of training_args.log_level is passive, so we set log level at info here to have that default.
transformers.utils.logging.set_verbosity_info()
__UpperCAmelCase : Any = training_args.get_process_log_level()
logger.setLevel(_UpperCamelCase )
datasets.utils.logging.set_verbosity(_UpperCamelCase )
transformers.utils.logging.set_verbosity(_UpperCamelCase )
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# 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}''' )
logger.info(f'''Training/evaluation parameters {training_args}''' )
# Detecting last checkpoint.
__UpperCAmelCase : Dict = None
if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
__UpperCAmelCase : Any = 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 and training_args.resume_from_checkpoint is 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.""" )
# Set seed before initializing model.
set_seed(training_args.seed )
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
# In distributed training, the load_dataset function guarantee that only one local process can concurrently
# download the dataset.
if data_args.train_file is not None or data_args.validation_file is not None:
__UpperCAmelCase : str = {}
if data_args.train_file is not None:
__UpperCAmelCase : str = data_args.train_file
if data_args.validation_file is not None:
__UpperCAmelCase : Union[str, Any] = data_args.validation_file
__UpperCAmelCase : List[Any] = data_args.train_file.split(""".""" )[-1]
__UpperCAmelCase : Optional[int] = load_dataset(
_UpperCamelCase , data_files=_UpperCamelCase , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
else:
# Downloading and loading the swag dataset from the hub.
__UpperCAmelCase : Any = load_dataset(
"""swag""" , """regular""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Load pretrained model and tokenizer
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
__UpperCAmelCase : Dict = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
__UpperCAmelCase : Union[str, Any] = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
__UpperCAmelCase : Dict = AutoModelForMultipleChoice.from_pretrained(
model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=_UpperCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
# When using your own dataset or a different dataset from swag, you will probably need to change this.
__UpperCAmelCase : Dict = [f'''ending{i}''' for i in range(4 )]
__UpperCAmelCase : Any = """sent1"""
__UpperCAmelCase : List[str] = """sent2"""
if data_args.max_seq_length is None:
__UpperCAmelCase : List[str] = tokenizer.model_max_length
if max_seq_length > 1_0_2_4:
logger.warning(
"""The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value"""
""" of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can"""
""" override this default with `--block_size xxx`.""" )
__UpperCAmelCase : str = 1_0_2_4
else:
if data_args.max_seq_length > tokenizer.model_max_length:
logger.warning(
f'''The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the'''
f'''model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.''' )
__UpperCAmelCase : Optional[Any] = min(data_args.max_seq_length , tokenizer.model_max_length )
# Preprocessing the datasets.
def preprocess_function(_UpperCamelCase : str ):
__UpperCAmelCase : List[str] = [[context] * 4 for context in examples[context_name]]
__UpperCAmelCase : Union[str, Any] = examples[question_header_name]
__UpperCAmelCase : int = [
[f'''{header} {examples[end][i]}''' for end in ending_names] for i, header in enumerate(_UpperCamelCase )
]
# Flatten out
__UpperCAmelCase : List[str] = list(chain(*_UpperCamelCase ) )
__UpperCAmelCase : List[Any] = list(chain(*_UpperCamelCase ) )
# Tokenize
__UpperCAmelCase : Optional[int] = tokenizer(
_UpperCamelCase , _UpperCamelCase , truncation=_UpperCamelCase , max_length=_UpperCamelCase , padding="""max_length""" if data_args.pad_to_max_length else False , )
# Un-flatten
return {k: [v[i : i + 4] for i in range(0 , len(_UpperCamelCase ) , 4 )] for k, v in tokenized_examples.items()}
if training_args.do_train:
if "train" not in raw_datasets:
raise ValueError("""--do_train requires a train dataset""" )
__UpperCAmelCase : List[Any] = raw_datasets["""train"""]
if data_args.max_train_samples is not None:
__UpperCAmelCase : Optional[int] = min(len(_UpperCamelCase ) , data_args.max_train_samples )
__UpperCAmelCase : Union[str, Any] = train_dataset.select(range(_UpperCamelCase ) )
with training_args.main_process_first(desc="""train dataset map pre-processing""" ):
__UpperCAmelCase : List[str] = train_dataset.map(
_UpperCamelCase , batched=_UpperCamelCase , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , )
if training_args.do_eval:
if "validation" not in raw_datasets:
raise ValueError("""--do_eval requires a validation dataset""" )
__UpperCAmelCase : int = raw_datasets["""validation"""]
if data_args.max_eval_samples is not None:
__UpperCAmelCase : Dict = min(len(_UpperCamelCase ) , data_args.max_eval_samples )
__UpperCAmelCase : Any = eval_dataset.select(range(_UpperCamelCase ) )
with training_args.main_process_first(desc="""validation dataset map pre-processing""" ):
__UpperCAmelCase : Any = eval_dataset.map(
_UpperCamelCase , batched=_UpperCamelCase , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , )
# Data collator
__UpperCAmelCase : Optional[int] = (
default_data_collator
if data_args.pad_to_max_length
else DataCollatorForMultipleChoice(tokenizer=_UpperCamelCase , pad_to_multiple_of=8 if training_args.fpaa else None )
)
# Metric
def compute_metrics(_UpperCamelCase : Dict ):
__UpperCAmelCase ,__UpperCAmelCase : List[str] = eval_predictions
__UpperCAmelCase : Optional[int] = np.argmax(_UpperCamelCase , axis=1 )
return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()}
# Initialize our Trainer
__UpperCAmelCase : Tuple = Trainer(
model=_UpperCamelCase , args=_UpperCamelCase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=_UpperCamelCase , data_collator=_UpperCamelCase , compute_metrics=_UpperCamelCase , )
# Training
if training_args.do_train:
__UpperCAmelCase : str = None
if training_args.resume_from_checkpoint is not None:
__UpperCAmelCase : Dict = training_args.resume_from_checkpoint
elif last_checkpoint is not None:
__UpperCAmelCase : List[str] = last_checkpoint
__UpperCAmelCase : Any = trainer.train(resume_from_checkpoint=_UpperCamelCase )
trainer.save_model() # Saves the tokenizer too for easy upload
__UpperCAmelCase : Dict = train_result.metrics
__UpperCAmelCase : List[str] = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(_UpperCamelCase )
)
__UpperCAmelCase : List[Any] = min(_UpperCamelCase , len(_UpperCamelCase ) )
trainer.log_metrics("""train""" , _UpperCamelCase )
trainer.save_metrics("""train""" , _UpperCamelCase )
trainer.save_state()
# Evaluation
if training_args.do_eval:
logger.info("""*** Evaluate ***""" )
__UpperCAmelCase : List[str] = trainer.evaluate()
__UpperCAmelCase : Any = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(_UpperCamelCase )
__UpperCAmelCase : Union[str, Any] = min(_UpperCamelCase , len(_UpperCamelCase ) )
trainer.log_metrics("""eval""" , _UpperCamelCase )
trainer.save_metrics("""eval""" , _UpperCamelCase )
__UpperCAmelCase : Tuple = {
"""finetuned_from""": model_args.model_name_or_path,
"""tasks""": """multiple-choice""",
"""dataset_tags""": """swag""",
"""dataset_args""": """regular""",
"""dataset""": """SWAG""",
"""language""": """en""",
}
if training_args.push_to_hub:
trainer.push_to_hub(**_UpperCamelCase )
else:
trainer.create_model_card(**_UpperCamelCase )
def lowerCamelCase ( _UpperCamelCase : int ) -> Union[str, Any]:
'''simple docstring'''
main()
if __name__ == "__main__":
main()
| 139 | 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 DetaImageProcessor
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def __init__(self , _lowercase , _lowercase=7 , _lowercase=3 , _lowercase=30 , _lowercase=400 , _lowercase=True , _lowercase=None , _lowercase=True , _lowercase=[0.5, 0.5, 0.5] , _lowercase=[0.5, 0.5, 0.5] , _lowercase=True , _lowercase=1 / 255 , _lowercase=True , ):
'''simple docstring'''
__a : Optional[Any] = size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 1333}
__a : Union[str, Any] = parent
__a : int = batch_size
__a : Optional[int] = num_channels
__a : Any = min_resolution
__a : str = max_resolution
__a : Union[str, Any] = do_resize
__a : List[str] = size
__a : Any = do_normalize
__a : Tuple = image_mean
__a : Tuple = image_std
__a : List[str] = do_rescale
__a : List[str] = rescale_factor
__a : int = do_pad
def lowerCAmelCase__(self ):
'''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,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_pad": self.do_pad,
}
def lowerCAmelCase__(self , _lowercase , _lowercase=False ):
'''simple docstring'''
if not batched:
__a : Tuple = image_inputs[0]
if isinstance(_lowercase , Image.Image ):
__a , __a : Tuple = image.size
else:
__a , __a : Optional[Any] = image.shape[1], image.shape[2]
if w < h:
__a : Union[str, Any] = int(self.size["""shortest_edge"""] * h / w )
__a : Optional[int] = self.size["""shortest_edge"""]
elif w > h:
__a : str = self.size["""shortest_edge"""]
__a : Union[str, Any] = int(self.size["""shortest_edge"""] * w / h )
else:
__a : Optional[Any] = self.size["""shortest_edge"""]
__a : Optional[int] = self.size["""shortest_edge"""]
else:
__a : List[Any] = []
for image in image_inputs:
__a , __a : int = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
__a : Optional[int] = max(_lowercase , key=lambda _lowercase : item[0] )[0]
__a : Union[str, Any] = max(_lowercase , key=lambda _lowercase : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , unittest.TestCase ):
_lowerCAmelCase = DetaImageProcessor if is_vision_available() else None
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : str = DetaImageProcessingTester(self )
@property
def lowerCAmelCase__(self ):
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowercase , """image_mean""" ) )
self.assertTrue(hasattr(_lowercase , """image_std""" ) )
self.assertTrue(hasattr(_lowercase , """do_normalize""" ) )
self.assertTrue(hasattr(_lowercase , """do_resize""" ) )
self.assertTrue(hasattr(_lowercase , """do_rescale""" ) )
self.assertTrue(hasattr(_lowercase , """do_pad""" ) )
self.assertTrue(hasattr(_lowercase , """size""" ) )
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Any = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"""shortest_edge""": 18, """longest_edge""": 1333} )
self.assertEqual(image_processor.do_pad , _lowercase )
def lowerCAmelCase__(self ):
'''simple docstring'''
pass
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : List[str] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__a : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowercase )
for image in image_inputs:
self.assertIsInstance(_lowercase , Image.Image )
# Test not batched input
__a : Tuple = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values
__a , __a : List[str] = self.image_processor_tester.get_expected_values(_lowercase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__a , __a : Dict = self.image_processor_tester.get_expected_values(_lowercase , batched=_lowercase )
__a : int = image_processing(_lowercase , 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 lowerCAmelCase__(self ):
'''simple docstring'''
__a : Tuple = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__a : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowercase , numpify=_lowercase )
for image in image_inputs:
self.assertIsInstance(_lowercase , np.ndarray )
# Test not batched input
__a : Any = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values
__a , __a : List[Any] = self.image_processor_tester.get_expected_values(_lowercase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__a : Optional[int] = image_processing(_lowercase , return_tensors="""pt""" ).pixel_values
__a , __a : Union[str, Any] = self.image_processor_tester.get_expected_values(_lowercase , batched=_lowercase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Tuple = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__a : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowercase , torchify=_lowercase )
for image in image_inputs:
self.assertIsInstance(_lowercase , torch.Tensor )
# Test not batched input
__a : List[Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values
__a , __a : Tuple = self.image_processor_tester.get_expected_values(_lowercase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__a : Union[str, Any] = image_processing(_lowercase , return_tensors="""pt""" ).pixel_values
__a , __a : Union[str, Any] = self.image_processor_tester.get_expected_values(_lowercase , batched=_lowercase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
@slow
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" , """r""" ) as f:
__a : Union[str, Any] = json.loads(f.read() )
__a : Optional[int] = {"""image_id""": 39769, """annotations""": target}
# encode them
__a : Union[str, Any] = DetaImageProcessor()
__a : str = image_processing(images=_lowercase , annotations=_lowercase , return_tensors="""pt""" )
# verify pixel values
__a : str = torch.Size([1, 3, 800, 1066] )
self.assertEqual(encoding["""pixel_values"""].shape , _lowercase )
__a : Optional[int] = torch.tensor([0.2796, 0.3138, 0.3481] )
self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , _lowercase , atol=1e-4 ) )
# verify area
__a : int = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , _lowercase ) )
# verify boxes
__a : List[str] = torch.Size([6, 4] )
self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , _lowercase )
__a : Tuple = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , _lowercase , atol=1e-3 ) )
# verify image_id
__a : List[Any] = torch.tensor([39769] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , _lowercase ) )
# verify is_crowd
__a : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , _lowercase ) )
# verify class_labels
__a : int = torch.tensor([75, 75, 63, 65, 17, 17] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , _lowercase ) )
# verify orig_size
__a : Dict = torch.tensor([480, 640] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , _lowercase ) )
# verify size
__a : Dict = torch.tensor([800, 1066] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , _lowercase ) )
@slow
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Tuple = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" , """r""" ) as f:
__a : List[Any] = json.loads(f.read() )
__a : Dict = {"""file_name""": """000000039769.png""", """image_id""": 39769, """segments_info""": target}
__a : Union[str, Any] = pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" )
# encode them
__a : Union[str, Any] = DetaImageProcessor(format="""coco_panoptic""" )
__a : List[Any] = image_processing(images=_lowercase , annotations=_lowercase , masks_path=_lowercase , return_tensors="""pt""" )
# verify pixel values
__a : Optional[int] = torch.Size([1, 3, 800, 1066] )
self.assertEqual(encoding["""pixel_values"""].shape , _lowercase )
__a : Optional[Any] = torch.tensor([0.2796, 0.3138, 0.3481] )
self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , _lowercase , atol=1e-4 ) )
# verify area
__a : Optional[Any] = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , _lowercase ) )
# verify boxes
__a : Tuple = torch.Size([6, 4] )
self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , _lowercase )
__a : str = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , _lowercase , atol=1e-3 ) )
# verify image_id
__a : Optional[Any] = torch.tensor([39769] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , _lowercase ) )
# verify is_crowd
__a : str = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , _lowercase ) )
# verify class_labels
__a : Optional[int] = torch.tensor([17, 17, 63, 75, 75, 93] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , _lowercase ) )
# verify masks
__a : List[str] = 822873
self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() , _lowercase )
# verify orig_size
__a : List[str] = torch.tensor([480, 640] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , _lowercase ) )
# verify size
__a : Optional[Any] = torch.tensor([800, 1066] )
self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , _lowercase ) )
| 716 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowercase__ = logging.get_logger(__name__)
lowercase__ = {
"sayakpaul/vit-msn-base": "https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json",
# See all ViT MSN models at https://huggingface.co/models?filter=vit_msn
}
class SCREAMING_SNAKE_CASE__ ( __snake_case ):
_lowerCAmelCase = "vit_msn"
def __init__(self , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3072 , _lowercase="gelu" , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.02 , _lowercase=1e-06 , _lowercase=224 , _lowercase=16 , _lowercase=3 , _lowercase=True , **_lowercase , ):
'''simple docstring'''
super().__init__(**_lowercase )
__a : int = hidden_size
__a : str = num_hidden_layers
__a : str = num_attention_heads
__a : Optional[Any] = intermediate_size
__a : Union[str, Any] = hidden_act
__a : Tuple = hidden_dropout_prob
__a : Any = attention_probs_dropout_prob
__a : List[Any] = initializer_range
__a : Any = layer_norm_eps
__a : Dict = image_size
__a : List[Any] = patch_size
__a : Dict = num_channels
__a : Optional[Any] = qkv_bias
| 63 | 0 |
import argparse
import json
import os
import re
import shutil
import torch
from transformers import BioGptConfig, BioGptForCausalLM
from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES
from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE
from transformers.utils import WEIGHTS_NAME, logging
logging.set_verbosity_warning()
SCREAMING_SNAKE_CASE :Optional[int] = 2
class UpperCAmelCase :
'''simple docstring'''
def __init__( self : Dict ,*, # begin keyword-only arguments
A : Tuple="<s>" ,A : Optional[Any]="<pad>" ,A : Tuple="</s>" ,A : Tuple="<unk>" ,A : Union[str, Any]=None ,):
__A , __A , __A , __A = bos, unk, pad, eos
__A = []
__A = []
__A = {}
__A = self.add_symbol(A )
__A = self.add_symbol(A )
__A = self.add_symbol(A )
__A = self.add_symbol(A )
if extra_special_symbols:
for s in extra_special_symbols:
self.add_symbol(A )
__A = len(self.symbols )
def __eq__( self : Any ,A : str ):
return self.indices == other.indices
def __getitem__( self : int ,A : Tuple ):
if idx < len(self.symbols ):
return self.symbols[idx]
return self.unk_word
def __len__( self : Any ):
return len(self.symbols )
def __contains__( self : Optional[Any] ,A : Optional[int] ):
return sym in self.indices
@classmethod
def UpperCamelCase_ ( cls : Any ,A : Union[str, Any] ):
__A = cls()
d.add_from_file(A )
return d
def UpperCamelCase_ ( self : Union[str, Any] ,A : Optional[Any] ,A : str=1 ,A : int=False ):
if word in self.indices and not overwrite:
__A = self.indices[word]
__A = self.count[idx] + n
return idx
else:
__A = len(self.symbols )
__A = idx
self.symbols.append(A )
self.count.append(A )
return idx
def UpperCamelCase_ ( self : Dict ,A : Optional[int] ):
return 0
def UpperCamelCase_ ( self : Dict ,A : List[Any] ):
if isinstance(A ,A ):
try:
with open(A ,"r" ,encoding="utf-8" ) as fd:
self.add_from_file(A )
except FileNotFoundError as fnfe:
raise fnfe
except UnicodeError:
raise Exception("Incorrect encoding detected in {}, please rebuild the dataset".format(A ) )
return
__A = f.readlines()
__A = self._load_meta(A )
for line in lines[indices_start_line:]:
try:
__A , __A = line.rstrip().rsplit(" " ,1 )
if field == "#fairseq:overwrite":
__A = True
__A , __A = line.rsplit(" " ,1 )
else:
__A = False
__A = int(A )
__A = line
if word in self and not overwrite:
raise RuntimeError(
"Duplicate word found when loading Dictionary: '{}'. "
"Duplicate words can overwrite earlier ones by adding the "
"#fairseq:overwrite flag at the end of the corresponding row "
"in the dictionary file. If using the Camembert model, please "
"download an updated copy of the model file.".format(A ) )
self.add_symbol(A ,n=A ,overwrite=A )
except ValueError:
raise ValueError("Incorrect dictionary format, expected '<token> <cnt> [flags]'" )
def UpperCAmelCase ( a_ ) -> List[str]:
"""simple docstring"""
__A = dict((re.sub(r"@@$" , "" , a_ ), v) if k.endswith("@@" ) else (re.sub(r"$" , "</w>" , a_ ), v) for k, v in d.items() )
__A = "<s> <pad> </s> <unk>".split()
# restore the special tokens
for k in keep_keys:
del da[F'''{k}</w>''']
__A = d[k] # restore
return da
def UpperCAmelCase ( a_ , a_ ) -> List[str]:
"""simple docstring"""
if not os.path.exists(a_ ):
raise ValueError(F'''path {biogpt_checkpoint_path} does not exist!''' )
os.makedirs(a_ , exist_ok=a_ )
print(F'''Writing results to {pytorch_dump_folder_path}''' )
# handle various types of models
__A = os.path.join(a_ , "checkpoint.pt" )
if not os.path.isfile(a_ ):
raise ValueError(F'''path to the file {checkpoint_file} does not exist!''' )
__A = torch.load(a_ , map_location="cpu" )
__A = chkpt["cfg"]["model"]
# dicts
__A = os.path.join(a_ , "dict.txt" )
if not os.path.isfile(a_ ):
raise ValueError(F'''path to the file {dict_file} does not exist!''' )
__A = Dictionary.load(a_ )
__A = rewrite_dict_keys(src_dict.indices )
__A = len(a_ )
__A = os.path.join(a_ , VOCAB_FILES_NAMES["vocab_file"] )
print(F'''Generating {src_vocab_file} of {src_vocab_size} records''' )
with open(a_ , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(a_ , ensure_ascii=a_ , indent=a_ ) )
# merges_file (bpecodes)
__A = os.path.join(a_ , "bpecodes" )
if not os.path.isfile(a_ ):
raise ValueError(F'''path to the file {bpecodes_file} does not exist!''' )
__A = os.path.join(a_ , VOCAB_FILES_NAMES["merges_file"] )
shutil.copyfile(a_ , a_ )
# model config
__A = os.path.join(a_ , "config.json" )
__A = {
"activation_dropout": args["activation_dropout"],
"architectures": ["BioGptForCausalLM"],
"attention_probs_dropout_prob": args["attention_dropout"],
"bos_token_id": 0,
"eos_token_id": 2,
"hidden_act": args["activation_fn"],
"hidden_dropout_prob": args["dropout"],
"hidden_size": args["decoder_embed_dim"],
"initializer_range": 0.02,
"intermediate_size": args["decoder_ffn_embed_dim"],
"layer_norm_eps": 1E-12,
"layerdrop": args["decoder_layerdrop"],
"max_position_embeddings": args["max_target_positions"],
"model_type": "biogpt",
"num_attention_heads": args["decoder_attention_heads"],
"num_hidden_layers": args["decoder_layers"],
"pad_token_id": 1,
"scale_embedding": not args["no_scale_embedding"],
"tie_word_embeddings": args["share_decoder_input_output_embed"],
"vocab_size": src_vocab_size,
}
# good hparam defaults to start with
print(F'''Generating {biogpt_model_config_file}''' )
with open(a_ , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(a_ , ensure_ascii=a_ , indent=a_ ) )
# tokenizer config
__A = os.path.join(a_ , a_ )
__A = {
"bos_token": "<s>",
"eos_token": "</s>",
"model_max_length": 1_0_2_4,
"pad_token": "<pad>",
"special_tokens_map_file": None,
"tokenizer_class": "BioGptTokenizer",
"unk_token": "<unk>",
}
print(F'''Generating {biogpt_tokenizer_config_file}''' )
with open(a_ , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(a_ , ensure_ascii=a_ , indent=a_ ) )
# model
__A = chkpt["model"]
# remove unneeded keys
__A = [
"decoder.version",
]
for k in ignore_keys:
model_state_dict.pop(a_ , a_ )
__A = list(model_state_dict.keys() )
for layer_name in layer_names:
if layer_name.endswith("output_projection.weight" ):
__A = model_state_dict.pop(a_ )
else:
__A = model_state_dict.pop(a_ )
__A = BioGptConfig.from_pretrained(a_ )
__A = BioGptForCausalLM(a_ )
# check that it loads ok
model_new.load_state_dict(a_ )
# save
__A = os.path.join(a_ , a_ )
print(F'''Generating {pytorch_weights_dump_path}''' )
torch.save(a_ , a_ )
print("Conversion is done!" )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE :Dict = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--biogpt_checkpoint_path',
default=None,
type=str,
required=True,
help=(
'Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,'
' bpecodes, etc.'
),
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
)
SCREAMING_SNAKE_CASE :List[Any] = parser.parse_args()
convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
| 55 |
import qiskit
def snake_case (UpperCamelCase : int = 2 ):
'''simple docstring'''
lowerCamelCase__ = qubits
# Using Aer's simulator
lowerCamelCase__ = qiskit.Aer.get_backend("""aer_simulator""" )
# Creating a Quantum Circuit acting on the q register
lowerCamelCase__ = qiskit.QuantumCircuit(UpperCamelCase , UpperCamelCase )
# Adding a H gate on qubit 0 (now q0 in superposition)
circuit.h(0 )
for i in range(1 , UpperCamelCase ):
# Adding CX (CNOT) gate
circuit.cx(i - 1 , UpperCamelCase )
# Mapping the quantum measurement to the classical bits
circuit.measure(list(range(UpperCamelCase ) ) , list(range(UpperCamelCase ) ) )
# Now measuring any one qubit would affect other qubits to collapse
# their super position and have same state as the measured one.
# Executing the circuit on the simulator
lowerCamelCase__ = qiskit.execute(UpperCamelCase , UpperCamelCase , shots=1000 )
return job.result().get_counts(UpperCamelCase )
if __name__ == "__main__":
print(f'''Total count for various states are: {quantum_entanglement(3)}''')
| 165 | 0 |
"""simple docstring"""
import torch
from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel
class lowerCamelCase (_SCREAMING_SNAKE_CASE ):
'''simple docstring'''
a = "M-CLIP"
def __init__( self : int , _snake_case : int=1024 , _snake_case : Optional[int]=768 , **_snake_case : str ) -> List[str]:
SCREAMING_SNAKE_CASE__ = transformerDimSize
SCREAMING_SNAKE_CASE__ = imageDimSize
super().__init__(**_snake_case )
class lowerCamelCase (_SCREAMING_SNAKE_CASE ):
'''simple docstring'''
a = MCLIPConfig
def __init__( self : Optional[Any] , _snake_case : Dict , *_snake_case : int , **_snake_case : List[Any] ) -> Union[str, Any]:
super().__init__(_snake_case , *_snake_case , **_snake_case )
SCREAMING_SNAKE_CASE__ = XLMRobertaModel(_snake_case )
SCREAMING_SNAKE_CASE__ = torch.nn.Linear(
in_features=config.transformerDimensions , out_features=config.numDims )
def lowerCAmelCase_ ( self : Union[str, Any] , _snake_case : Dict , _snake_case : List[str] ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE__ = self.transformer(input_ids=_snake_case , attention_mask=_snake_case )[0]
SCREAMING_SNAKE_CASE__ = (embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None]
return self.LinearTransformation(_snake_case ), embs
| 704 | """simple docstring"""
from typing import TYPE_CHECKING
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
_A = {'configuration_van': ['VAN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VanConfig']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_A = [
'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
_A = _LazyModule(__name__, globals()['__file__'], _import_structure)
| 538 | 0 |
'''simple docstring'''
from __future__ import annotations
__lowerCamelCase : Any = 'Muhammad Umer Farooq'
__lowerCamelCase : Optional[int] = 'MIT'
__lowerCamelCase : str = '1.0.0'
__lowerCamelCase : Optional[int] = 'Muhammad Umer Farooq'
__lowerCamelCase : Any = 'contact@muhammadumerfarooq.me'
__lowerCamelCase : Any = 'Alpha'
import re
from html.parser import HTMLParser
from urllib import parse
import requests
class UpperCAmelCase ( lowercase_):
"""simple docstring"""
def __init__( self : str , UpperCamelCase__ : str ) -> None:
super().__init__()
_UpperCamelCase =[]
_UpperCamelCase =domain
def UpperCamelCase__ ( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : list[tuple[str, str | None]] ) -> None:
# Only parse the 'anchor' tag.
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, and not empty nor # print it.
if name == "href" and value != "#" and value != "":
# If not already in urls.
if value not in self.urls:
_UpperCamelCase =parse.urljoin(self.domain , UpperCamelCase__ )
self.urls.append(UpperCamelCase__ )
def _a (__SCREAMING_SNAKE_CASE ):
"""simple docstring"""
return ".".join(get_sub_domain_name(__SCREAMING_SNAKE_CASE ).split('''.''' )[-2:] )
def _a (__SCREAMING_SNAKE_CASE ):
"""simple docstring"""
return parse.urlparse(__SCREAMING_SNAKE_CASE ).netloc
def _a (__SCREAMING_SNAKE_CASE = "https://github.com" ):
"""simple docstring"""
_UpperCamelCase =get_domain_name(__SCREAMING_SNAKE_CASE )
# Initialize the parser
_UpperCamelCase =Parser(__SCREAMING_SNAKE_CASE )
try:
# Open URL
_UpperCamelCase =requests.get(__SCREAMING_SNAKE_CASE )
# pass the raw HTML to the parser to get links
parser.feed(r.text )
# Get links and loop through
_UpperCamelCase =set()
for link in parser.urls:
# open URL.
# read = requests.get(link)
try:
_UpperCamelCase =requests.get(__SCREAMING_SNAKE_CASE )
# Get the valid email.
_UpperCamelCase =re.findall('''[a-zA-Z0-9]+@''' + domain , read.text )
# If not in list then append it.
for email in emails:
valid_emails.add(__SCREAMING_SNAKE_CASE )
except ValueError:
pass
except ValueError:
raise SystemExit(1 )
# Finally return a sorted list of email addresses with no duplicates.
return sorted(__SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
__lowerCamelCase : Union[str, Any] = emails_from_url('https://github.com')
print(F"""{len(emails)} emails found:""")
print('\n'.join(sorted(emails)))
| 404 |
'''simple docstring'''
import importlib.metadata
import operator
import re
import sys
from typing import Optional
from packaging import version
__lowerCamelCase : List[str] = {
'<': operator.lt,
'<=': operator.le,
'==': operator.eq,
'!=': operator.ne,
'>=': operator.ge,
'>': operator.gt,
}
def _a (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
"""simple docstring"""
if got_ver is None or want_ver is None:
raise ValueError(
f'''Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider'''
f''' reinstalling {pkg}.''' )
if not ops[op](version.parse(__SCREAMING_SNAKE_CASE ) , version.parse(__SCREAMING_SNAKE_CASE ) ):
raise ImportError(
f'''{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}''' )
def _a (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ):
"""simple docstring"""
_UpperCamelCase =f'''\n{hint}''' if hint is not None else ''''''
# non-versioned check
if re.match(r'''^[\w_\-\d]+$''' , __SCREAMING_SNAKE_CASE ):
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase =requirement, None, None
else:
_UpperCamelCase =re.findall(r'''^([^!=<>\s]+)([\s!=<>]{1,2}.+)''' , __SCREAMING_SNAKE_CASE )
if not match:
raise ValueError(
'''requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but'''
f''' got {requirement}''' )
_UpperCamelCase , _UpperCamelCase =match[0]
_UpperCamelCase =want_full.split(''',''' ) # there could be multiple requirements
_UpperCamelCase ={}
for w in want_range:
_UpperCamelCase =re.findall(r'''^([\s!=<>]{1,2})(.+)''' , __SCREAMING_SNAKE_CASE )
if not match:
raise ValueError(
'''requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,'''
f''' but got {requirement}''' )
_UpperCamelCase , _UpperCamelCase =match[0]
_UpperCamelCase =want_ver
if op not in ops:
raise ValueError(f'''{requirement}: need one of {list(ops.keys() )}, but got {op}''' )
# special case
if pkg == "python":
_UpperCamelCase ='''.'''.join([str(__SCREAMING_SNAKE_CASE ) for x in sys.version_info[:3]] )
for op, want_ver in wanted.items():
_compare_versions(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
return
# check if any version is installed
try:
_UpperCamelCase =importlib.metadata.version(__SCREAMING_SNAKE_CASE )
except importlib.metadata.PackageNotFoundError:
raise importlib.metadata.PackageNotFoundError(
f'''The \'{requirement}\' distribution was not found and is required by this application. {hint}''' )
# check that the right version is installed if version number or a range was provided
if want_ver is not None:
for op, want_ver in wanted.items():
_compare_versions(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
def _a (__SCREAMING_SNAKE_CASE ):
"""simple docstring"""
_UpperCamelCase ='''Try: pip install transformers -U or pip install -e \'.[dev]\' if you\'re working with git main'''
return require_version(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
| 404 | 1 |
def _lowerCAmelCase ( __lowerCamelCase : int ):
"""simple docstring"""
return 1 if digit in (0, 1) else (digit * factorial(digit - 1 ))
def _lowerCAmelCase ( __lowerCamelCase : int ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Dict = 0
__SCREAMING_SNAKE_CASE : int = number
while duplicate > 0:
__SCREAMING_SNAKE_CASE : Union[str, Any] = divmod(__lowerCamelCase , 10 )
fact_sum += factorial(__lowerCamelCase )
return fact_sum == number
if __name__ == "__main__":
print("""Program to check whether a number is a Krisnamurthy Number or not.""")
_lowerCamelCase = int(input("""Enter number: """).strip())
print(
f'''{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number.'''
)
| 719 |
import io
import math
from typing import Dict, Optional, Union
import numpy as np
from huggingface_hub import hf_hub_download
from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
ChannelDimension,
ImageInput,
get_image_size,
infer_channel_dimension_format,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_torch_available, is_vision_available, logging
from ...utils.import_utils import requires_backends
if is_vision_available():
import textwrap
from PIL import Image, ImageDraw, ImageFont
if is_torch_available():
import torch
from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
_lowerCamelCase = False
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = """ybelkada/fonts"""
def _lowerCAmelCase ( ):
"""simple docstring"""
if is_torch_available() and not is_torch_greater_or_equal_than_1_11:
raise ImportError(
F"""You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use """
"Pix2StructImageProcessor. Please upgrade torch." )
def _lowerCAmelCase ( __lowerCamelCase : List[str] , __lowerCamelCase : int , __lowerCamelCase : Dict ):
"""simple docstring"""
requires_backends(__lowerCamelCase , ["torch"] )
_check_torch_version()
__SCREAMING_SNAKE_CASE : List[Any] = image_tensor.unsqueeze(0 )
__SCREAMING_SNAKE_CASE : Optional[Any] = torch.nn.functional.unfold(__lowerCamelCase , (patch_height, patch_width) , stride=(patch_height, patch_width) )
__SCREAMING_SNAKE_CASE : List[Any] = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , __lowerCamelCase , __lowerCamelCase , -1 )
__SCREAMING_SNAKE_CASE : Any = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape(
image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , )
return patches.unsqueeze(0 )
def _lowerCAmelCase ( __lowerCamelCase : str , __lowerCamelCase : int = 36 , __lowerCamelCase : str = "black" , __lowerCamelCase : str = "white" , __lowerCamelCase : int = 5 , __lowerCamelCase : int = 5 , __lowerCamelCase : int = 5 , __lowerCamelCase : int = 5 , __lowerCamelCase : Optional[bytes] = None , __lowerCamelCase : Optional[str] = None , ):
"""simple docstring"""
requires_backends(__lowerCamelCase , "vision" )
# Add new lines so that each line is no more than 80 characters.
__SCREAMING_SNAKE_CASE : Union[str, Any] = textwrap.TextWrapper(width=80 )
__SCREAMING_SNAKE_CASE : Optional[Any] = wrapper.wrap(text=__lowerCamelCase )
__SCREAMING_SNAKE_CASE : str = "\n".join(__lowerCamelCase )
if font_bytes is not None and font_path is None:
__SCREAMING_SNAKE_CASE : List[Any] = io.BytesIO(__lowerCamelCase )
elif font_path is not None:
__SCREAMING_SNAKE_CASE : Union[str, Any] = font_path
else:
__SCREAMING_SNAKE_CASE : Tuple = hf_hub_download(__lowerCamelCase , "Arial.TTF" )
__SCREAMING_SNAKE_CASE : List[Any] = ImageFont.truetype(__lowerCamelCase , encoding="UTF-8" , size=__lowerCamelCase )
# Use a temporary canvas to determine the width and height in pixels when
# rendering the text.
__SCREAMING_SNAKE_CASE : str = ImageDraw.Draw(Image.new("RGB" , (1, 1) , __lowerCamelCase ) )
__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = temp_draw.textbbox((0, 0) , __lowerCamelCase , __lowerCamelCase )
# Create the actual image with a bit of padding around the text.
__SCREAMING_SNAKE_CASE : Union[str, Any] = text_width + left_padding + right_padding
__SCREAMING_SNAKE_CASE : Tuple = text_height + top_padding + bottom_padding
__SCREAMING_SNAKE_CASE : Tuple = Image.new("RGB" , (image_width, image_height) , __lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = ImageDraw.Draw(__lowerCamelCase )
draw.text(xy=(left_padding, top_padding) , text=__lowerCamelCase , fill=__lowerCamelCase , font=__lowerCamelCase )
return image
def _lowerCAmelCase ( __lowerCamelCase : np.ndarray , __lowerCamelCase : str , **__lowerCamelCase : Union[str, Any] ):
"""simple docstring"""
requires_backends(__lowerCamelCase , "vision" )
# Convert to PIL image if necessary
__SCREAMING_SNAKE_CASE : int = to_pil_image(__lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = render_text(__lowerCamelCase , **__lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = max(header_image.width , image.width )
__SCREAMING_SNAKE_CASE : Tuple = int(image.height * (new_width / image.width) )
__SCREAMING_SNAKE_CASE : Any = int(header_image.height * (new_width / header_image.width) )
__SCREAMING_SNAKE_CASE : Tuple = Image.new("RGB" , (new_width, new_height + new_header_height) , "white" )
new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) )
new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) )
# Convert back to the original framework if necessary
__SCREAMING_SNAKE_CASE : Dict = to_numpy_array(__lowerCamelCase )
if infer_channel_dimension_format(__lowerCamelCase ) == ChannelDimension.LAST:
__SCREAMING_SNAKE_CASE : Any = to_channel_dimension_format(__lowerCamelCase , ChannelDimension.LAST )
return new_image
class _SCREAMING_SNAKE_CASE (UpperCamelCase ):
lowerCAmelCase = ["""flattened_patches"""]
def __init__( self : Tuple , UpperCamelCase : bool = True , UpperCamelCase : bool = True , UpperCamelCase : Dict[str, int] = None , UpperCamelCase : int = 2_0_4_8 , UpperCamelCase : bool = False , **UpperCamelCase : Optional[int] , )->None:
super().__init__(**UpperCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = patch_size if patch_size is not None else {"height": 1_6, "width": 1_6}
__SCREAMING_SNAKE_CASE : List[Any] = do_normalize
__SCREAMING_SNAKE_CASE : List[Any] = do_convert_rgb
__SCREAMING_SNAKE_CASE : List[str] = max_patches
__SCREAMING_SNAKE_CASE : List[Any] = is_vqa
def __snake_case ( self : Tuple , UpperCamelCase : np.ndarray , UpperCamelCase : int , UpperCamelCase : dict , **UpperCamelCase : Tuple )->np.ndarray:
requires_backends(self.extract_flattened_patches , "torch" )
_check_torch_version()
# convert to torch
__SCREAMING_SNAKE_CASE : Optional[Any] = to_channel_dimension_format(UpperCamelCase , ChannelDimension.FIRST )
__SCREAMING_SNAKE_CASE : int = torch.from_numpy(UpperCamelCase )
__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[str] = patch_size["height"], patch_size["width"]
__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[Any] = get_image_size(UpperCamelCase )
# maximize scale s.t.
__SCREAMING_SNAKE_CASE : List[str] = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) )
__SCREAMING_SNAKE_CASE : List[str] = max(min(math.floor(scale * image_height / patch_height ) , UpperCamelCase ) , 1 )
__SCREAMING_SNAKE_CASE : Tuple = max(min(math.floor(scale * image_width / patch_width ) , UpperCamelCase ) , 1 )
__SCREAMING_SNAKE_CASE : List[str] = max(num_feasible_rows * patch_height , 1 )
__SCREAMING_SNAKE_CASE : int = max(num_feasible_cols * patch_width , 1 )
__SCREAMING_SNAKE_CASE : Any = torch.nn.functional.interpolate(
image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="bilinear" , align_corners=UpperCamelCase , antialias=UpperCamelCase , ).squeeze(0 )
# [1, rows, columns, patch_height * patch_width * image_channels]
__SCREAMING_SNAKE_CASE : List[str] = torch_extract_patches(UpperCamelCase , UpperCamelCase , UpperCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = patches.shape
__SCREAMING_SNAKE_CASE : int = patches_shape[1]
__SCREAMING_SNAKE_CASE : List[str] = patches_shape[2]
__SCREAMING_SNAKE_CASE : List[str] = patches_shape[3]
# [rows * columns, patch_height * patch_width * image_channels]
__SCREAMING_SNAKE_CASE : Union[str, Any] = patches.reshape([rows * columns, depth] )
# [rows * columns, 1]
__SCREAMING_SNAKE_CASE : Any = torch.arange(UpperCamelCase ).reshape([rows, 1] ).repeat(1 , UpperCamelCase ).reshape([rows * columns, 1] )
__SCREAMING_SNAKE_CASE : Optional[int] = torch.arange(UpperCamelCase ).reshape([1, columns] ).repeat(UpperCamelCase , 1 ).reshape([rows * columns, 1] )
# Offset by 1 so the ids do not contain zeros, which represent padding.
row_ids += 1
col_ids += 1
# Prepare additional patch features.
# [rows * columns, 1]
__SCREAMING_SNAKE_CASE : str = row_ids.to(torch.floataa )
__SCREAMING_SNAKE_CASE : int = col_ids.to(torch.floataa )
# [rows * columns, 2 + patch_height * patch_width * image_channels]
__SCREAMING_SNAKE_CASE : Optional[int] = torch.cat([row_ids, col_ids, patches] , -1 )
# [max_patches, 2 + patch_height * patch_width * image_channels]
__SCREAMING_SNAKE_CASE : Any = torch.nn.functional.pad(UpperCamelCase , [0, 0, 0, max_patches - (rows * columns)] ).float()
__SCREAMING_SNAKE_CASE : str = to_numpy_array(UpperCamelCase )
return result
def __snake_case ( self : Optional[Any] , UpperCamelCase : np.ndarray , UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase : Optional[int] )->np.ndarray:
if image.dtype == np.uinta:
__SCREAMING_SNAKE_CASE : Optional[int] = image.astype(np.floataa )
# take mean across the whole `image`
__SCREAMING_SNAKE_CASE : int = np.mean(UpperCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = np.std(UpperCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = max(UpperCamelCase , 1.0 / math.sqrt(np.prod(image.shape ) ) )
return normalize(UpperCamelCase , mean=UpperCamelCase , std=UpperCamelCase , **UpperCamelCase )
def __snake_case ( self : Union[str, Any] , UpperCamelCase : ImageInput , UpperCamelCase : Optional[str] = None , UpperCamelCase : bool = None , UpperCamelCase : Optional[bool] = None , UpperCamelCase : Optional[int] = None , UpperCamelCase : Optional[Dict[str, int]] = None , UpperCamelCase : Optional[Union[str, TensorType]] = None , UpperCamelCase : ChannelDimension = ChannelDimension.FIRST , **UpperCamelCase : Dict , )->ImageInput:
__SCREAMING_SNAKE_CASE : int = do_normalize if do_normalize is not None else self.do_normalize
__SCREAMING_SNAKE_CASE : Optional[Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
__SCREAMING_SNAKE_CASE : List[Any] = patch_size if patch_size is not None else self.patch_size
__SCREAMING_SNAKE_CASE : List[str] = max_patches if max_patches is not None else self.max_patches
__SCREAMING_SNAKE_CASE : List[Any] = self.is_vqa
if kwargs.get("data_format" , UpperCamelCase ) is not None:
raise ValueError("data_format is not an accepted input as the outputs are " )
__SCREAMING_SNAKE_CASE : Union[str, Any] = 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." )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
__SCREAMING_SNAKE_CASE : Optional[int] = [convert_to_rgb(UpperCamelCase ) for image in images]
# All transformations expect numpy arrays.
__SCREAMING_SNAKE_CASE : str = [to_numpy_array(UpperCamelCase ) for image in images]
if is_vqa:
if header_text is None:
raise ValueError("A header text must be provided for VQA models." )
__SCREAMING_SNAKE_CASE : Any = kwargs.pop("font_bytes" , UpperCamelCase )
__SCREAMING_SNAKE_CASE : Any = kwargs.pop("font_path" , UpperCamelCase )
if isinstance(UpperCamelCase , UpperCamelCase ):
__SCREAMING_SNAKE_CASE : Dict = [header_text] * len(UpperCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = [
render_header(UpperCamelCase , header_text[i] , font_bytes=UpperCamelCase , font_path=UpperCamelCase )
for i, image in enumerate(UpperCamelCase )
]
if do_normalize:
__SCREAMING_SNAKE_CASE : List[str] = [self.normalize(image=UpperCamelCase ) for image in images]
# convert to torch tensor and permute
__SCREAMING_SNAKE_CASE : str = [
self.extract_flattened_patches(image=UpperCamelCase , max_patches=UpperCamelCase , patch_size=UpperCamelCase )
for image in images
]
# create attention mask in numpy
__SCREAMING_SNAKE_CASE : List[Any] = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images]
__SCREAMING_SNAKE_CASE : Dict = BatchFeature(
data={"flattened_patches": images, "attention_mask": attention_masks} , tensor_type=UpperCamelCase )
return encoded_outputs
| 447 | 0 |
'''simple docstring'''
from __future__ import annotations
import sys
from collections import deque
from typing import Generic, TypeVar
__magic_name__ = TypeVar('T')
class __lowerCAmelCase ( Generic[T] ):
'''simple docstring'''
a_ = 42 # Cache store of keys
a_ = 42 # References of the keys in cache
a_ = 10 # Maximum capacity of cache
def __init__( self : Optional[int] ,_a : int ):
'''simple docstring'''
A_ : Optional[Any] = deque()
A_ : List[str] = set()
if not n:
A_ : List[str] = sys.maxsize
elif n < 0:
raise ValueError("""n should be an integer greater than 0.""" )
else:
A_ : Tuple = n
def _a ( self : int ,_a : T ):
'''simple docstring'''
if x not in self.key_reference:
if len(self.dq_store ) == LRUCache._MAX_CAPACITY:
A_ : Dict = self.dq_store.pop()
self.key_reference.remove(_a )
else:
self.dq_store.remove(_a )
self.dq_store.appendleft(_a )
self.key_reference.add(_a )
def _a ( self : List[Any] ):
'''simple docstring'''
for k in self.dq_store:
print(_a )
def __repr__( self : Optional[int] ):
'''simple docstring'''
return f'LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}'
if __name__ == "__main__":
import doctest
doctest.testmod()
__magic_name__ = LRUCache(4)
lru_cache.refer('A')
lru_cache.refer(2)
lru_cache.refer(3)
lru_cache.refer('A')
lru_cache.refer(4)
lru_cache.refer(5)
lru_cache.display()
print(lru_cache)
assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
| 665 |
'''simple docstring'''
from math import acos, sin
from typing import List, Tuple, Union
import numpy as np
import torch
from PIL import Image
from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel
class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
a_ = ["""vqvae"""]
def __init__( self : Optional[Any] ,_a : AutoencoderKL ,_a : UNetaDConditionModel ,_a : Mel ,_a : Union[DDIMScheduler, DDPMScheduler] ,):
'''simple docstring'''
super().__init__()
self.register_modules(unet=_a ,scheduler=_a ,mel=_a ,vqvae=_a )
def _a ( self : str ):
'''simple docstring'''
return 50 if isinstance(self.scheduler ,_a ) else 1000
@torch.no_grad()
def __call__( self : Optional[int] ,_a : int = 1 ,_a : str = None ,_a : np.ndarray = None ,_a : int = 0 ,_a : int = 0 ,_a : int = None ,_a : torch.Generator = None ,_a : float = 0 ,_a : float = 0 ,_a : torch.Generator = None ,_a : float = 0 ,_a : torch.Tensor = None ,_a : torch.Tensor = None ,_a : int=True ,):
'''simple docstring'''
A_ : List[str] = steps or self.get_default_steps()
self.scheduler.set_timesteps(_a )
A_ : Union[str, Any] = step_generator or generator
# For backwards compatibility
if type(self.unet.config.sample_size ) == int:
A_ : Tuple = (self.unet.config.sample_size, self.unet.config.sample_size)
if noise is None:
A_ : int = randn_tensor(
(
batch_size,
self.unet.config.in_channels,
self.unet.config.sample_size[0],
self.unet.config.sample_size[1],
) ,generator=_a ,device=self.device ,)
A_ : List[Any] = noise
A_ : str = None
if audio_file is not None or raw_audio is not None:
self.mel.load_audio(_a ,_a )
A_ : Any = self.mel.audio_slice_to_image(_a )
A_ : Union[str, Any] = np.frombuffer(input_image.tobytes() ,dtype="""uint8""" ).reshape(
(input_image.height, input_image.width) )
A_ : Optional[Any] = (input_image / 255) * 2 - 1
A_ : Union[str, Any] = torch.tensor(input_image[np.newaxis, :, :] ,dtype=torch.float ).to(self.device )
if self.vqvae is not None:
A_ : Union[str, Any] = self.vqvae.encode(torch.unsqueeze(_a ,0 ) ).latent_dist.sample(
generator=_a )[0]
A_ : List[str] = self.vqvae.config.scaling_factor * input_images
if start_step > 0:
A_ : Any = self.scheduler.add_noise(_a ,_a ,self.scheduler.timesteps[start_step - 1] )
A_ : Tuple = (
self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
)
A_ : Tuple = int(mask_start_secs * pixels_per_second )
A_ : str = int(mask_end_secs * pixels_per_second )
A_ : int = self.scheduler.add_noise(_a ,_a ,torch.tensor(self.scheduler.timesteps[start_step:] ) )
for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ):
if isinstance(self.unet ,_a ):
A_ : Optional[Any] = self.unet(_a ,_a ,_a )["""sample"""]
else:
A_ : List[Any] = self.unet(_a ,_a )["""sample"""]
if isinstance(self.scheduler ,_a ):
A_ : Dict = self.scheduler.step(
model_output=_a ,timestep=_a ,sample=_a ,eta=_a ,generator=_a ,)["""prev_sample"""]
else:
A_ : Any = self.scheduler.step(
model_output=_a ,timestep=_a ,sample=_a ,generator=_a ,)["""prev_sample"""]
if mask is not None:
if mask_start > 0:
A_ : Tuple = mask[:, step, :, :mask_start]
if mask_end > 0:
A_ : List[str] = mask[:, step, :, -mask_end:]
if self.vqvae is not None:
# 0.18215 was scaling factor used in training to ensure unit variance
A_ : str = 1 / self.vqvae.config.scaling_factor * images
A_ : Union[str, Any] = self.vqvae.decode(_a )["""sample"""]
A_ : int = (images / 2 + 0.5).clamp(0 ,1 )
A_ : str = images.cpu().permute(0 ,2 ,3 ,1 ).numpy()
A_ : Optional[int] = (images * 255).round().astype("""uint8""" )
A_ : List[Any] = list(
(Image.fromarray(_[:, :, 0] ) for _ in images)
if images.shape[3] == 1
else (Image.fromarray(_a ,mode="""RGB""" ).convert("""L""" ) for _ in images) )
A_ : Tuple = [self.mel.image_to_audio(_a ) for _ in images]
if not return_dict:
return images, (self.mel.get_sample_rate(), audios)
return BaseOutput(**AudioPipelineOutput(np.array(_a )[:, np.newaxis, :] ) ,**ImagePipelineOutput(_a ) )
@torch.no_grad()
def _a ( self : Union[str, Any] ,_a : List[Image.Image] ,_a : int = 50 ):
'''simple docstring'''
assert isinstance(self.scheduler ,_a )
self.scheduler.set_timesteps(_a )
A_ : Optional[Any] = np.array(
[np.frombuffer(image.tobytes() ,dtype="""uint8""" ).reshape((1, image.height, image.width) ) for image in images] )
A_ : List[str] = (sample / 255) * 2 - 1
A_ : Optional[int] = torch.Tensor(_a ).to(self.device )
for t in self.progress_bar(torch.flip(self.scheduler.timesteps ,(0,) ) ):
A_ : List[str] = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
A_ : Any = self.scheduler.alphas_cumprod[t]
A_ : List[Any] = (
self.scheduler.alphas_cumprod[prev_timestep]
if prev_timestep >= 0
else self.scheduler.final_alpha_cumprod
)
A_ : str = 1 - alpha_prod_t
A_ : List[str] = self.unet(_a ,_a )["""sample"""]
A_ : str = (1 - alpha_prod_t_prev) ** 0.5 * model_output
A_ : Union[str, Any] = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
A_ : Optional[int] = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output
return sample
@staticmethod
def _a ( _a : torch.Tensor ,_a : torch.Tensor ,_a : float ):
'''simple docstring'''
A_ : List[Any] = acos(torch.dot(torch.flatten(_a ) ,torch.flatten(_a ) ) / torch.norm(_a ) / torch.norm(_a ) )
return sin((1 - alpha) * theta ) * xa / sin(_a ) + sin(alpha * theta ) * xa / sin(_a )
| 665 | 1 |
from random import randint
from tempfile import TemporaryFile
import numpy as np
def a_ ( lowerCAmelCase_ : Optional[Any], lowerCAmelCase_ : Union[str, Any], lowerCAmelCase_ : int ):
__lowerCAmelCase = 0
if start < end:
__lowerCAmelCase = randint(lowerCAmelCase__, lowerCAmelCase__ )
__lowerCAmelCase = a[end]
__lowerCAmelCase = a[pivot]
__lowerCAmelCase = temp
__lowerCAmelCase , __lowerCAmelCase = _in_place_partition(lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__ )
count += _in_place_quick_sort(lowerCAmelCase__, lowerCAmelCase__, p - 1 )
count += _in_place_quick_sort(lowerCAmelCase__, p + 1, lowerCAmelCase__ )
return count
def a_ ( lowerCAmelCase_ : Dict, lowerCAmelCase_ : Union[str, Any], lowerCAmelCase_ : List[str] ):
__lowerCAmelCase = 0
__lowerCAmelCase = randint(lowerCAmelCase__, lowerCAmelCase__ )
__lowerCAmelCase = a[end]
__lowerCAmelCase = a[pivot]
__lowerCAmelCase = temp
__lowerCAmelCase = start - 1
for index in range(lowerCAmelCase__, lowerCAmelCase__ ):
count += 1
if a[index] < a[end]: # check if current val is less than pivot value
__lowerCAmelCase = new_pivot_index + 1
__lowerCAmelCase = a[new_pivot_index]
__lowerCAmelCase = a[index]
__lowerCAmelCase = temp
__lowerCAmelCase = a[new_pivot_index + 1]
__lowerCAmelCase = a[end]
__lowerCAmelCase = temp
return new_pivot_index + 1, count
_snake_case : Optional[int] = TemporaryFile()
_snake_case : Optional[int] = 100 # 1000 elements are to be sorted
_snake_case , _snake_case : List[str] = 0, 1 # mean and standard deviation
_snake_case : List[Any] = np.random.normal(mu, sigma, p)
np.save(outfile, X)
print('The array is')
print(X)
outfile.seek(0) # using the same array
_snake_case : List[str] = np.load(outfile)
_snake_case : str = len(M) - 1
_snake_case : int = _in_place_quick_sort(M, 0, r)
print(
'No of Comparisons for 100 elements selected from a standard normal distribution'
'is :'
)
print(z)
| 714 |
import pytest
import requests
from datasets.utils.file_utils import http_head
from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline
@pytest.mark.integration
def a_ ( ):
with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ):
with pytest.raises(lowerCAmelCase_ ):
requests.request('GET', 'https://huggingface.co' )
with pytest.raises(requests.exceptions.ConnectTimeout ):
requests.request('GET', 'https://huggingface.co', timeout=1.0 )
@pytest.mark.integration
def a_ ( ):
with offline(OfflineSimulationMode.CONNECTION_FAILS ):
with pytest.raises(requests.exceptions.ConnectionError ):
requests.request('GET', 'https://huggingface.co' )
def a_ ( ):
with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ):
with pytest.raises(lowerCAmelCase_ ):
http_head('https://huggingface.co' )
| 421 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
A = {
"""configuration_deberta""": ["""DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DebertaConfig""", """DebertaOnnxConfig"""],
"""tokenization_deberta""": ["""DebertaTokenizer"""],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A = ["""DebertaTokenizerFast"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A = [
"""DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""DebertaForMaskedLM""",
"""DebertaForQuestionAnswering""",
"""DebertaForSequenceClassification""",
"""DebertaForTokenClassification""",
"""DebertaModel""",
"""DebertaPreTrainedModel""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A = [
"""TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFDebertaForMaskedLM""",
"""TFDebertaForQuestionAnswering""",
"""TFDebertaForSequenceClassification""",
"""TFDebertaForTokenClassification""",
"""TFDebertaModel""",
"""TFDebertaPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig
from .tokenization_deberta import DebertaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_deberta_fast import DebertaTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_deberta import (
DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
DebertaForMaskedLM,
DebertaForQuestionAnswering,
DebertaForSequenceClassification,
DebertaForTokenClassification,
DebertaModel,
DebertaPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_deberta import (
TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
TFDebertaForMaskedLM,
TFDebertaForQuestionAnswering,
TFDebertaForSequenceClassification,
TFDebertaForTokenClassification,
TFDebertaModel,
TFDebertaPreTrainedModel,
)
else:
import sys
A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 77 |
from ....configuration_utils import PretrainedConfig
from ....utils import logging
SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE__ : Any = {
"""Visual-Attention-Network/van-base""": (
"""https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json"""
),
}
class UpperCAmelCase_ ( __lowerCamelCase ):
__lowerCamelCase = 'van'
def __init__( self , _lowerCAmelCase=224 , _lowerCAmelCase=3 , _lowerCAmelCase=[7, 3, 3, 3] , _lowerCAmelCase=[4, 2, 2, 2] , _lowerCAmelCase=[64, 128, 320, 512] , _lowerCAmelCase=[3, 3, 12, 3] , _lowerCAmelCase=[8, 8, 4, 4] , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=1e-6 , _lowerCAmelCase=1e-2 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0 , **_lowerCAmelCase , ):
super().__init__(**_lowerCAmelCase )
UpperCAmelCase__ : Tuple = image_size
UpperCAmelCase__ : Optional[Any] = num_channels
UpperCAmelCase__ : Optional[int] = patch_sizes
UpperCAmelCase__ : int = strides
UpperCAmelCase__ : Optional[int] = hidden_sizes
UpperCAmelCase__ : str = depths
UpperCAmelCase__ : Optional[Any] = mlp_ratios
UpperCAmelCase__ : List[Any] = hidden_act
UpperCAmelCase__ : Tuple = initializer_range
UpperCAmelCase__ : Any = layer_norm_eps
UpperCAmelCase__ : List[Any] = layer_scale_init_value
UpperCAmelCase__ : int = drop_path_rate
UpperCAmelCase__ : Dict = dropout_rate
| 79 | 0 |
import unittest
from transformers import CamembertTokenizer, CamembertTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.utils import is_torch_available
from ...test_tokenization_common import TokenizerTesterMixin
lowercase__ :Any = get_tests_dir("fixtures/test_sentencepiece.model")
lowercase__ :Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece_bpe.model")
lowercase__ :Any = """pt""" if is_torch_available() else """tf"""
@require_sentencepiece
@require_tokenizers
class lowercase ( snake_case_ , unittest.TestCase ):
lowercase_ : Dict =CamembertTokenizer
lowercase_ : Dict =CamembertTokenizerFast
lowercase_ : Any =True
lowercase_ : List[str] =True
def A__ ( self):
super().setUp()
# We have a SentencePiece fixture for testing
lowercase = CamembertTokenizer(A__)
tokenizer.save_pretrained(self.tmpdirname)
def A__ ( self):
lowercase = '''<pad>'''
lowercase = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(A__) ,A__)
self.assertEqual(self.get_tokenizer()._convert_id_to_token(A__) ,A__)
def A__ ( self):
lowercase = list(self.get_tokenizer().get_vocab().keys())
self.assertEqual(vocab_keys[0] ,'''<s>NOTUSED''')
self.assertEqual(vocab_keys[1] ,'''<pad>''')
self.assertEqual(vocab_keys[-1] ,'''<mask>''')
self.assertEqual(len(A__) ,1_0_0_4)
def A__ ( self):
self.assertEqual(self.get_tokenizer().vocab_size ,1_0_0_5)
def A__ ( self):
lowercase = CamembertTokenizer(A__)
tokenizer.save_pretrained(self.tmpdirname)
lowercase = CamembertTokenizerFast.from_pretrained(self.tmpdirname)
lowercase = '''I was born in 92000, and this is falsé.'''
lowercase = tokenizer.encode(A__)
lowercase = rust_tokenizer.encode(A__)
self.assertListEqual(A__ ,A__)
lowercase = tokenizer.encode(A__ ,add_special_tokens=A__)
lowercase = rust_tokenizer.encode(A__ ,add_special_tokens=A__)
self.assertListEqual(A__ ,A__)
# <unk> tokens are not the same for `rust` than for `slow`.
# Because spm gives back raw token instead of `unk` in EncodeAsPieces
# tokens = tokenizer.tokenize(sequence)
lowercase = tokenizer.convert_ids_to_tokens(A__)
lowercase = rust_tokenizer.tokenize(A__)
self.assertListEqual(A__ ,A__)
def A__ ( self):
if not self.test_rust_tokenizer:
return
lowercase = self.get_tokenizer()
lowercase = self.get_rust_tokenizer()
lowercase = '''I was born in 92000, and this is falsé.'''
lowercase = tokenizer.tokenize(A__)
lowercase = rust_tokenizer.tokenize(A__)
self.assertListEqual(A__ ,A__)
lowercase = tokenizer.encode(A__ ,add_special_tokens=A__)
lowercase = rust_tokenizer.encode(A__ ,add_special_tokens=A__)
self.assertListEqual(A__ ,A__)
lowercase = self.get_rust_tokenizer()
lowercase = tokenizer.encode(A__)
lowercase = rust_tokenizer.encode(A__)
self.assertListEqual(A__ ,A__)
@slow
def A__ ( self):
# fmt: off
lowercase = {'''input_ids''': [[5, 5_4, 7_1_9_6, 2_9_7, 3_0, 2_3, 7_7_6, 1_8, 1_1, 3_2_1_5, 3_7_0_5, 8_2_5_2, 2_2, 3_1_6_4, 1_1_8_1, 2_1_1_6, 2_9, 1_6, 8_1_3, 2_5, 7_9_1, 3_3_1_4, 2_0, 3_4_4_6, 3_8, 2_7_5_7_5, 1_2_0, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_6_8, 1_7, 1_1, 9_0_8_8, 2_0, 1_5_1_7, 8, 2_2_8_0_4, 1_8_8_1_8, 1_0, 3_8, 6_2_9, 6_0_7, 6_0_7, 1_4_2, 1_9, 7_1_9_6, 8_6_7, 5_6, 1_0_3_2_6, 2_4, 2_2_6_7, 2_0, 4_1_6, 5_0_7_2, 1_5_6_1_2, 2_3_3, 7_3_4, 7, 2_3_9_9, 2_7, 1_6, 3_0_1_5, 1_6_4_9, 7, 2_4, 2_0, 4_3_3_8, 2_3_9_9, 2_7, 1_3, 3_4_0_0, 1_4, 1_3, 6_1_8_9, 8, 9_3_0, 9, 6]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501
# fmt: on
# camembert is a french model. So we also use french texts.
lowercase = [
'''Le transformeur est un modèle d\'apprentissage profond introduit en 2017, '''
'''utilisé principalement dans le domaine du traitement automatique des langues (TAL).''',
'''À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus '''
'''pour gérer des données séquentielles, telles que le langage naturel, pour des tâches '''
'''telles que la traduction et la synthèse de texte.''',
]
self.tokenizer_integration_test_util(
expected_encoding=A__ ,model_name='''camembert-base''' ,revision='''3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf''' ,sequences=A__ ,)
| 701 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
lowercase__ :Tuple = {
"configuration_biogpt": ["BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BioGptConfig"],
"tokenization_biogpt": ["BioGptTokenizer"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase__ :Union[str, Any] = [
"BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST",
"BioGptForCausalLM",
"BioGptForTokenClassification",
"BioGptForSequenceClassification",
"BioGptModel",
"BioGptPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig
from .tokenization_biogpt import BioGptTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_biogpt import (
BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST,
BioGptForCausalLM,
BioGptForSequenceClassification,
BioGptForTokenClassification,
BioGptModel,
BioGptPreTrainedModel,
)
else:
import sys
lowercase__ :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 633 | 0 |
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
lowerCAmelCase = logging.get_logger(__name__)
lowerCAmelCase = {"""vocab_file""": """spiece.model"""}
lowerCAmelCase = {
"""vocab_file""": {
"""bert_for_seq_generation""": (
"""https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model"""
),
}
}
lowerCAmelCase = {"""bert_for_seq_generation""": 512}
class lowerCamelCase ( __UpperCamelCase ):
_lowerCAmelCase : List[str] = VOCAB_FILES_NAMES
_lowerCAmelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP
_lowerCAmelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_lowerCAmelCase : Optional[Any] = []
_lowerCAmelCase : List[str] = ['''input_ids''', '''attention_mask''']
def __init__( self , lowercase__ , lowercase__="<s>" , lowercase__="</s>" , lowercase__="<unk>" , lowercase__="<pad>" , lowercase__="<::::>" , lowercase__ = None , **lowercase__ , ):
__UpperCAmelCase : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs
# Add extra_ids to the special token list
super().__init__(
bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCAmelCase , )
__UpperCAmelCase : Dict = vocab_file
__UpperCAmelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs)
self.sp_model.Load(__UpperCAmelCase)
@property
def A( self):
return self.sp_model.get_piece_size()
def A( self):
__UpperCAmelCase : Tuple = {self.convert_ids_to_tokens(__UpperCAmelCase): i for i in range(self.vocab_size)}
vocab.update(self.added_tokens_encoder)
return vocab
def __getstate__( self):
__UpperCAmelCase : Union[str, Any] = self.__dict__.copy()
__UpperCAmelCase : Dict = None
return state
def __setstate__( self , lowercase__):
__UpperCAmelCase : Union[str, Any] = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs'''):
__UpperCAmelCase : Dict = {}
__UpperCAmelCase : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs)
self.sp_model.Load(self.vocab_file)
def A( self , lowercase__):
return self.sp_model.encode(__UpperCAmelCase , out_type=__UpperCAmelCase)
def A( self , lowercase__):
return self.sp_model.piece_to_id(__UpperCAmelCase)
def A( self , lowercase__):
__UpperCAmelCase : Union[str, Any] = self.sp_model.IdToPiece(__UpperCAmelCase)
return token
def A( self , lowercase__):
__UpperCAmelCase : List[Any] = []
__UpperCAmelCase : Union[str, Any] = ""
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
out_string += self.sp_model.decode(__UpperCAmelCase) + token
__UpperCAmelCase : Optional[Any] = []
else:
current_sub_tokens.append(__UpperCAmelCase)
out_string += self.sp_model.decode(__UpperCAmelCase)
return out_string.strip()
def A( self , lowercase__ , lowercase__ = None):
if not os.path.isdir(__UpperCAmelCase):
logger.error(F"Vocabulary path ({save_directory}) should be a directory")
return
__UpperCAmelCase : List[str] = os.path.join(
__UpperCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''])
if os.path.abspath(self.vocab_file) != os.path.abspath(__UpperCAmelCase) and os.path.isfile(self.vocab_file):
copyfile(self.vocab_file , __UpperCAmelCase)
elif not os.path.isfile(self.vocab_file):
with open(__UpperCAmelCase , '''wb''') as fi:
__UpperCAmelCase : Dict = self.sp_model.serialized_model_proto()
fi.write(__UpperCAmelCase)
return (out_vocab_file,)
| 462 |
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 OwlViTImageProcessor, OwlViTProcessor
@require_vision
class snake_case_ ( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase__ (self: int ) -> str:
'''simple docstring'''
__a : Union[str, Any] = tempfile.mkdtemp()
# fmt: off
__a : Dict = ["", "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
__a : str = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) )
__a : Union[str, Any] = ["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""]
__a : Union[str, Any] = {"unk_token": "<unk>"}
__a : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
__a : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as fp:
fp.write(json.dumps(__UpperCAmelCase ) + "\n" )
with open(self.merges_file , "w" , encoding="utf-8" ) as fp:
fp.write("\n".join(__UpperCAmelCase ) )
__a : str = {
"do_resize": True,
"size": 20,
"do_center_crop": True,
"crop_size": 18,
"do_normalize": True,
"image_mean": [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73],
"image_std": [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11],
}
__a : Any = 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: Tuple , **__UpperCAmelCase: Dict ) -> List[str]:
'''simple docstring'''
return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token="!" , **__UpperCAmelCase )
def UpperCAmelCase__ (self: Optional[Any] , **__UpperCAmelCase: int ) -> Any:
'''simple docstring'''
return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token="!" , **__UpperCAmelCase )
def UpperCAmelCase__ (self: List[Any] , **__UpperCAmelCase: Dict ) -> Optional[int]:
'''simple docstring'''
return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase )
def UpperCAmelCase__ (self: str ) -> int:
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def UpperCAmelCase__ (self: Dict ) -> Union[str, Any]:
'''simple docstring'''
__a : Dict = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
__a : Any = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def UpperCAmelCase__ (self: Tuple ) -> Optional[Any]:
'''simple docstring'''
__a : Dict = self.get_tokenizer()
__a : Dict = self.get_rust_tokenizer()
__a : List[str] = self.get_image_processor()
__a : Any = OwlViTProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase )
processor_slow.save_pretrained(self.tmpdirname )
__a : str = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=__UpperCAmelCase )
__a : Union[str, Any] = OwlViTProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase )
processor_fast.save_pretrained(self.tmpdirname )
__a : List[Any] = OwlViTProcessor.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: str ) -> Dict:
'''simple docstring'''
__a : Tuple = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
__a : Optional[Any] = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" )
__a : str = self.get_image_processor(do_normalize=__UpperCAmelCase )
__a : str = OwlViTProcessor.from_pretrained(
self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=__UpperCAmelCase )
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[int] ) -> Dict:
'''simple docstring'''
__a : Optional[Any] = self.get_image_processor()
__a : str = self.get_tokenizer()
__a : List[str] = OwlViTProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase )
__a : List[str] = self.prepare_image_inputs()
__a : Optional[Any] = image_processor(__UpperCAmelCase , return_tensors="np" )
__a : int = 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: Dict ) -> Optional[int]:
'''simple docstring'''
__a : int = self.get_image_processor()
__a : Tuple = self.get_tokenizer()
__a : Optional[int] = OwlViTProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase )
__a : Dict = "lower newer"
__a : Any = processor(text=__UpperCAmelCase , return_tensors="np" )
__a : List[str] = tokenizer(__UpperCAmelCase , return_tensors="np" )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() )
def UpperCAmelCase__ (self: List[Any] ) -> Dict:
'''simple docstring'''
__a : Dict = self.get_image_processor()
__a : List[str] = self.get_tokenizer()
__a : Optional[Any] = OwlViTProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase )
__a : Optional[int] = "lower newer"
__a : int = self.prepare_image_inputs()
__a : Optional[int] = 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: int ) -> Union[str, Any]:
'''simple docstring'''
__a : Dict = "google/owlvit-base-patch32"
__a : Dict = OwlViTProcessor.from_pretrained(__UpperCAmelCase )
__a : List[str] = ["cat", "nasa badge"]
__a : List[Any] = processor(text=__UpperCAmelCase )
__a : Any = 16
self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask"] )
self.assertEqual(inputs["input_ids"].shape , (2, seq_length) )
# test if it raises when no input is passed
with pytest.raises(__UpperCAmelCase ):
processor()
def UpperCAmelCase__ (self: Any ) -> Optional[int]:
'''simple docstring'''
__a : Optional[int] = "google/owlvit-base-patch32"
__a : Optional[int] = OwlViTProcessor.from_pretrained(__UpperCAmelCase )
__a : Tuple = [["cat", "nasa badge"], ["person"]]
__a : List[Any] = processor(text=__UpperCAmelCase )
__a : Tuple = 16
__a : Optional[Any] = len(__UpperCAmelCase )
__a : Optional[Any] = max([len(__UpperCAmelCase ) for texts in input_texts] )
self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask"] )
self.assertEqual(inputs["input_ids"].shape , (batch_size * num_max_text_queries, seq_length) )
# test if it raises when no input is passed
with pytest.raises(__UpperCAmelCase ):
processor()
def UpperCAmelCase__ (self: Tuple ) -> Dict:
'''simple docstring'''
__a : int = "google/owlvit-base-patch32"
__a : Dict = OwlViTProcessor.from_pretrained(__UpperCAmelCase )
__a : List[str] = ["cat", "nasa badge"]
__a : List[Any] = processor(text=__UpperCAmelCase )
__a : int = 16
__a : Union[str, Any] = inputs["input_ids"]
__a : Optional[int] = [
[49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]
self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask"] )
self.assertEqual(inputs["input_ids"].shape , (2, seq_length) )
self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] )
self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] )
def UpperCAmelCase__ (self: Optional[int] ) -> List[Any]:
'''simple docstring'''
__a : Union[str, Any] = self.get_image_processor()
__a : List[str] = self.get_tokenizer()
__a : Tuple = OwlViTProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase )
__a : str = self.prepare_image_inputs()
__a : Any = self.prepare_image_inputs()
__a : str = processor(images=__UpperCAmelCase , query_images=__UpperCAmelCase )
self.assertListEqual(list(inputs.keys() ) , ["query_pixel_values", "pixel_values"] )
# test if it raises when no input is passed
with pytest.raises(__UpperCAmelCase ):
processor()
def UpperCAmelCase__ (self: Any ) -> Tuple:
'''simple docstring'''
__a : int = self.get_image_processor()
__a : Tuple = self.get_tokenizer()
__a : Optional[int] = OwlViTProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase )
__a : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
__a : Tuple = processor.batch_decode(__UpperCAmelCase )
__a : str = tokenizer.batch_decode(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
| 351 | 0 |
"""simple docstring"""
import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer
import datasets
from datasets import logging
_a : List[Any] = """\
"""
_a : str = """
Perplexity (PPL) is one of the most common metrics for evaluating language models.
It is defined as the exponentiated average negative log-likelihood of a sequence.
For more information, see https://huggingface.co/docs/transformers/perplexity
"""
_a : List[str] = """
Args:
model_id (str): model used for calculating Perplexity
NOTE: Perplexity can only be calculated for causal language models.
This includes models such as gpt2, causal variations of bert,
causal versions of t5, and more (the full list can be found
in the AutoModelForCausalLM documentation here:
https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )
input_texts (list of str): input text, each separate text snippet
is one list entry.
batch_size (int): the batch size to run texts through the model. Defaults to 16.
add_start_token (bool): whether to add the start token to the texts,
so the perplexity can include the probability of the first word. Defaults to True.
device (str): device to run on, defaults to 'cuda' when available
Returns:
perplexity: dictionary containing the perplexity scores for the texts
in the input list, as well as the mean perplexity. If one of the input texts is
longer than the max input length of the model, then it is truncated to the
max length for the perplexity computation.
Examples:
Example 1:
>>> perplexity = datasets.load_metric(\"perplexity\")
>>> input_texts = [\"lorem ipsum\", \"Happy Birthday!\", \"Bienvenue\"]
>>> results = perplexity.compute(model_id='gpt2',
... add_start_token=False,
... input_texts=input_texts) # doctest:+ELLIPSIS
>>> print(list(results.keys()))
['perplexities', 'mean_perplexity']
>>> print(round(results[\"mean_perplexity\"], 2))
78.22
>>> print(round(results[\"perplexities\"][0], 2))
11.11
Example 2:
>>> perplexity = datasets.load_metric(\"perplexity\")
>>> input_texts = datasets.load_dataset(\"wikitext\",
... \"wikitext-2-raw-v1\",
... split=\"test\")[\"text\"][:50] # doctest:+ELLIPSIS
[...]
>>> input_texts = [s for s in input_texts if s!='']
>>> results = perplexity.compute(model_id='gpt2',
... input_texts=input_texts) # doctest:+ELLIPSIS
>>> print(list(results.keys()))
['perplexities', 'mean_perplexity']
>>> print(round(results[\"mean_perplexity\"], 2))
60.35
>>> print(round(results[\"perplexities\"][0], 2))
81.12
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION)
class _UpperCAmelCase ( datasets.Metric):
def lowerCamelCase__ ( self ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"input_texts": datasets.Value("string" ),
} ) , reference_urls=["https://huggingface.co/docs/transformers/perplexity"] , )
def lowerCamelCase__ ( self , snake_case_ , snake_case_ , snake_case_ = 16 , snake_case_ = True , snake_case_=None ):
if device is not None:
assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
if device == "gpu":
_snake_case : int = "cuda"
else:
_snake_case : List[Any] = "cuda" if torch.cuda.is_available() else "cpu"
_snake_case : List[Any] = AutoModelForCausalLM.from_pretrained(snake_case_ )
_snake_case : Optional[int] = model.to(snake_case_ )
_snake_case : Tuple = AutoTokenizer.from_pretrained(snake_case_ )
# if batch_size > 1 (which generally leads to padding being required), and
# if there is not an already assigned pad_token, assign an existing
# special token to also be the padding token
if tokenizer.pad_token is None and batch_size > 1:
_snake_case : Optional[int] = list(tokenizer.special_tokens_map_extended.values() )
# check that the model already has at least one special token defined
assert (
len(snake_case_ ) > 0
), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
# assign one of the special tokens to also be the pad token
tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]} )
if add_start_token:
# leave room for <BOS> token to be added:
assert (
tokenizer.bos_token is not None
), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
_snake_case : Optional[Any] = model.config.max_length - 1
else:
_snake_case : Optional[Any] = model.config.max_length
_snake_case : List[Any] = tokenizer(
snake_case_ , add_special_tokens=snake_case_ , padding=snake_case_ , truncation=snake_case_ , max_length=snake_case_ , return_tensors="pt" , return_attention_mask=snake_case_ , ).to(snake_case_ )
_snake_case : int = encodings["input_ids"]
_snake_case : Optional[int] = encodings["attention_mask"]
# check that each input is long enough:
if add_start_token:
assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long."
else:
assert torch.all(
torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."
_snake_case : Tuple = []
_snake_case : Union[str, Any] = CrossEntropyLoss(reduction="none" )
for start_index in logging.tqdm(range(0 , len(snake_case_ ) , snake_case_ ) ):
_snake_case : Dict = min(start_index + batch_size , len(snake_case_ ) )
_snake_case : Optional[Any] = encoded_texts[start_index:end_index]
_snake_case : Union[str, Any] = attn_masks[start_index:end_index]
if add_start_token:
_snake_case : Any = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(snake_case_ )
_snake_case : Optional[int] = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 )
_snake_case : str = torch.cat(
[torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(snake_case_ ), attn_mask] , dim=1 )
_snake_case : Optional[int] = encoded_batch
with torch.no_grad():
_snake_case : Optional[int] = model(snake_case_ , attention_mask=snake_case_ ).logits
_snake_case : Optional[Any] = out_logits[..., :-1, :].contiguous()
_snake_case : int = labels[..., 1:].contiguous()
_snake_case : Tuple = attn_mask[..., 1:].contiguous()
_snake_case : Union[str, Any] = torch.expa(
(loss_fct(shift_logits.transpose(1 , 2 ) , snake_case_ ) * shift_attention_mask_batch).sum(1 )
/ shift_attention_mask_batch.sum(1 ) )
ppls += perplexity_batch.tolist()
return {"perplexities": ppls, "mean_perplexity": np.mean(snake_case_ )}
| 87 |
"""simple docstring"""
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DPMSolverMultistepScheduler,
TextToVideoSDPipeline,
UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
@skip_mps
class _UpperCAmelCase ( _snake_case , unittest.TestCase):
__lowercase : Any = TextToVideoSDPipeline
__lowercase : str = TEXT_TO_IMAGE_PARAMS
__lowercase : int = TEXT_TO_IMAGE_BATCH_PARAMS
# No `output_type`.
__lowercase : Optional[int] = frozenset(
[
"""num_inference_steps""",
"""generator""",
"""latents""",
"""return_dict""",
"""callback""",
"""callback_steps""",
])
def lowerCamelCase__ ( self ):
torch.manual_seed(0 )
_snake_case : str = UNetaDConditionModel(
block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , )
_snake_case : List[Any] = DDIMScheduler(
beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=snake_case_ , set_alpha_to_one=snake_case_ , )
torch.manual_seed(0 )
_snake_case : Union[str, Any] = AutoencoderKL(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=1_28 , )
torch.manual_seed(0 )
_snake_case : Optional[Any] = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act="gelu" , projection_dim=5_12 , )
_snake_case : Tuple = CLIPTextModel(snake_case_ )
_snake_case : Optional[int] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
_snake_case : Any = {
"unet": unet,
"scheduler": scheduler,
"vae": vae,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
}
return components
def lowerCamelCase__ ( self , snake_case_ , snake_case_=0 ):
if str(snake_case_ ).startswith("mps" ):
_snake_case : str = torch.manual_seed(snake_case_ )
else:
_snake_case : Union[str, Any] = torch.Generator(device=snake_case_ ).manual_seed(snake_case_ )
_snake_case : str = {
"prompt": "A painting of a squirrel eating a burger",
"generator": generator,
"num_inference_steps": 2,
"guidance_scale": 6.0,
"output_type": "pt",
}
return inputs
def lowerCamelCase__ ( self ):
_snake_case : int = "cpu" # ensure determinism for the device-dependent torch.Generator
_snake_case : Optional[Any] = self.get_dummy_components()
_snake_case : Tuple = TextToVideoSDPipeline(**snake_case_ )
_snake_case : List[str] = sd_pipe.to(snake_case_ )
sd_pipe.set_progress_bar_config(disable=snake_case_ )
_snake_case : int = self.get_dummy_inputs(snake_case_ )
_snake_case : Union[str, Any] = "np"
_snake_case : Dict = sd_pipe(**snake_case_ ).frames
_snake_case : Any = frames[0][-3:, -3:, -1]
assert frames[0].shape == (64, 64, 3)
_snake_case : Dict = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def lowerCamelCase__ ( self ):
self._test_attention_slicing_forward_pass(test_mean_pixel_difference=snake_case_ , expected_max_diff=3E-3 )
@unittest.skipIf(
torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , )
def lowerCamelCase__ ( self ):
self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=snake_case_ , expected_max_diff=1E-2 )
@unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." )
def lowerCamelCase__ ( self ):
pass
@unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." )
def lowerCamelCase__ ( self ):
pass
@unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." )
def lowerCamelCase__ ( self ):
pass
def lowerCamelCase__ ( self ):
return super().test_progress_bar()
@slow
@skip_mps
class _UpperCAmelCase ( unittest.TestCase):
def lowerCamelCase__ ( self ):
_snake_case : List[Any] = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy" )
_snake_case : int = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b" )
_snake_case : str = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
_snake_case : Tuple = pipe.to("cuda" )
_snake_case : List[Any] = "Spiderman is surfing"
_snake_case : Optional[int] = torch.Generator(device="cpu" ).manual_seed(0 )
_snake_case : int = pipe(snake_case_ , generator=snake_case_ , num_inference_steps=25 , output_type="pt" ).frames
_snake_case : int = video_frames.cpu().numpy()
assert np.abs(expected_video - video ).mean() < 5E-2
def lowerCamelCase__ ( self ):
_snake_case : Any = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy" )
_snake_case : str = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b" )
_snake_case : int = pipe.to("cuda" )
_snake_case : Any = "Spiderman is surfing"
_snake_case : str = torch.Generator(device="cpu" ).manual_seed(0 )
_snake_case : Any = pipe(snake_case_ , generator=snake_case_ , num_inference_steps=2 , output_type="pt" ).frames
_snake_case : Optional[int] = video_frames.cpu().numpy()
assert np.abs(expected_video - video ).mean() < 5E-2
| 87 | 1 |
import heapq as hq
import math
from collections.abc import Iterator
class UpperCAmelCase_ :
def __init__( self ,__snake_case ):
"""simple docstring"""
A_ = str(id_ )
A_ = None
A_ = None
A_ = []
A_ = {} # {vertex:distance}
def __lt__( self ,__snake_case ):
"""simple docstring"""
return self.key < other.key
def __repr__( self ):
"""simple docstring"""
return self.id
def __UpperCAmelCase ( self ,__snake_case ):
"""simple docstring"""
self.neighbors.append(__snake_case )
def __UpperCAmelCase ( self ,__snake_case ,__snake_case ):
"""simple docstring"""
A_ = weight
def UpperCAmelCase_ ( _UpperCAmelCase :Optional[int] , _UpperCAmelCase :List[str] , _UpperCAmelCase :Optional[Any] , _UpperCAmelCase :List[str] ) -> Optional[Any]:
'''simple docstring'''
graph[a - 1].add_neighbor(graph[b - 1] )
graph[b - 1].add_neighbor(graph[a - 1] )
# add the edges:
graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase )
graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase )
def UpperCAmelCase_ ( _UpperCAmelCase :list , _UpperCAmelCase :Vertex ) -> list:
'''simple docstring'''
A_ = []
for u in graph:
A_ = math.inf
A_ = None
A_ = 0
A_ = graph[:]
while q:
A_ = min(_UpperCAmelCase )
q.remove(_UpperCAmelCase )
for v in u.neighbors:
if (v in q) and (u.edges[v.id] < v.key):
A_ = u
A_ = u.edges[v.id]
for i in range(1 , len(_UpperCAmelCase ) ):
a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) )
return a
def UpperCAmelCase_ ( _UpperCAmelCase :list , _UpperCAmelCase :Vertex ) -> Iterator[tuple]:
'''simple docstring'''
for u in graph:
A_ = math.inf
A_ = None
A_ = 0
A_ = list(_UpperCAmelCase )
hq.heapify(_UpperCAmelCase )
while h:
A_ = hq.heappop(_UpperCAmelCase )
for v in u.neighbors:
if (v in h) and (u.edges[v.id] < v.key):
A_ = u
A_ = u.edges[v.id]
hq.heapify(_UpperCAmelCase )
for i in range(1 , len(_UpperCAmelCase ) ):
yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1)
def UpperCAmelCase_ ( ) -> None:
'''simple docstring'''
if __name__ == "__main__":
import doctest
doctest.testmod()
| 188 |
import requests
a__ : Any = 'YOUR API KEY'
def UpperCAmelCase_ ( _UpperCAmelCase :str , _UpperCAmelCase :str = giphy_api_key ) -> list:
'''simple docstring'''
A_ = '''+'''.join(query.split() )
A_ = f'https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}'
A_ = requests.get(_UpperCAmelCase ).json()['''data''']
return [gif["url"] for gif in gifs]
if __name__ == "__main__":
print('\n'.join(get_gifs('space ship')))
| 188 | 1 |
'''simple docstring'''
import copy
import os
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union
if TYPE_CHECKING:
from ...processing_utils import ProcessorMixin
from ...utils import TensorType
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__A : str = logging.get_logger(__name__)
__A : int = {
"""google/owlvit-base-patch32""": """https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json""",
"""google/owlvit-base-patch16""": """https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json""",
"""google/owlvit-large-patch14""": """https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json""",
}
class lowercase ( __snake_case ):
'''simple docstring'''
lowerCAmelCase__ = "owlvit_text_model"
def __init__( self : Tuple , __lowerCamelCase : Optional[Any]=49408 , __lowerCamelCase : Union[str, Any]=512 , __lowerCamelCase : List[str]=2048 , __lowerCamelCase : List[str]=12 , __lowerCamelCase : List[str]=8 , __lowerCamelCase : List[Any]=16 , __lowerCamelCase : Tuple="quick_gelu" , __lowerCamelCase : Optional[int]=1E-5 , __lowerCamelCase : Union[str, Any]=0.0 , __lowerCamelCase : List[str]=0.0_2 , __lowerCamelCase : Dict=1.0 , __lowerCamelCase : Optional[Any]=0 , __lowerCamelCase : int=49406 , __lowerCamelCase : Union[str, Any]=49407 , **__lowerCamelCase : Any , ) -> Dict:
'''simple docstring'''
super().__init__(pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase , **_lowercase )
lowerCamelCase__ = vocab_size
lowerCamelCase__ = hidden_size
lowerCamelCase__ = intermediate_size
lowerCamelCase__ = num_hidden_layers
lowerCamelCase__ = num_attention_heads
lowerCamelCase__ = max_position_embeddings
lowerCamelCase__ = hidden_act
lowerCamelCase__ = layer_norm_eps
lowerCamelCase__ = attention_dropout
lowerCamelCase__ = initializer_range
lowerCamelCase__ = initializer_factor
@classmethod
def a__ ( cls : Optional[Any] , __lowerCamelCase : Optional[int] , **__lowerCamelCase : Optional[Any] ) -> Any:
'''simple docstring'''
cls._set_token_in_kwargs(_lowercase )
lowerCamelCase__ = cls.get_config_dict(_lowercase , **_lowercase )
# get the text config dict if we are loading from OwlViTConfig
if config_dict.get("model_type" ) == "owlvit":
lowerCamelCase__ = config_dict["""text_config"""]
if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type '''
f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' )
return cls.from_dict(_lowercase , **_lowercase )
class lowercase ( __snake_case ):
'''simple docstring'''
lowerCAmelCase__ = "owlvit_vision_model"
def __init__( self : List[Any] , __lowerCamelCase : List[Any]=768 , __lowerCamelCase : Union[str, Any]=3072 , __lowerCamelCase : str=12 , __lowerCamelCase : str=12 , __lowerCamelCase : int=3 , __lowerCamelCase : Union[str, Any]=768 , __lowerCamelCase : str=32 , __lowerCamelCase : Tuple="quick_gelu" , __lowerCamelCase : int=1E-5 , __lowerCamelCase : Optional[int]=0.0 , __lowerCamelCase : List[Any]=0.0_2 , __lowerCamelCase : Union[str, Any]=1.0 , **__lowerCamelCase : Tuple , ) -> List[Any]:
'''simple docstring'''
super().__init__(**_lowercase )
lowerCamelCase__ = hidden_size
lowerCamelCase__ = intermediate_size
lowerCamelCase__ = num_hidden_layers
lowerCamelCase__ = num_attention_heads
lowerCamelCase__ = num_channels
lowerCamelCase__ = image_size
lowerCamelCase__ = patch_size
lowerCamelCase__ = hidden_act
lowerCamelCase__ = layer_norm_eps
lowerCamelCase__ = attention_dropout
lowerCamelCase__ = initializer_range
lowerCamelCase__ = initializer_factor
@classmethod
def a__ ( cls : int , __lowerCamelCase : str , **__lowerCamelCase : Tuple ) -> Dict:
'''simple docstring'''
cls._set_token_in_kwargs(_lowercase )
lowerCamelCase__ = cls.get_config_dict(_lowercase , **_lowercase )
# get the vision config dict if we are loading from OwlViTConfig
if config_dict.get("model_type" ) == "owlvit":
lowerCamelCase__ = config_dict["""vision_config"""]
if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type '''
f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' )
return cls.from_dict(_lowercase , **_lowercase )
class lowercase ( __snake_case ):
'''simple docstring'''
lowerCAmelCase__ = "owlvit"
lowerCAmelCase__ = True
def __init__( self : str , __lowerCamelCase : str=None , __lowerCamelCase : List[Any]=None , __lowerCamelCase : str=512 , __lowerCamelCase : str=2.6_5_9_2 , __lowerCamelCase : Any=True , **__lowerCamelCase : List[str] , ) -> Optional[int]:
'''simple docstring'''
super().__init__(**_lowercase )
if text_config is None:
lowerCamelCase__ = {}
logger.info("text_config is None. Initializing the OwlViTTextConfig with default values." )
if vision_config is None:
lowerCamelCase__ = {}
logger.info("vision_config is None. initializing the OwlViTVisionConfig with default values." )
lowerCamelCase__ = OwlViTTextConfig(**_lowercase )
lowerCamelCase__ = OwlViTVisionConfig(**_lowercase )
lowerCamelCase__ = projection_dim
lowerCamelCase__ = logit_scale_init_value
lowerCamelCase__ = return_dict
lowerCamelCase__ = 1.0
@classmethod
def a__ ( cls : List[str] , __lowerCamelCase : Tuple , **__lowerCamelCase : Dict ) -> Any:
'''simple docstring'''
cls._set_token_in_kwargs(_lowercase )
lowerCamelCase__ = cls.get_config_dict(_lowercase , **_lowercase )
if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type '''
f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' )
return cls.from_dict(_lowercase , **_lowercase )
@classmethod
def a__ ( cls : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , **__lowerCamelCase : str ) -> Dict:
'''simple docstring'''
lowerCamelCase__ = {}
lowerCamelCase__ = text_config
lowerCamelCase__ = vision_config
return cls.from_dict(_lowercase , **_lowercase )
def a__ ( self : Any ) -> str:
'''simple docstring'''
lowerCamelCase__ = copy.deepcopy(self.__dict__ )
lowerCamelCase__ = self.text_config.to_dict()
lowerCamelCase__ = self.vision_config.to_dict()
lowerCamelCase__ = self.__class__.model_type
return output
class lowercase ( __snake_case ):
'''simple docstring'''
@property
def a__ ( self : Any ) -> int:
'''simple docstring'''
return OrderedDict(
[
("input_ids", {0: "batch", 1: "sequence"}),
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
("attention_mask", {0: "batch", 1: "sequence"}),
] )
@property
def a__ ( self : Any ) -> int:
'''simple docstring'''
return OrderedDict(
[
("logits_per_image", {0: "batch"}),
("logits_per_text", {0: "batch"}),
("text_embeds", {0: "batch"}),
("image_embeds", {0: "batch"}),
] )
@property
def a__ ( self : Optional[int] ) -> int:
'''simple docstring'''
return 1E-4
def a__ ( self : List[Any] , __lowerCamelCase : int , __lowerCamelCase : Union[str, Any] = -1 , __lowerCamelCase : List[Any] = -1 , __lowerCamelCase : Union[str, Any] = None , ) -> str:
'''simple docstring'''
lowerCamelCase__ = super().generate_dummy_inputs(
processor.tokenizer , batch_size=_lowercase , seq_length=_lowercase , framework=_lowercase )
lowerCamelCase__ = super().generate_dummy_inputs(
processor.image_processor , batch_size=_lowercase , framework=_lowercase )
return {**text_input_dict, **image_input_dict}
@property
def a__ ( self : Tuple ) -> Dict:
'''simple docstring'''
return 14
| 719 |
'''simple docstring'''
import argparse
import collections
import os
import re
import tempfile
import pandas as pd
from datasets import Dataset
from huggingface_hub import hf_hub_download, upload_folder
from transformers.utils import direct_transformers_import
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/update_metadata.py
__A : List[Any] = """src/transformers"""
# This is to make sure the transformers module imported is the one in the repo.
__A : Dict = direct_transformers_import(TRANSFORMERS_PATH)
# Regexes that match TF/Flax/PT model names.
__A : List[Any] = re.compile(R"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")
__A : Union[str, Any] = re.compile(R"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
__A : int = re.compile(R"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")
# Fill this with tuples (pipeline_tag, model_mapping, auto_model)
__A : List[Any] = [
("""pretraining""", """MODEL_FOR_PRETRAINING_MAPPING_NAMES""", """AutoModelForPreTraining"""),
("""feature-extraction""", """MODEL_MAPPING_NAMES""", """AutoModel"""),
("""audio-classification""", """MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForAudioClassification"""),
("""text-generation""", """MODEL_FOR_CAUSAL_LM_MAPPING_NAMES""", """AutoModelForCausalLM"""),
("""automatic-speech-recognition""", """MODEL_FOR_CTC_MAPPING_NAMES""", """AutoModelForCTC"""),
("""image-classification""", """MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForImageClassification"""),
("""image-segmentation""", """MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES""", """AutoModelForImageSegmentation"""),
("""fill-mask""", """MODEL_FOR_MASKED_LM_MAPPING_NAMES""", """AutoModelForMaskedLM"""),
("""object-detection""", """MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES""", """AutoModelForObjectDetection"""),
(
"""zero-shot-object-detection""",
"""MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES""",
"""AutoModelForZeroShotObjectDetection""",
),
("""question-answering""", """MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForQuestionAnswering"""),
("""text2text-generation""", """MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES""", """AutoModelForSeq2SeqLM"""),
("""text-classification""", """MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForSequenceClassification"""),
("""automatic-speech-recognition""", """MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES""", """AutoModelForSpeechSeq2Seq"""),
(
"""table-question-answering""",
"""MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES""",
"""AutoModelForTableQuestionAnswering""",
),
("""token-classification""", """MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForTokenClassification"""),
("""multiple-choice""", """MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES""", """AutoModelForMultipleChoice"""),
(
"""next-sentence-prediction""",
"""MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES""",
"""AutoModelForNextSentencePrediction""",
),
(
"""audio-frame-classification""",
"""MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES""",
"""AutoModelForAudioFrameClassification""",
),
("""audio-xvector""", """MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES""", """AutoModelForAudioXVector"""),
(
"""document-question-answering""",
"""MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES""",
"""AutoModelForDocumentQuestionAnswering""",
),
(
"""visual-question-answering""",
"""MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES""",
"""AutoModelForVisualQuestionAnswering""",
),
("""image-to-text""", """MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES""", """AutoModelForVision2Seq"""),
(
"""zero-shot-image-classification""",
"""MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES""",
"""AutoModelForZeroShotImageClassification""",
),
("""depth-estimation""", """MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES""", """AutoModelForDepthEstimation"""),
("""video-classification""", """MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForVideoClassification"""),
("""mask-generation""", """MODEL_FOR_MASK_GENERATION_MAPPING_NAMES""", """AutoModelForMaskGeneration"""),
]
def lowerCamelCase_ ( lowercase__):
lowerCamelCase__ = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)" , lowercase__)
return [m.group(0) for m in matches]
def lowerCamelCase_ ( ):
lowerCamelCase__ = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
lowerCamelCase__ = {
config.replace("Config" , ""): model_type for model_type, config in config_maping_names.items()
}
# Dictionaries flagging if each model prefix has a backend in PT/TF/Flax.
lowerCamelCase__ = collections.defaultdict(lowercase__)
lowerCamelCase__ = collections.defaultdict(lowercase__)
lowerCamelCase__ = collections.defaultdict(lowercase__)
# Let's lookup through all transformers object (once) and find if models are supported by a given backend.
for attr_name in dir(lowercase__):
lowerCamelCase__ = None
if _re_tf_models.match(lowercase__) is not None:
lowerCamelCase__ = tf_models
lowerCamelCase__ = _re_tf_models.match(lowercase__).groups()[0]
elif _re_flax_models.match(lowercase__) is not None:
lowerCamelCase__ = flax_models
lowerCamelCase__ = _re_flax_models.match(lowercase__).groups()[0]
elif _re_pt_models.match(lowercase__) is not None:
lowerCamelCase__ = pt_models
lowerCamelCase__ = _re_pt_models.match(lowercase__).groups()[0]
if lookup_dict is not None:
while len(lowercase__) > 0:
if attr_name in model_prefix_to_model_type:
lowerCamelCase__ = True
break
# Try again after removing the last word in the name
lowerCamelCase__ = "".join(camel_case_split(lowercase__)[:-1])
lowerCamelCase__ = set(list(pt_models.keys()) + list(tf_models.keys()) + list(flax_models.keys()))
lowerCamelCase__ = list(lowercase__)
all_models.sort()
lowerCamelCase__ = {"model_type": all_models}
lowerCamelCase__ = [pt_models[t] for t in all_models]
lowerCamelCase__ = [tf_models[t] for t in all_models]
lowerCamelCase__ = [flax_models[t] for t in all_models]
# Now let's use the auto-mapping names to make sure
lowerCamelCase__ = {}
for t in all_models:
if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES:
lowerCamelCase__ = "AutoProcessor"
elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES:
lowerCamelCase__ = "AutoTokenizer"
elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES:
lowerCamelCase__ = "AutoFeatureExtractor"
else:
# Default to AutoTokenizer if a model has nothing, for backward compatibility.
lowerCamelCase__ = "AutoTokenizer"
lowerCamelCase__ = [processors[t] for t in all_models]
return pd.DataFrame(lowercase__)
def lowerCamelCase_ ( lowercase__):
lowerCamelCase__ = [
transformers_module.models.auto.modeling_auto,
transformers_module.models.auto.modeling_tf_auto,
transformers_module.models.auto.modeling_flax_auto,
]
for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS:
lowerCamelCase__ = [model_mapping, F'''TF_{model_mapping}''', F'''FLAX_{model_mapping}''']
lowerCamelCase__ = [auto_class, F'''TF_{auto_class}''', F'''Flax_{auto_class}''']
# Loop through all three frameworks
for module, cls, mapping in zip(lowercase__ , lowercase__ , lowercase__):
# The type of pipeline may not exist in this framework
if not hasattr(lowercase__ , lowercase__):
continue
# First extract all model_names
lowerCamelCase__ = []
for name in getattr(lowercase__ , lowercase__).values():
if isinstance(lowercase__ , lowercase__):
model_names.append(lowercase__)
else:
model_names.extend(list(lowercase__))
# Add pipeline tag and auto model class for those models
table.update({model_name: (pipeline_tag, cls) for model_name in model_names})
return table
def lowerCamelCase_ ( lowercase__ , lowercase__):
lowerCamelCase__ = get_frameworks_table()
lowerCamelCase__ = Dataset.from_pandas(lowercase__)
lowerCamelCase__ = hf_hub_download(
"huggingface/transformers-metadata" , "pipeline_tags.json" , repo_type="dataset" , token=lowercase__)
lowerCamelCase__ = Dataset.from_json(lowercase__)
lowerCamelCase__ = {
tags_dataset[i]["model_class"]: (tags_dataset[i]["pipeline_tag"], tags_dataset[i]["auto_class"])
for i in range(len(lowercase__))
}
lowerCamelCase__ = update_pipeline_and_auto_class_table(lowercase__)
# Sort the model classes to avoid some nondeterministic updates to create false update commits.
lowerCamelCase__ = sorted(table.keys())
lowerCamelCase__ = pd.DataFrame(
{
"model_class": model_classes,
"pipeline_tag": [table[m][0] for m in model_classes],
"auto_class": [table[m][1] for m in model_classes],
})
lowerCamelCase__ = Dataset.from_pandas(lowercase__)
with tempfile.TemporaryDirectory() as tmp_dir:
frameworks_dataset.to_json(os.path.join(lowercase__ , "frameworks.json"))
tags_dataset.to_json(os.path.join(lowercase__ , "pipeline_tags.json"))
if commit_sha is not None:
lowerCamelCase__ = (
F'''Update with commit {commit_sha}\n\nSee: '''
F'''https://github.com/huggingface/transformers/commit/{commit_sha}'''
)
else:
lowerCamelCase__ = "Update"
upload_folder(
repo_id="huggingface/transformers-metadata" , folder_path=lowercase__ , repo_type="dataset" , token=lowercase__ , commit_message=lowercase__ , )
def lowerCamelCase_ ( ):
lowerCamelCase__ = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS}
lowerCamelCase__ = transformers_module.pipelines.SUPPORTED_TASKS
lowerCamelCase__ = []
for key in pipeline_tasks:
if key not in in_table:
lowerCamelCase__ = pipeline_tasks[key]["pt"]
if isinstance(lowercase__ , (list, tuple)):
lowerCamelCase__ = model[0]
lowerCamelCase__ = model.__name__
if model not in in_table.values():
missing.append(lowercase__)
if len(lowercase__) > 0:
lowerCamelCase__ = ", ".join(lowercase__)
raise ValueError(
"The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside "
F'''`utils/update_metadata.py`: {msg}. Please add them!''')
if __name__ == "__main__":
__A : Any = argparse.ArgumentParser()
parser.add_argument("""--token""", type=str, help="""The token to use to push to the transformers-metadata dataset.""")
parser.add_argument("""--commit_sha""", type=str, help="""The sha of the commit going with this update.""")
parser.add_argument("""--check-only""", action="""store_true""", help="""Activate to just check all pipelines are present.""")
__A : Dict = parser.parse_args()
if args.check_only:
check_pipeline_tags()
else:
update_metadata(args.token, args.commit_sha)
| 187 | 0 |
'''simple docstring'''
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class __lowercase (__lowerCamelCase ):
_lowerCamelCase = ['''image_processor''', '''tokenizer''']
_lowerCamelCase = '''ChineseCLIPImageProcessor'''
_lowerCamelCase = ('''BertTokenizer''', '''BertTokenizerFast''')
def __init__( self : Optional[int] , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Dict=None , **UpperCAmelCase_ : Tuple):
UpperCamelCase__ : Dict = None
if "feature_extractor" in kwargs:
warnings.warn(
'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
' instead.' , UpperCAmelCase_ , )
UpperCamelCase__ : Optional[Any] = kwargs.pop('feature_extractor')
UpperCamelCase__ : Any = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('You need to specify an `image_processor`.')
if tokenizer is None:
raise ValueError('You need to specify a `tokenizer`.')
super().__init__(UpperCAmelCase_ , UpperCAmelCase_)
UpperCamelCase__ : Optional[Any] = self.image_processor
def __call__( self : Dict , UpperCAmelCase_ : int=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Dict=None , **UpperCAmelCase_ : Optional[int]):
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__ : int = self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if images is not None:
UpperCamelCase__ : Optional[Any] = self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if text is not None and images is not None:
UpperCamelCase__ : Optional[Any] = image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_)
def __UpperCamelCase ( self : Optional[int] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[str]):
return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_)
def __UpperCamelCase ( self : Dict , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Tuple):
return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_)
@property
def __UpperCamelCase ( self : Union[str, Any]):
UpperCamelCase__ : Optional[Any] = self.tokenizer.model_input_names
UpperCamelCase__ : List[Any] = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
@property
def __UpperCamelCase ( self : Optional[Any]):
warnings.warn(
'`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , UpperCAmelCase_ , )
return self.image_processor_class
| 596 |
'''simple docstring'''
import copy
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
lowerCAmelCase__ = logging.get_logger(__name__)
lowerCAmelCase__ = {
'microsoft/conditional-detr-resnet-50': (
'https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json'
),
}
class __lowercase (__lowerCamelCase ):
_lowerCamelCase = '''conditional_detr'''
_lowerCamelCase = ['''past_key_values''']
_lowerCamelCase = {
'''hidden_size''': '''d_model''',
'''num_attention_heads''': '''encoder_attention_heads''',
}
def __init__( self : Optional[int] , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=3 , UpperCAmelCase_ : List[Any]=300 , UpperCAmelCase_ : List[str]=6 , UpperCAmelCase_ : Optional[Any]=2_048 , UpperCAmelCase_ : Tuple=8 , UpperCAmelCase_ : Optional[Any]=6 , UpperCAmelCase_ : Union[str, Any]=2_048 , UpperCAmelCase_ : Union[str, Any]=8 , UpperCAmelCase_ : int=0.0 , UpperCAmelCase_ : Optional[int]=0.0 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Any="relu" , UpperCAmelCase_ : Optional[Any]=256 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Optional[int]=0.0 , UpperCAmelCase_ : Optional[Any]=0.0 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Tuple=1.0 , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : Union[str, Any]="sine" , UpperCAmelCase_ : Any="resnet50" , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : str=2 , UpperCAmelCase_ : Any=5 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : List[str]=1 , UpperCAmelCase_ : List[Any]=2 , UpperCAmelCase_ : Any=5 , UpperCAmelCase_ : Optional[int]=2 , UpperCAmelCase_ : List[str]=0.25 , **UpperCAmelCase_ : List[Any] , ):
if backbone_config is not None and use_timm_backbone:
raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.')
if not use_timm_backbone:
if backbone_config is None:
logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.')
UpperCamelCase__ : int = CONFIG_MAPPING['resnet'](out_features=['stage4'])
elif isinstance(UpperCAmelCase_ , UpperCAmelCase_):
UpperCamelCase__ : Optional[Any] = backbone_config.get('model_type')
UpperCamelCase__ : List[Any] = CONFIG_MAPPING[backbone_model_type]
UpperCamelCase__ : Union[str, Any] = config_class.from_dict(UpperCAmelCase_)
UpperCamelCase__ : Optional[Any] = use_timm_backbone
UpperCamelCase__ : int = backbone_config
UpperCamelCase__ : Optional[Any] = num_channels
UpperCamelCase__ : int = num_queries
UpperCamelCase__ : List[str] = d_model
UpperCamelCase__ : Union[str, Any] = encoder_ffn_dim
UpperCamelCase__ : Tuple = encoder_layers
UpperCamelCase__ : Any = encoder_attention_heads
UpperCamelCase__ : int = decoder_ffn_dim
UpperCamelCase__ : Any = decoder_layers
UpperCamelCase__ : Dict = decoder_attention_heads
UpperCamelCase__ : Optional[Any] = dropout
UpperCamelCase__ : Union[str, Any] = attention_dropout
UpperCamelCase__ : Tuple = activation_dropout
UpperCamelCase__ : Any = activation_function
UpperCamelCase__ : int = init_std
UpperCamelCase__ : Optional[Any] = init_xavier_std
UpperCamelCase__ : str = encoder_layerdrop
UpperCamelCase__ : Optional[int] = decoder_layerdrop
UpperCamelCase__ : Any = encoder_layers
UpperCamelCase__ : Optional[int] = auxiliary_loss
UpperCamelCase__ : int = position_embedding_type
UpperCamelCase__ : Optional[Any] = backbone
UpperCamelCase__ : Optional[int] = use_pretrained_backbone
UpperCamelCase__ : Dict = dilation
# Hungarian matcher
UpperCamelCase__ : List[str] = class_cost
UpperCamelCase__ : Optional[int] = bbox_cost
UpperCamelCase__ : Union[str, Any] = giou_cost
# Loss coefficients
UpperCamelCase__ : Optional[int] = mask_loss_coefficient
UpperCamelCase__ : Optional[Any] = dice_loss_coefficient
UpperCamelCase__ : Tuple = cls_loss_coefficient
UpperCamelCase__ : str = bbox_loss_coefficient
UpperCamelCase__ : Optional[Any] = giou_loss_coefficient
UpperCamelCase__ : Dict = focal_alpha
super().__init__(is_encoder_decoder=UpperCAmelCase_ , **UpperCAmelCase_)
@property
def __UpperCamelCase ( self : Tuple):
return self.encoder_attention_heads
@property
def __UpperCamelCase ( self : Optional[int]):
return self.d_model
def __UpperCamelCase ( self : List[str]):
UpperCamelCase__ : Optional[int] = copy.deepcopy(self.__dict__)
if self.backbone_config is not None:
UpperCamelCase__ : Any = self.backbone_config.to_dict()
UpperCamelCase__ : Dict = self.__class__.model_type
return output
class __lowercase (__lowerCamelCase ):
_lowerCamelCase = version.parse('''1.11''' )
@property
def __UpperCamelCase ( self : Optional[int]):
return OrderedDict(
[
('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
('pixel_mask', {0: 'batch'}),
])
@property
def __UpperCamelCase ( self : List[Any]):
return 1e-5
@property
def __UpperCamelCase ( self : Union[str, Any]):
return 12
| 596 | 1 |
'''simple docstring'''
class _a :
def __init__( self : List[Any] ):
'''simple docstring'''
UpperCAmelCase = {} # Mapping from char to TrieNode
UpperCAmelCase = False
def A ( self : Tuple , lowercase : list[str] ):
'''simple docstring'''
for word in words:
self.insert(lowercase )
def A ( self : Tuple , lowercase : str ):
'''simple docstring'''
UpperCAmelCase = self
for char in word:
if char not in curr.nodes:
UpperCAmelCase = TrieNode()
UpperCAmelCase = curr.nodes[char]
UpperCAmelCase = True
def A ( self : Any , lowercase : str ):
'''simple docstring'''
UpperCAmelCase = self
for char in word:
if char not in curr.nodes:
return False
UpperCAmelCase = curr.nodes[char]
return curr.is_leaf
def A ( self : int , lowercase : str ):
'''simple docstring'''
def _delete(lowercase : TrieNode , lowercase : str , lowercase : int ) -> bool:
if index == len(lowercase ):
# If word does not exist
if not curr.is_leaf:
return False
UpperCAmelCase = False
return len(curr.nodes ) == 0
UpperCAmelCase = word[index]
UpperCAmelCase = 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 = _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_ (_a : TrieNode , _a : str ):
if node.is_leaf:
print(_a , end=''' ''' )
for key, value in node.nodes.items():
print_words(_a , word + key )
def snake_case_ ():
UpperCAmelCase = '''banana bananas bandana band apple all beast'''.split()
UpperCAmelCase = TrieNode()
root.insert_many(_a )
# print_words(root, "")
assert all(root.find(_a ) 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_ (_a : str , _a : bool ):
print(str(_a ) , '''works!''' if passes else '''doesn\'t work :(''' )
def snake_case_ ():
assert test_trie()
def snake_case_ ():
print_results('''Testing trie functionality''' , test_trie() )
if __name__ == "__main__":
main()
| 358 |
'''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 =logging.getLogger(__name__)
A ={'facebook/bart-base': BartForConditionalGeneration}
A ={'facebook/bart-base': BartTokenizer}
def snake_case_ ():
UpperCAmelCase = argparse.ArgumentParser(description='''Export Bart model + Beam Search to ONNX graph.''' )
parser.add_argument(
'''--validation_file''' , type=_a , default=_a , help='''A csv or a json file containing the validation data.''' )
parser.add_argument(
'''--max_length''' , type=_a , default=5 , help='''The maximum total input sequence length after tokenization.''' , )
parser.add_argument(
'''--num_beams''' , type=_a , default=_a , 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=_a , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=_a , )
parser.add_argument(
'''--config_name''' , type=_a , default=_a , help='''Pretrained config name or path if not the same as model_name''' , )
parser.add_argument(
'''--device''' , type=_a , default='''cpu''' , help='''Device where the model will be run''' , )
parser.add_argument('''--output_file_path''' , type=_a , default=_a , help='''Where to store the final ONNX file.''' )
UpperCAmelCase = parser.parse_args()
return args
def snake_case_ (_a : Tuple , _a : str="cpu" ):
UpperCAmelCase = model_dict[model_name].from_pretrained(_a ).to(_a )
UpperCAmelCase = tokenizer_dict[model_name].from_pretrained(_a )
if model_name in ["facebook/bart-base"]:
UpperCAmelCase = 0
UpperCAmelCase = None
UpperCAmelCase = 0
return huggingface_model, tokenizer
def snake_case_ (_a : Optional[int] , _a : List[str] , _a : str , _a : Optional[Any] , _a : str ):
model.eval()
UpperCAmelCase = None
UpperCAmelCase = torch.jit.script(BARTBeamSearchGenerator(_a ) )
with torch.no_grad():
UpperCAmelCase = '''My friends are cool but they eat too many carbs.'''
UpperCAmelCase = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1_0_2_4 , return_tensors='''pt''' ).to(model.device )
UpperCAmelCase = model.generate(
inputs['''input_ids'''] , attention_mask=inputs['''attention_mask'''] , num_beams=_a , max_length=_a , early_stopping=_a , decoder_start_token_id=model.config.decoder_start_token_id , )
torch.onnx.export(
_a , (
inputs['''input_ids'''],
inputs['''attention_mask'''],
num_beams,
max_length,
model.config.decoder_start_token_id,
) , _a , opset_version=1_4 , 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=_a , )
logger.info('''Model exported to {}'''.format(_a ) )
UpperCAmelCase = remove_dup_initializers(os.path.abspath(_a ) )
logger.info('''Deduplicated and optimized model written to {}'''.format(_a ) )
UpperCAmelCase = onnxruntime.InferenceSession(_a )
UpperCAmelCase = ort_sess.run(
_a , {
'''input_ids''': inputs['''input_ids'''].cpu().numpy(),
'''attention_mask''': inputs['''attention_mask'''].cpu().numpy(),
'''num_beams''': np.array(_a ),
'''max_length''': np.array(_a ),
'''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 snake_case_ ():
UpperCAmelCase = parse_args()
UpperCAmelCase = 5
UpperCAmelCase = 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()
UpperCAmelCase = torch.device(args.device )
UpperCAmelCase , UpperCAmelCase = load_model_tokenizer(args.model_name_or_path , _a )
if model.config.decoder_start_token_id is None:
raise ValueError('''Make sure that `config.decoder_start_token_id` is correctly defined''' )
model.to(_a )
if args.max_length:
UpperCAmelCase = args.max_length
if args.num_beams:
UpperCAmelCase = args.num_beams
if args.output_file_path:
UpperCAmelCase = args.output_file_path
else:
UpperCAmelCase = '''BART.onnx'''
logger.info('''Exporting model to ONNX''' )
export_and_validate_model(_a , _a , _a , _a , _a )
if __name__ == "__main__":
main()
| 358 | 1 |
from __future__ import annotations
def snake_case ( lowerCamelCase ):
'''simple docstring'''
if not nums:
raise ValueError("""List is empty""" )
return sum(lowerCamelCase ) / len(lowerCamelCase )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 80 |
"""simple docstring"""
from __future__ import annotations
import unittest
import numpy as np
from transformers import OPTConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel
def UpperCAmelCase ( A__: int , A__: str , A__: List[Any]=None , A__: Dict=None ) -> List[str]:
if attention_mask is None:
__lowerCamelCase : int = tf.cast(tf.math.not_equal(A__ , config.pad_token_id ) , tf.inta )
return {"input_ids": input_ids, "attention_mask": attention_mask}
@require_tf
class __lowercase:
'''simple docstring'''
__a : Any = OPTConfig
__a : Union[str, Any] = {}
__a : Any = 'gelu'
def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=False , __a=99 , __a=16 , __a=2 , __a=4 , __a=4 , __a="gelu" , __a=0.1 , __a=0.1 , __a=20 , __a=2 , __a=1 , __a=0 , __a=16 , __a=16 , ):
__lowerCamelCase : Dict = parent
__lowerCamelCase : List[str] = batch_size
__lowerCamelCase : Tuple = seq_length
__lowerCamelCase : int = is_training
__lowerCamelCase : Optional[int] = use_labels
__lowerCamelCase : Optional[int] = vocab_size
__lowerCamelCase : Any = hidden_size
__lowerCamelCase : Tuple = num_hidden_layers
__lowerCamelCase : Optional[int] = num_attention_heads
__lowerCamelCase : Any = intermediate_size
__lowerCamelCase : Union[str, Any] = hidden_act
__lowerCamelCase : int = hidden_dropout_prob
__lowerCamelCase : List[Any] = attention_probs_dropout_prob
__lowerCamelCase : Dict = max_position_embeddings
__lowerCamelCase : str = eos_token_id
__lowerCamelCase : int = pad_token_id
__lowerCamelCase : Union[str, Any] = bos_token_id
__lowerCamelCase : Dict = embed_dim
__lowerCamelCase : Tuple = word_embed_proj_dim
__lowerCamelCase : Any = False
def snake_case_ ( self ):
__lowerCamelCase : str = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size )
__lowerCamelCase : int = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 )
__lowerCamelCase : Tuple = tf.concat([input_ids, eos_tensor] , axis=1 )
__lowerCamelCase : Any = self.config_cls(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=__a , **self.config_updates , )
__lowerCamelCase : int = prepare_opt_inputs_dict(__a , __a )
return config, inputs_dict
def snake_case_ ( self , __a , __a ):
__lowerCamelCase : Optional[int] = TFOPTModel(config=__a )
__lowerCamelCase : Dict = inputs_dict['input_ids']
__lowerCamelCase : List[Any] = input_ids[:1, :]
__lowerCamelCase : Optional[int] = inputs_dict['attention_mask'][:1, :]
__lowerCamelCase : Any = 1
# first forward pass
__lowerCamelCase : int = model(__a , attention_mask=__a , use_cache=__a )
__lowerCamelCase , __lowerCamelCase : Tuple = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
__lowerCamelCase : Dict = ids_tensor((self.batch_size, 3) , config.vocab_size )
__lowerCamelCase : Union[str, Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta )
# append to next input_ids and
__lowerCamelCase : Union[str, Any] = tf.concat([input_ids, next_tokens] , axis=-1 )
__lowerCamelCase : Dict = tf.concat([attention_mask, next_attn_mask] , axis=-1 )
__lowerCamelCase : Dict = model(__a , attention_mask=__a )[0]
__lowerCamelCase : str = model(__a , attention_mask=__a , past_key_values=__a )[0]
self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] )
# select random slice
__lowerCamelCase : Dict = int(ids_tensor((1,) , output_from_past.shape[-1] ) )
__lowerCamelCase : Dict = output_from_no_past[:, -3:, random_slice_idx]
__lowerCamelCase : Any = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(__a , __a , rtol=1E-3 )
@require_tf
class __lowercase( lowercase__ , lowercase__ , unittest.TestCase ):
'''simple docstring'''
__a : List[Any] = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else ()
__a : List[Any] = (TFOPTForCausalLM,) if is_tf_available() else ()
__a : List[str] = (
{'feature-extraction': TFOPTModel, 'text-generation': TFOPTForCausalLM} if is_tf_available() else {}
)
__a : List[Any] = False
__a : Dict = False
__a : Dict = False
__a : int = 10
def snake_case_ ( self ):
__lowerCamelCase : Optional[int] = TFOPTModelTester(self )
__lowerCamelCase : List[Any] = ConfigTester(self , config_class=__a )
def snake_case_ ( self ):
self.config_tester.run_common_tests()
def snake_case_ ( self ):
__lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*__a )
def snake_case_ ( self ):
__lowerCamelCase , __lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
def _get_word_embedding_weight(__a , __a ):
if hasattr(__a , 'weight' ):
return embedding_layer.weight
else:
# Here we build the word embeddings weights if not exists.
# And then we retry to get the attribute once built.
model.build()
if hasattr(__a , 'weight' ):
return embedding_layer.weight
else:
return None
for model_class in self.all_model_classes:
for size in [config.vocab_size - 10, config.vocab_size + 10]:
# build the embeddings
__lowerCamelCase : Any = model_class(config=__a )
__lowerCamelCase : Union[str, Any] = _get_word_embedding_weight(__a , model.get_input_embeddings() )
__lowerCamelCase : Any = _get_word_embedding_weight(__a , model.get_output_embeddings() )
# reshape the embeddings
model.resize_token_embeddings(__a )
__lowerCamelCase : int = _get_word_embedding_weight(__a , model.get_input_embeddings() )
__lowerCamelCase : Tuple = _get_word_embedding_weight(__a , model.get_output_embeddings() )
# check that the resized embeddings size matches the desired size.
__lowerCamelCase : Tuple = size if size is not None else config.vocab_size
self.assertEqual(new_input_embeddings.shape[0] , __a )
# check that weights remain the same after resizing
__lowerCamelCase : List[Any] = True
for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ):
if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0:
__lowerCamelCase : str = False
self.assertTrue(__a )
if old_output_embeddings is not None and new_output_embeddings is not None:
self.assertEqual(new_output_embeddings.shape[0] , __a )
__lowerCamelCase : Dict = True
for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ):
if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0:
__lowerCamelCase : Tuple = False
self.assertTrue(__a )
def UpperCAmelCase ( A__: Tuple ) -> Dict:
return tf.constant(A__ , dtype=tf.intaa )
@require_tf
class __lowercase( unittest.TestCase ):
'''simple docstring'''
__a : str = 99
def snake_case_ ( self ):
__lowerCamelCase : str = tf.ones((4, 1) , dtype=tf.intaa ) * 2
__lowerCamelCase : int = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 )
__lowerCamelCase : int = input_ids.shape[0]
__lowerCamelCase : Optional[int] = OPTConfig(
vocab_size=self.vocab_size , hidden_size=24 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , )
return config, input_ids, batch_size
@require_sentencepiece
@require_tf
class __lowercase( unittest.TestCase ):
'''simple docstring'''
@slow
def snake_case_ ( self ):
__lowerCamelCase : str = TFOPTModel.from_pretrained('facebook/opt-350m' )
__lowerCamelCase : Dict = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] )
__lowerCamelCase : List[Any] = tf.not_equal(__a , model.config.pad_token_id )
with tf.GradientTape():
__lowerCamelCase : Dict = model(input_ids=__a , attention_mask=__a ).last_hidden_state
__lowerCamelCase : List[Any] = (1, 11, 512)
self.assertEqual(output.shape , __a )
__lowerCamelCase : str = tf.constant(
[[-0.2_873, -1.9_218, -0.3_033], [-1.2_710, -0.1_338, -0.1_902], [0.4_095, 0.1_214, -1.3_121]] )
self.assertTrue(np.allclose(output[:, :3, :3] , __a , atol=4E-3 ) )
__lowerCamelCase : int = tf.function(__a , jit_compile=__a )
__lowerCamelCase : Optional[int] = xla_generate(__a , __a )[0]
self.assertTrue(np.allclose(output[:, :3, :3] , __a , atol=4E-2 ) )
@require_tf
@slow
class __lowercase( unittest.TestCase ):
'''simple docstring'''
def snake_case_ ( self ):
super().setUp()
__lowerCamelCase : str = 'facebook/opt-350m'
def snake_case_ ( self ):
__lowerCamelCase : int = TFOPTForCausalLM.from_pretrained(self.path_model )
__lowerCamelCase : List[Any] = GPTaTokenizer.from_pretrained(self.path_model )
__lowerCamelCase : Optional[int] = [
'Today is a beautiful day and I want to',
'In the city of',
'Paris is the capital of France and',
'Computers and mobile phones have taken',
]
# verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
__lowerCamelCase : str = tokenizer(__a , return_tensors='tf' , padding=__a , add_special_tokens=__a )
__lowerCamelCase : Tuple = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 )
__lowerCamelCase : List[str] = tf.constant(
[
[1.3_851, -13.8_923, -10.5_229, -10.7_533, -0.2_309, -10.2_384, -0.5_365, -9.0_947, -5.1_670],
[-4.7_073, -10.6_276, -3.9_415, -21.5_242, -0.2_822, -0.2_822, -0.2_822, -0.2_822, -0.2_822],
[0.6_247, -3.4_229, -8.9_179, -1.4_297, -14.1_650, 1.4_146, -9.0_218, -0.2_703, -0.2_703],
[6.4_783, -1.9_913, -10.7_926, -2.3_336, 1.5_092, -0.9_974, -6.8_213, 1.3_477, 1.3_477],
] )
self.assertTrue(np.allclose(__a , __a , atol=1E-4 ) )
__lowerCamelCase : Union[str, Any] = tf.function(__a , jit_compile=__a )
__lowerCamelCase : List[Any] = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 )
self.assertTrue(np.allclose(__a , __a , atol=1E-4 ) )
@require_tf
@slow
class __lowercase( unittest.TestCase ):
'''simple docstring'''
@property
def snake_case_ ( self ):
return [
"Today is a beautiful day and I want",
"In the city of",
"Paris is the capital of France and",
"Computers and mobile phones have taken",
]
def snake_case_ ( self ):
__lowerCamelCase : List[str] = 'facebook/opt-125m'
__lowerCamelCase : Dict = [
'Today is a beautiful day and I want to',
'In the city of New York, the city',
'Paris is the capital of France and the capital',
'Computers and mobile phones have taken over the',
]
__lowerCamelCase : Tuple = []
__lowerCamelCase : str = GPTaTokenizer.from_pretrained(__a )
__lowerCamelCase : Dict = TFOPTForCausalLM.from_pretrained(__a )
for prompt in self.prompts:
__lowerCamelCase : Dict = tokenizer(__a , return_tensors='tf' ).input_ids
__lowerCamelCase : int = model.generate(__a , max_length=10 )
__lowerCamelCase : List[Any] = tokenizer.batch_decode(__a , skip_special_tokens=__a )
predicted_outputs += generated_string
self.assertListEqual(__a , __a )
def snake_case_ ( self ):
__lowerCamelCase : int = 'facebook/opt-350m'
__lowerCamelCase : List[Any] = GPTaTokenizer.from_pretrained(__a )
__lowerCamelCase : str = TFOPTForCausalLM.from_pretrained(__a )
__lowerCamelCase : Optional[int] = 'left'
# use different length sentences to test batching
__lowerCamelCase : List[Any] = [
'Hello, my dog is a little',
'Today, I',
]
__lowerCamelCase : Optional[int] = tokenizer(__a , return_tensors='tf' , padding=__a )
__lowerCamelCase : Tuple = inputs['input_ids']
__lowerCamelCase : Optional[Any] = model.generate(input_ids=__a , attention_mask=inputs['attention_mask'] )
__lowerCamelCase : Any = tokenizer(sentences[0] , return_tensors='tf' ).input_ids
__lowerCamelCase : Optional[Any] = model.generate(input_ids=__a )
__lowerCamelCase : List[Any] = inputs_non_padded.shape[-1] - tf.math.reduce_sum(
tf.cast(inputs['attention_mask'][-1] , tf.intaa ) )
__lowerCamelCase : Union[str, Any] = tokenizer(sentences[1] , return_tensors='tf' ).input_ids
__lowerCamelCase : Any = model.generate(input_ids=__a , max_length=model.config.max_length - num_paddings )
__lowerCamelCase : Optional[int] = tokenizer.batch_decode(__a , skip_special_tokens=__a )
__lowerCamelCase : str = tokenizer.decode(output_non_padded[0] , skip_special_tokens=__a )
__lowerCamelCase : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=__a )
__lowerCamelCase : Any = [
'Hello, my dog is a little bit of a dork.\nI\'m a little bit',
'Today, I was in the middle of a conversation with a friend about the',
]
self.assertListEqual(__a , __a )
self.assertListEqual(__a , [non_padded_sentence, padded_sentence] )
def snake_case_ ( self ):
__lowerCamelCase : Any = 'facebook/opt-350m'
__lowerCamelCase : str = [
'Today is a beautiful day and I want to',
'In the city of San Francisco, the city',
'Paris is the capital of France and the capital',
'Computers and mobile phones have taken over the',
]
__lowerCamelCase : int = []
__lowerCamelCase : Tuple = GPTaTokenizer.from_pretrained(__a )
__lowerCamelCase : List[Any] = TFOPTForCausalLM.from_pretrained(__a )
for prompt in self.prompts:
__lowerCamelCase : Optional[Any] = tokenizer(__a , return_tensors='tf' ).input_ids
__lowerCamelCase : List[Any] = model.generate(__a , max_length=10 )
__lowerCamelCase : Union[str, Any] = tokenizer.batch_decode(__a , skip_special_tokens=__a )
predicted_outputs += generated_string
self.assertListEqual(__a , __a )
| 594 | 0 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ = logging.get_logger(__name__)
UpperCamelCase__ = {'openai-gpt': 'https://huggingface.co/openai-gpt/resolve/main/config.json'}
class _UpperCAmelCase ( snake_case ):
__lowerCamelCase: Dict = 'openai-gpt'
__lowerCamelCase: Any = {
'max_position_embeddings': 'n_positions',
'hidden_size': 'n_embd',
'num_attention_heads': 'n_head',
'num_hidden_layers': 'n_layer',
}
def __init__( self : Any , a : List[Any]=4_0_4_7_8 , a : Dict=5_1_2 , a : Optional[Any]=7_6_8 , a : Tuple=1_2 , a : Any=1_2 , a : Any="gelu" , a : Union[str, Any]=0.1 , a : Optional[Any]=0.1 , a : List[str]=0.1 , a : List[str]=1e-5 , a : Optional[int]=0.02 , a : Tuple="cls_index" , a : str=True , a : int=None , a : Union[str, Any]=True , a : Dict=0.1 , **a : int , ):
'''simple docstring'''
lowercase_ : int = vocab_size
lowercase_ : Tuple = n_positions
lowercase_ : List[str] = n_embd
lowercase_ : List[Any] = n_layer
lowercase_ : List[Any] = n_head
lowercase_ : Union[str, Any] = afn
lowercase_ : Any = resid_pdrop
lowercase_ : Dict = embd_pdrop
lowercase_ : Tuple = attn_pdrop
lowercase_ : Optional[Any] = layer_norm_epsilon
lowercase_ : List[Any] = initializer_range
lowercase_ : Optional[int] = summary_type
lowercase_ : Optional[Any] = summary_use_proj
lowercase_ : List[str] = summary_activation
lowercase_ : Tuple = summary_first_dropout
lowercase_ : Tuple = summary_proj_to_labels
super().__init__(**a )
| 640 |
'''simple docstring'''
def __SCREAMING_SNAKE_CASE ( _UpperCamelCase ):
"""simple docstring"""
return [
{
0: [1, 2],
1: [0, 2],
2: [0, 1, 3, 5],
3: [2, 4],
4: [3],
5: [2, 6, 8],
6: [5, 7],
7: [6, 8],
8: [5, 7],
},
{
0: [6],
1: [9],
2: [4, 5],
3: [4],
4: [2, 3],
5: [2],
6: [0, 7],
7: [6],
8: [],
9: [1],
},
{
0: [4],
1: [6],
2: [],
3: [5, 6, 7],
4: [0, 6],
5: [3, 8, 9],
6: [1, 3, 4, 7],
7: [3, 6, 8, 9],
8: [5, 7],
9: [5, 7],
},
{
0: [1, 3],
1: [0, 2, 4],
2: [1, 3, 4],
3: [0, 2, 4],
4: [1, 2, 3],
},
][index]
def __SCREAMING_SNAKE_CASE ( _UpperCamelCase ):
"""simple docstring"""
lowercase_ : Dict = 0
lowercase_ : Optional[Any] = len(_UpperCamelCase ) # No of vertices in graph
lowercase_ : Union[str, Any] = [0] * n
lowercase_ : Optional[int] = [False] * n
def dfs(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ):
lowercase_ : Union[str, Any] = True
lowercase_ : Dict = id_
id_ += 1
for to in graph[at]:
if to == parent:
pass
elif not visited[to]:
dfs(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , id_ )
lowercase_ : str = min(low[at] , low[to] )
if id_ <= low[to]:
bridges.append((at, to) if at < to else (to, at) )
else:
# This edge is a back edge and cannot be a bridge
lowercase_ : Optional[int] = min(low[at] , low[to] )
lowercase_ : list[tuple[int, int]] = []
for i in range(_UpperCamelCase ):
if not visited[i]:
dfs(_UpperCamelCase , -1 , _UpperCamelCase , id_ )
return bridges
if __name__ == "__main__":
import doctest
doctest.testmod()
| 640 | 1 |
import collections
import os
import re
from pathlib import Path
snake_case__ = """src/transformers"""
# Matches is_xxx_available()
snake_case__ = re.compile(R"""is\_([a-z_]*)_available()""")
# Catches a one-line _import_struct = {xxx}
snake_case__ = re.compile(R"""^_import_structure\s+=\s+\{([^\}]+)\}""")
# Catches a line with a key-values pattern: "bla": ["foo", "bar"]
snake_case__ = re.compile(R"""\s+\"\S*\":\s+\[([^\]]*)\]""")
# Catches a line if not is_foo_available
snake_case__ = re.compile(R"""^\s*if\s+not\s+is\_[a-z_]*\_available\(\)""")
# Catches a line _import_struct["bla"].append("foo")
snake_case__ = re.compile(R"""^\s*_import_structure\[\"\S*\"\]\.append\(\"(\S*)\"\)""")
# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"]
snake_case__ = re.compile(R"""^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]""")
# Catches a line with an object between quotes and a comma: "MyModel",
snake_case__ = re.compile(R"""^\s+\"([^\"]+)\",""")
# Catches a line with objects between brackets only: ["foo", "bar"],
snake_case__ = re.compile(R"""^\s+\[([^\]]+)\]""")
# Catches a line with from foo import bar, bla, boo
snake_case__ = re.compile(R"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""")
# Catches a line with try:
snake_case__ = re.compile(R"""^\s*try:""")
# Catches a line with else:
snake_case__ = re.compile(R"""^\s*else:""")
def lowerCamelCase_ ( UpperCAmelCase_ : Union[str, Any] ):
if _re_test_backend.search(UpperCAmelCase_ ) is None:
return None
lowercase : Optional[Any] = [b[0] for b in _re_backend.findall(UpperCAmelCase_ )]
backends.sort()
return "_and_".join(UpperCAmelCase_ )
def lowerCamelCase_ ( UpperCAmelCase_ : Any ):
with open(UpperCAmelCase_ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f:
lowercase : Union[str, Any] = f.readlines()
lowercase : Union[str, Any] = 0
while line_index < len(UpperCAmelCase_ ) and not lines[line_index].startswith('''_import_structure = {''' ):
line_index += 1
# If this is a traditional init, just return.
if line_index >= len(UpperCAmelCase_ ):
return None
# First grab the objects without a specific backend in _import_structure
lowercase : Dict = []
while not lines[line_index].startswith('''if TYPE_CHECKING''' ) and find_backend(lines[line_index] ) is None:
lowercase : Any = lines[line_index]
# If we have everything on a single line, let's deal with it.
if _re_one_line_import_struct.search(UpperCAmelCase_ ):
lowercase : Any = _re_one_line_import_struct.search(UpperCAmelCase_ ).groups()[0]
lowercase : List[str] = re.findall(r'''\[([^\]]+)\]''' , UpperCAmelCase_ )
for imp in imports:
objects.extend([obj[1:-1] for obj in imp.split(''', ''' )] )
line_index += 1
continue
lowercase : Union[str, Any] = _re_import_struct_key_value.search(UpperCAmelCase_ )
if single_line_import_search is not None:
lowercase : Tuple = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(''', ''' ) if len(UpperCAmelCase_ ) > 0]
objects.extend(UpperCAmelCase_ )
elif line.startswith(''' ''' * 8 + '''"''' ):
objects.append(line[9:-3] )
line_index += 1
lowercase : Dict = {'''none''': objects}
# Let's continue with backend-specific objects in _import_structure
while not lines[line_index].startswith('''if TYPE_CHECKING''' ):
# If the line is an if not is_backend_available, we grab all objects associated.
lowercase : str = find_backend(lines[line_index] )
# Check if the backend declaration is inside a try block:
if _re_try.search(lines[line_index - 1] ) is None:
lowercase : Tuple = None
if backend is not None:
line_index += 1
# Scroll until we hit the else block of try-except-else
while _re_else.search(lines[line_index] ) is None:
line_index += 1
line_index += 1
lowercase : List[str] = []
# Until we unindent, add backend objects to the list
while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 4 ):
lowercase : int = lines[line_index]
if _re_import_struct_add_one.search(UpperCAmelCase_ ) is not None:
objects.append(_re_import_struct_add_one.search(UpperCAmelCase_ ).groups()[0] )
elif _re_import_struct_add_many.search(UpperCAmelCase_ ) is not None:
lowercase : str = _re_import_struct_add_many.search(UpperCAmelCase_ ).groups()[0].split(''', ''' )
lowercase : Optional[Any] = [obj[1:-1] for obj in imports if len(UpperCAmelCase_ ) > 0]
objects.extend(UpperCAmelCase_ )
elif _re_between_brackets.search(UpperCAmelCase_ ) is not None:
lowercase : List[str] = _re_between_brackets.search(UpperCAmelCase_ ).groups()[0].split(''', ''' )
lowercase : Optional[int] = [obj[1:-1] for obj in imports if len(UpperCAmelCase_ ) > 0]
objects.extend(UpperCAmelCase_ )
elif _re_quote_object.search(UpperCAmelCase_ ) is not None:
objects.append(_re_quote_object.search(UpperCAmelCase_ ).groups()[0] )
elif line.startswith(''' ''' * 8 + '''"''' ):
objects.append(line[9:-3] )
elif line.startswith(''' ''' * 12 + '''"''' ):
objects.append(line[13:-3] )
line_index += 1
lowercase : int = objects
else:
line_index += 1
# At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend
lowercase : int = []
while (
line_index < len(UpperCAmelCase_ )
and find_backend(lines[line_index] ) is None
and not lines[line_index].startswith('''else''' )
):
lowercase : Any = lines[line_index]
lowercase : int = _re_import.search(UpperCAmelCase_ )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(''', ''' ) )
elif line.startswith(''' ''' * 8 ):
objects.append(line[8:-2] )
line_index += 1
lowercase : str = {'''none''': objects}
# Let's continue with backend-specific objects
while line_index < len(UpperCAmelCase_ ):
# If the line is an if is_backend_available, we grab all objects associated.
lowercase : str = find_backend(lines[line_index] )
# Check if the backend declaration is inside a try block:
if _re_try.search(lines[line_index - 1] ) is None:
lowercase : List[str] = None
if backend is not None:
line_index += 1
# Scroll until we hit the else block of try-except-else
while _re_else.search(lines[line_index] ) is None:
line_index += 1
line_index += 1
lowercase : int = []
# Until we unindent, add backend objects to the list
while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 8 ):
lowercase : Union[str, Any] = lines[line_index]
lowercase : int = _re_import.search(UpperCAmelCase_ )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(''', ''' ) )
elif line.startswith(''' ''' * 12 ):
objects.append(line[12:-2] )
line_index += 1
lowercase : Optional[int] = objects
else:
line_index += 1
return import_dict_objects, type_hint_objects
def lowerCamelCase_ ( UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ):
def find_duplicates(UpperCAmelCase_ : Tuple ):
return [k for k, v in collections.Counter(UpperCAmelCase_ ).items() if v > 1]
if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ):
return ["Both sides of the init do not have the same backends!"]
lowercase : Any = []
for key in import_dict_objects.keys():
lowercase : Optional[Any] = find_duplicates(import_dict_objects[key] )
if duplicate_imports:
errors.append(f'''Duplicate _import_structure definitions for: {duplicate_imports}''' )
lowercase : str = find_duplicates(type_hint_objects[key] )
if duplicate_type_hints:
errors.append(f'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}''' )
if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ):
lowercase : Optional[int] = '''base imports''' if key == '''none''' else f'''{key} backend'''
errors.append(f'''Differences for {name}:''' )
for a in type_hint_objects[key]:
if a not in import_dict_objects[key]:
errors.append(f''' {a} in TYPE_HINT but not in _import_structure.''' )
for a in import_dict_objects[key]:
if a not in type_hint_objects[key]:
errors.append(f''' {a} in _import_structure but not in TYPE_HINT.''' )
return errors
def lowerCamelCase_ ( ):
lowercase : List[Any] = []
for root, _, files in os.walk(UpperCAmelCase_ ):
if "__init__.py" in files:
lowercase : Dict = os.path.join(UpperCAmelCase_ , '''__init__.py''' )
lowercase : Union[str, Any] = parse_init(UpperCAmelCase_ )
if objects is not None:
lowercase : Union[str, Any] = analyze_results(*UpperCAmelCase_ )
if len(UpperCAmelCase_ ) > 0:
lowercase : List[str] = f'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}'''
failures.append('''\n'''.join(UpperCAmelCase_ ) )
if len(UpperCAmelCase_ ) > 0:
raise ValueError('''\n\n'''.join(UpperCAmelCase_ ) )
def lowerCamelCase_ ( ):
lowercase : Tuple = []
for path, directories, files in os.walk(UpperCAmelCase_ ):
for folder in directories:
# Ignore private modules
if folder.startswith('''_''' ):
directories.remove(UpperCAmelCase_ )
continue
# Ignore leftovers from branches (empty folders apart from pycache)
if len(list((Path(UpperCAmelCase_ ) / folder).glob('''*.py''' ) ) ) == 0:
continue
lowercase : Optional[Any] = str((Path(UpperCAmelCase_ ) / folder).relative_to(UpperCAmelCase_ ) )
lowercase : Any = short_path.replace(os.path.sep , '''.''' )
submodules.append(UpperCAmelCase_ )
for fname in files:
if fname == "__init__.py":
continue
lowercase : str = str((Path(UpperCAmelCase_ ) / fname).relative_to(UpperCAmelCase_ ) )
lowercase : Dict = short_path.replace('''.py''' , '''''' ).replace(os.path.sep , '''.''' )
if len(submodule.split('''.''' ) ) == 1:
submodules.append(UpperCAmelCase_ )
return submodules
snake_case__ = [
"""convert_pytorch_checkpoint_to_tf2""",
"""modeling_flax_pytorch_utils""",
"""models.esm.openfold_utils""",
]
def lowerCamelCase_ ( ):
# This is to make sure the transformers module imported is the one in the repo.
from transformers.utils import direct_transformers_import
lowercase : Dict = direct_transformers_import(UpperCAmelCase_ )
lowercase : Union[str, Any] = set(transformers._import_structure.keys() )
# This contains all the base keys of the _import_structure object defined in the init, but if the user is missing
# some optional dependencies, they may not have all of them. Thus we read the init to read all additions and
# (potentiall re-) add them.
with open(os.path.join(UpperCAmelCase_ , '''__init__.py''' ) , '''r''' ) as f:
lowercase : Any = f.read()
import_structure_keys.update(set(re.findall(r'''import_structure\[\"([^\"]*)\"\]''' , UpperCAmelCase_ ) ) )
lowercase : Union[str, Any] = [
module
for module in get_transformers_submodules()
if module not in IGNORE_SUBMODULES and module not in import_structure_keys
]
if len(UpperCAmelCase_ ) > 0:
lowercase : Union[str, Any] = '''\n'''.join(f'''- {module}''' for module in module_not_registered )
raise ValueError(
'''The following submodules are not properly registed in the main init of Transformers:\n'''
f'''{list_of_modules}\n'''
'''Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.''' )
if __name__ == "__main__":
check_all_inits()
check_submodules()
| 583 |
def lowerCamelCase_ ( UpperCAmelCase_ : int | float | str ):
try:
lowercase : Dict = float(UpperCAmelCase_ )
except ValueError:
raise ValueError('''Please enter a valid number''' )
lowercase : str = decimal - int(UpperCAmelCase_ )
if fractional_part == 0:
return int(UpperCAmelCase_ ), 1
else:
lowercase : Union[str, Any] = len(str(UpperCAmelCase_ ).split('''.''' )[1] )
lowercase : List[Any] = int(decimal * (10**number_of_frac_digits) )
lowercase : str = 10**number_of_frac_digits
lowercase , lowercase : str = denominator, numerator
while True:
lowercase : Any = dividend % divisor
if remainder == 0:
break
lowercase , lowercase : Union[str, Any] = divisor, remainder
lowercase , lowercase : str = numerator / divisor, denominator / divisor
return int(UpperCAmelCase_ ), int(UpperCAmelCase_ )
if __name__ == "__main__":
print(F'{decimal_to_fraction(2) = }')
print(F'{decimal_to_fraction(8_9.0) = }')
print(F'{decimal_to_fraction("67") = }')
print(F'{decimal_to_fraction("45.0") = }')
print(F'{decimal_to_fraction(1.5) = }')
print(F'{decimal_to_fraction("6.25") = }')
print(F'{decimal_to_fraction("78td") = }')
| 583 | 1 |
'''simple docstring'''
def _A ( snake_case__ : int ):
return number & 1 == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| 711 |
'''simple docstring'''
def _A ( snake_case__ : float ):
return 10 - x * x
def _A ( snake_case__ : float , snake_case__ : float ):
# Bolzano theory in order to find if there is a root between a and b
if equation(snake_case__ ) * equation(snake_case__ ) >= 0:
raise ValueError('''Wrong space!''' )
snake_case__ : List[str] = a
while (b - a) >= 0.01:
# Find middle point
snake_case__ : Optional[int] = (a + b) / 2
# Check if middle point is root
if equation(snake_case__ ) == 0.0:
break
# Decide the side to repeat the steps
if equation(snake_case__ ) * equation(snake_case__ ) < 0:
snake_case__ : Dict = c
else:
snake_case__ : List[str] = c
return c
if __name__ == "__main__":
import doctest
doctest.testmod()
print(bisection(-2, 5))
print(bisection(0, 6))
| 694 | 0 |
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 ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
return 1.0 / (1.0 + np.exp(-_outputs ))
def _lowerCamelCase ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
A_ = np.max(_outputs , axis=-1 , keepdims=SCREAMING_SNAKE_CASE )
A_ = np.exp(_outputs - maxes )
return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=SCREAMING_SNAKE_CASE )
class _lowercase ( __lowerCamelCase ):
_lowercase : Dict = 'sigmoid'
_lowercase : Any = 'softmax'
_lowercase : Union[str, Any] = 'none'
@add_end_docstrings(
__lowerCamelCase,r'\n return_all_scores (`bool`, *optional*, defaults to `False`):\n Whether to return all prediction scores or just the one of the predicted class.\n function_to_apply (`str`, *optional*, defaults to `"default"`):\n The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n has several labels, will apply the softmax function on the output.\n - `"sigmoid"`: Applies the sigmoid function on the output.\n - `"softmax"`: Applies the softmax function on the output.\n - `"none"`: Does not apply any function on the output.\n ',)
class _lowercase ( __lowerCamelCase ):
_lowercase : List[Any] = False
_lowercase : Any = ClassificationFunction.NONE
def __init__( self : Any , **lowerCamelCase__ : str ) -> str:
"""simple docstring"""
super().__init__(**lowerCamelCase__ )
self.check_model_type(
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
if self.framework == '''tf'''
else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING )
def UpperCamelCase ( self : List[Any] , lowerCamelCase__ : Union[str, Any]=None , lowerCamelCase__ : Union[str, Any]=None , lowerCamelCase__ : Union[str, Any]="" , **lowerCamelCase__ : List[Any] ) -> str:
"""simple docstring"""
A_ = tokenizer_kwargs
A_ = {}
if hasattr(self.model.config , '''return_all_scores''' ) and return_all_scores is None:
A_ = self.model.config.return_all_scores
if isinstance(lowerCamelCase__ , lowerCamelCase__ ) or top_k is None:
A_ = top_k
A_ = 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`.''' , lowerCamelCase__ , )
if return_all_scores:
A_ = None
else:
A_ = 1
if isinstance(lowerCamelCase__ , lowerCamelCase__ ):
A_ = ClassificationFunction[function_to_apply.upper()]
if function_to_apply is not None:
A_ = function_to_apply
return preprocess_params, {}, postprocess_params
def __call__( self : str , *lowerCamelCase__ : Tuple , **lowerCamelCase__ : Any ) -> Optional[int]:
"""simple docstring"""
A_ = super().__call__(*lowerCamelCase__ , **lowerCamelCase__ )
# TODO try and retrieve it in a nicer way from _sanitize_parameters.
A_ = '''top_k''' not in kwargs
if isinstance(args[0] , lowerCamelCase__ ) and _legacy:
# This pipeline is odd, and return a list when single item is run
return [result]
else:
return result
def UpperCamelCase ( self : Any , lowerCamelCase__ : Optional[Any] , **lowerCamelCase__ : Optional[Any] ) -> Dict[str, GenericTensor]:
"""simple docstring"""
A_ = self.framework
if isinstance(lowerCamelCase__ , lowerCamelCase__ ):
return self.tokenizer(**lowerCamelCase__ , return_tensors=lowerCamelCase__ , **lowerCamelCase__ )
elif isinstance(lowerCamelCase__ , lowerCamelCase__ ) and len(lowerCamelCase__ ) == 1 and isinstance(inputs[0] , lowerCamelCase__ ) 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=lowerCamelCase__ , **lowerCamelCase__ )
elif isinstance(lowerCamelCase__ , lowerCamelCase__ ):
# 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(lowerCamelCase__ , return_tensors=lowerCamelCase__ , **lowerCamelCase__ )
def UpperCamelCase ( self : Tuple , lowerCamelCase__ : Union[str, Any] ) -> Any:
"""simple docstring"""
return self.model(**lowerCamelCase__ )
def UpperCamelCase ( self : Dict , lowerCamelCase__ : Tuple , lowerCamelCase__ : Dict=None , lowerCamelCase__ : Dict=1 , lowerCamelCase__ : Any=True ) -> List[Any]:
"""simple docstring"""
if function_to_apply is None:
if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
A_ = ClassificationFunction.SIGMOID
elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
A_ = ClassificationFunction.SOFTMAX
elif hasattr(self.model.config , '''function_to_apply''' ) and function_to_apply is None:
A_ = self.model.config.function_to_apply
else:
A_ = ClassificationFunction.NONE
A_ = model_outputs['''logits'''][0]
A_ = outputs.numpy()
if function_to_apply == ClassificationFunction.SIGMOID:
A_ = sigmoid(lowerCamelCase__ )
elif function_to_apply == ClassificationFunction.SOFTMAX:
A_ = softmax(lowerCamelCase__ )
elif function_to_apply == ClassificationFunction.NONE:
A_ = 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()}
A_ = [
{'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(lowerCamelCase__ )
]
if not _legacy:
dict_scores.sort(key=lambda lowerCamelCase__ : x["score"] , reverse=lowerCamelCase__ )
if top_k is not None:
A_ = dict_scores[:top_k]
return dict_scores
| 203 |
def _lowerCamelCase ( SCREAMING_SNAKE_CASE = 100 ):
'''simple docstring'''
A_ = 0
A_ = 0
for i in range(1 , n + 1 ):
sum_of_squares += i**2
sum_of_ints += i
return sum_of_ints**2 - sum_of_squares
if __name__ == "__main__":
print(f'{solution() = }')
| 203 | 1 |
def a( A ):
return " ".join(
''.join(word[::-1] ) if len(A ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words('Hey wollef sroirraw'))
| 702 |
import operator as op
def lowercase__( A ):
snake_case__ : Optional[int] = []
snake_case__ : int = lambda A , A : int(x / y ) # noqa: E731 integer division operation
snake_case__ : Union[str, Any] = {
'^': op.pow,
'*': op.mul,
'/': div,
'+': op.add,
'-': op.sub,
} # operators & their respective operation
# print table header
print('Symbol'.center(8 ) , 'Action'.center(1_2 ) , 'Stack' , sep=' | ' )
print('-' * (3_0 + len(A )) )
for x in post_fix:
if x.isdigit(): # if x in digit
stack.append(A ) # append x to stack
# output in tabular format
print(x.rjust(8 ) , ('push(' + x + ')').ljust(1_2 ) , ','.join(A ) , sep=' | ' )
else:
snake_case__ : List[str] = stack.pop() # pop stack
# output in tabular format
print(''.rjust(8 ) , ('pop(' + b + ')').ljust(1_2 ) , ','.join(A ) , sep=' | ' )
snake_case__ : Dict = stack.pop() # pop stack
# output in tabular format
print(''.rjust(8 ) , ('pop(' + a + ')').ljust(1_2 ) , ','.join(A ) , sep=' | ' )
stack.append(
str(opr[x](int(A ) , int(A ) ) ) ) # evaluate the 2 values popped from stack & push result to stack
# output in tabular format
print(
x.rjust(8 ) , ('push(' + a + x + b + ')').ljust(1_2 ) , ','.join(A ) , sep=' | ' , )
return int(stack[0] )
if __name__ == "__main__":
lowerCamelCase : str = input('\n\nEnter a Postfix Equation (space separated) = ').split(' ')
print('\n\tResult = ', solve(Postfix))
| 303 | 0 |
'''simple docstring'''
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch
import math
from typing import Union
import torch
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import randn_tensor
from .scheduling_utils import SchedulerMixin
class _SCREAMING_SNAKE_CASE( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
A_ : str = 1
@register_to_config
def __init__( self : Any , UpperCamelCase_ : str=20_00 , UpperCamelCase_ : List[str]=0.1 , UpperCamelCase_ : int=20 , UpperCamelCase_ : Union[str, Any]=1e-3 ) -> List[Any]:
SCREAMING_SNAKE_CASE__ :int = None
SCREAMING_SNAKE_CASE__ :List[str] = None
SCREAMING_SNAKE_CASE__ :Dict = None
def __lowerCamelCase ( self : Dict , UpperCamelCase_ : int , UpperCamelCase_ : Union[str, torch.device] = None ) -> List[str]:
SCREAMING_SNAKE_CASE__ :List[Any] = torch.linspace(1 , self.config.sampling_eps , UpperCamelCase_ , device=UpperCamelCase_ )
def __lowerCamelCase ( self : Optional[int] , UpperCamelCase_ : Tuple , UpperCamelCase_ : List[Any] , UpperCamelCase_ : List[str] , UpperCamelCase_ : List[str]=None ) -> str:
if self.timesteps is None:
raise ValueError(
'`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler' )
# TODO(Patrick) better comments + non-PyTorch
# postprocess model score
SCREAMING_SNAKE_CASE__ :int = (
-0.25 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min
)
SCREAMING_SNAKE_CASE__ :List[str] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) )
SCREAMING_SNAKE_CASE__ :Optional[int] = std.flatten()
while len(std.shape ) < len(score.shape ):
SCREAMING_SNAKE_CASE__ :Optional[Any] = std.unsqueeze(-1 )
SCREAMING_SNAKE_CASE__ :Union[str, Any] = -score / std
# compute
SCREAMING_SNAKE_CASE__ :Optional[int] = -1.0 / len(self.timesteps )
SCREAMING_SNAKE_CASE__ :List[Any] = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min)
SCREAMING_SNAKE_CASE__ :Union[str, Any] = beta_t.flatten()
while len(beta_t.shape ) < len(x.shape ):
SCREAMING_SNAKE_CASE__ :str = beta_t.unsqueeze(-1 )
SCREAMING_SNAKE_CASE__ :Dict = -0.5 * beta_t * x
SCREAMING_SNAKE_CASE__ :Optional[Any] = torch.sqrt(UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ :str = drift - diffusion**2 * score
SCREAMING_SNAKE_CASE__ :List[Any] = x + drift * dt
# add noise
SCREAMING_SNAKE_CASE__ :Union[str, Any] = randn_tensor(x.shape , layout=x.layout , generator=UpperCamelCase_ , device=x.device , dtype=x.dtype )
SCREAMING_SNAKE_CASE__ :Union[str, Any] = x_mean + diffusion * math.sqrt(-dt ) * noise
return x, x_mean
def __len__( self : Tuple ) -> int:
return self.config.num_train_timesteps
| 209 | '''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 _SCREAMING_SNAKE_CASE:
def __init__( self : Optional[Any] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Tuple=2 , UpperCamelCase_ : List[Any]=3 , UpperCamelCase_ : Union[str, Any]=4 , UpperCamelCase_ : int=2 , UpperCamelCase_ : List[str]=7 , UpperCamelCase_ : List[str]=True , UpperCamelCase_ : List[Any]=True , UpperCamelCase_ : List[str]=True , UpperCamelCase_ : int=True , UpperCamelCase_ : List[str]=99 , UpperCamelCase_ : Dict=36 , UpperCamelCase_ : int=2 , UpperCamelCase_ : Union[str, Any]=4 , UpperCamelCase_ : str=37 , UpperCamelCase_ : List[Any]="gelu" , UpperCamelCase_ : Optional[int]=0.1 , UpperCamelCase_ : Optional[int]=0.1 , UpperCamelCase_ : int=5_12 , UpperCamelCase_ : List[Any]=16 , UpperCamelCase_ : Optional[Any]=2 , UpperCamelCase_ : Union[str, Any]=0.02 , UpperCamelCase_ : str=6 , UpperCamelCase_ : int=6 , UpperCamelCase_ : List[str]=3 , UpperCamelCase_ : Optional[Any]=4 , UpperCamelCase_ : Any=None , UpperCamelCase_ : Union[str, Any]=10_00 , ) -> int:
SCREAMING_SNAKE_CASE__ :int = parent
SCREAMING_SNAKE_CASE__ :str = batch_size
SCREAMING_SNAKE_CASE__ :Dict = num_channels
SCREAMING_SNAKE_CASE__ :Any = image_size
SCREAMING_SNAKE_CASE__ :Optional[Any] = patch_size
SCREAMING_SNAKE_CASE__ :List[Any] = is_training
SCREAMING_SNAKE_CASE__ :Tuple = use_input_mask
SCREAMING_SNAKE_CASE__ :Union[str, Any] = use_token_type_ids
SCREAMING_SNAKE_CASE__ :Optional[Any] = use_labels
SCREAMING_SNAKE_CASE__ :Tuple = vocab_size
SCREAMING_SNAKE_CASE__ :List[Any] = hidden_size
SCREAMING_SNAKE_CASE__ :int = num_hidden_layers
SCREAMING_SNAKE_CASE__ :Optional[Any] = num_attention_heads
SCREAMING_SNAKE_CASE__ :Any = intermediate_size
SCREAMING_SNAKE_CASE__ :Tuple = hidden_act
SCREAMING_SNAKE_CASE__ :Any = hidden_dropout_prob
SCREAMING_SNAKE_CASE__ :Any = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE__ :List[str] = max_position_embeddings
SCREAMING_SNAKE_CASE__ :Tuple = type_vocab_size
SCREAMING_SNAKE_CASE__ :List[str] = type_sequence_label_size
SCREAMING_SNAKE_CASE__ :Any = initializer_range
SCREAMING_SNAKE_CASE__ :List[Any] = coordinate_size
SCREAMING_SNAKE_CASE__ :List[Any] = shape_size
SCREAMING_SNAKE_CASE__ :str = num_labels
SCREAMING_SNAKE_CASE__ :Any = num_choices
SCREAMING_SNAKE_CASE__ :Union[str, Any] = scope
SCREAMING_SNAKE_CASE__ :Union[str, Any] = range_bbox
# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
SCREAMING_SNAKE_CASE__ :str = text_seq_length
SCREAMING_SNAKE_CASE__ :int = (image_size // patch_size) ** 2 + 1
SCREAMING_SNAKE_CASE__ :Union[str, Any] = self.text_seq_length + self.image_seq_length
def __lowerCamelCase ( self : Optional[int] ) -> int:
SCREAMING_SNAKE_CASE__ :Optional[int] = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size )
SCREAMING_SNAKE_CASE__ :List[str] = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox )
SCREAMING_SNAKE_CASE__ :Any = 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]:
SCREAMING_SNAKE_CASE__ :str = bbox[i, j, 3]
SCREAMING_SNAKE_CASE__ :str = bbox[i, j, 1]
SCREAMING_SNAKE_CASE__ :Dict = tmp_coordinate
if bbox[i, j, 2] < bbox[i, j, 0]:
SCREAMING_SNAKE_CASE__ :Optional[int] = bbox[i, j, 2]
SCREAMING_SNAKE_CASE__ :Dict = bbox[i, j, 0]
SCREAMING_SNAKE_CASE__ :Any = tmp_coordinate
SCREAMING_SNAKE_CASE__ :Tuple = tf.constant(UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ :Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
SCREAMING_SNAKE_CASE__ :Union[str, Any] = None
if self.use_input_mask:
SCREAMING_SNAKE_CASE__ :Tuple = random_attention_mask([self.batch_size, self.text_seq_length] )
SCREAMING_SNAKE_CASE__ :Optional[Any] = None
if self.use_token_type_ids:
SCREAMING_SNAKE_CASE__ :Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size )
SCREAMING_SNAKE_CASE__ :Optional[Any] = None
SCREAMING_SNAKE_CASE__ :Any = None
if self.use_labels:
SCREAMING_SNAKE_CASE__ :List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
SCREAMING_SNAKE_CASE__ :Optional[int] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels )
SCREAMING_SNAKE_CASE__ :Optional[int] = 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 __lowerCamelCase ( self : Optional[Any] , UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : int , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : str , UpperCamelCase_ : str ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE__ :Dict = TFLayoutLMvaModel(config=UpperCamelCase_ )
# text + image
SCREAMING_SNAKE_CASE__ :int = model(UpperCamelCase_ , pixel_values=UpperCamelCase_ , training=UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ :int = model(
UpperCamelCase_ , bbox=UpperCamelCase_ , pixel_values=UpperCamelCase_ , attention_mask=UpperCamelCase_ , token_type_ids=UpperCamelCase_ , training=UpperCamelCase_ , )
SCREAMING_SNAKE_CASE__ :str = model(UpperCamelCase_ , bbox=UpperCamelCase_ , pixel_values=UpperCamelCase_ , training=UpperCamelCase_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
# text only
SCREAMING_SNAKE_CASE__ :List[Any] = model(UpperCamelCase_ , training=UpperCamelCase_ )
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) )
# image only
SCREAMING_SNAKE_CASE__ :Optional[int] = model({'pixel_values': pixel_values} , training=UpperCamelCase_ )
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) )
def __lowerCamelCase ( self : Union[str, Any] , UpperCamelCase_ : Dict , UpperCamelCase_ : int , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Any , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Union[str, Any] ) -> Optional[int]:
SCREAMING_SNAKE_CASE__ :Any = self.num_labels
SCREAMING_SNAKE_CASE__ :Any = TFLayoutLMvaForSequenceClassification(config=UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ :Tuple = model(
UpperCamelCase_ , bbox=UpperCamelCase_ , pixel_values=UpperCamelCase_ , attention_mask=UpperCamelCase_ , token_type_ids=UpperCamelCase_ , labels=UpperCamelCase_ , training=UpperCamelCase_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __lowerCamelCase ( self : Union[str, Any] , UpperCamelCase_ : Dict , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : str , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Any , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Tuple ) -> Optional[int]:
SCREAMING_SNAKE_CASE__ :Union[str, Any] = self.num_labels
SCREAMING_SNAKE_CASE__ :Tuple = TFLayoutLMvaForTokenClassification(config=UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ :Optional[Any] = model(
UpperCamelCase_ , bbox=UpperCamelCase_ , pixel_values=UpperCamelCase_ , attention_mask=UpperCamelCase_ , token_type_ids=UpperCamelCase_ , labels=UpperCamelCase_ , training=UpperCamelCase_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) )
def __lowerCamelCase ( self : Optional[Any] , UpperCamelCase_ : Any , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : str , UpperCamelCase_ : Tuple , UpperCamelCase_ : int , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Optional[Any] ) -> int:
SCREAMING_SNAKE_CASE__ :int = 2
SCREAMING_SNAKE_CASE__ :str = TFLayoutLMvaForQuestionAnswering(config=UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ :List[Any] = model(
UpperCamelCase_ , bbox=UpperCamelCase_ , pixel_values=UpperCamelCase_ , attention_mask=UpperCamelCase_ , token_type_ids=UpperCamelCase_ , start_positions=UpperCamelCase_ , end_positions=UpperCamelCase_ , training=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 __lowerCamelCase ( self : Optional[Any] ) -> int:
SCREAMING_SNAKE_CASE__ :Tuple = self.prepare_config_and_inputs()
((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) :List[str] = config_and_inputs
SCREAMING_SNAKE_CASE__ :Tuple = {
'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 _SCREAMING_SNAKE_CASE( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ):
A_ : List[str] = (
(
TFLayoutLMvaModel,
TFLayoutLMvaForQuestionAnswering,
TFLayoutLMvaForSequenceClassification,
TFLayoutLMvaForTokenClassification,
)
if is_tf_available()
else ()
)
A_ : str = (
{'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
if is_tf_available()
else {}
)
A_ : Tuple = False
A_ : Tuple = False
A_ : Tuple = False
def __lowerCamelCase ( self : int , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : List[str] ) -> Optional[Any]:
return True
def __lowerCamelCase ( self : List[str] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Any=False ) -> dict:
SCREAMING_SNAKE_CASE__ :Dict = copy.deepcopy(UpperCamelCase_ )
if model_class in get_values(UpperCamelCase_ ):
SCREAMING_SNAKE_CASE__ :Optional[int] = {
k: tf.tile(tf.expand_dims(UpperCamelCase_ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) )
if isinstance(UpperCamelCase_ , tf.Tensor ) and v.ndim > 0
else v
for k, v in inputs_dict.items()
}
if return_labels:
if model_class in get_values(UpperCamelCase_ ):
SCREAMING_SNAKE_CASE__ :Any = tf.ones(self.model_tester.batch_size , dtype=tf.intaa )
elif model_class in get_values(UpperCamelCase_ ):
SCREAMING_SNAKE_CASE__ :Optional[int] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa )
SCREAMING_SNAKE_CASE__ :Dict = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa )
elif model_class in get_values(UpperCamelCase_ ):
SCREAMING_SNAKE_CASE__ :str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa )
elif model_class in get_values(UpperCamelCase_ ):
SCREAMING_SNAKE_CASE__ :Optional[Any] = tf.zeros(
(self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa )
return inputs_dict
def __lowerCamelCase ( self : Tuple ) -> Optional[int]:
SCREAMING_SNAKE_CASE__ :Optional[Any] = TFLayoutLMvaModelTester(self )
SCREAMING_SNAKE_CASE__ :Union[str, Any] = ConfigTester(self , config_class=UpperCamelCase_ , hidden_size=37 )
def __lowerCamelCase ( self : str ) -> Dict:
self.config_tester.run_common_tests()
def __lowerCamelCase ( self : int ) -> List[str]:
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ :str = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE__ :int = model_class(UpperCamelCase_ )
if getattr(UpperCamelCase_ , 'hf_compute_loss' , UpperCamelCase_ ):
# The number of elements in the loss should be the same as the number of elements in the label
SCREAMING_SNAKE_CASE__ :List[Any] = self._prepare_for_class(inputs_dict.copy() , UpperCamelCase_ , return_labels=UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ :Optional[Any] = prepared_for_class[
sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=UpperCamelCase_ )[0]
]
SCREAMING_SNAKE_CASE__ :List[Any] = added_label.shape.as_list()[:1]
# Test that model correctly compute the loss with kwargs
SCREAMING_SNAKE_CASE__ :List[Any] = self._prepare_for_class(inputs_dict.copy() , UpperCamelCase_ , return_labels=UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ :List[Any] = prepared_for_class.pop('input_ids' )
SCREAMING_SNAKE_CASE__ :Optional[int] = model(UpperCamelCase_ , **UpperCamelCase_ )[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
SCREAMING_SNAKE_CASE__ :Tuple = self._prepare_for_class(inputs_dict.copy() , UpperCamelCase_ , return_labels=UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ :str = prepared_for_class.pop('input_ids' )
if "labels" in prepared_for_class:
SCREAMING_SNAKE_CASE__ :Optional[int] = prepared_for_class['labels'].numpy()
if len(labels.shape ) > 1 and labels.shape[1] != 1:
SCREAMING_SNAKE_CASE__ :str = -1_00
SCREAMING_SNAKE_CASE__ :int = tf.convert_to_tensor(UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ :Tuple = model(UpperCamelCase_ , **UpperCamelCase_ )[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
SCREAMING_SNAKE_CASE__ :Optional[int] = self._prepare_for_class(inputs_dict.copy() , UpperCamelCase_ , return_labels=UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ :Any = model(UpperCamelCase_ )[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
SCREAMING_SNAKE_CASE__ :Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , UpperCamelCase_ , return_labels=UpperCamelCase_ )
# Get keys that were added with the _prepare_for_class function
SCREAMING_SNAKE_CASE__ :int = prepared_for_class.keys() - inputs_dict.keys()
SCREAMING_SNAKE_CASE__ :Union[str, Any] = inspect.signature(model.call ).parameters
SCREAMING_SNAKE_CASE__ :Optional[Any] = list(signature.keys() )
# Create a dictionary holding the location of the tensors in the tuple
SCREAMING_SNAKE_CASE__ :List[str] = {0: 'input_ids'}
for label_key in label_keys:
SCREAMING_SNAKE_CASE__ :Tuple = signature_names.index(UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ :Union[str, Any] = label_key
SCREAMING_SNAKE_CASE__ :Any = sorted(tuple_index_mapping.items() )
# Initialize a list with their default values, update the values and convert to a tuple
SCREAMING_SNAKE_CASE__ :List[str] = []
for name in signature_names:
if name != "kwargs":
list_input.append(signature[name].default )
for index, value in sorted_tuple_index_mapping:
SCREAMING_SNAKE_CASE__ :List[str] = prepared_for_class[value]
SCREAMING_SNAKE_CASE__ :List[str] = tuple(UpperCamelCase_ )
# Send to model
SCREAMING_SNAKE_CASE__ :List[str] = model(tuple_input[:-1] )[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] )
def __lowerCamelCase ( self : Tuple ) -> str:
(
(
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) ,
) :Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
def __lowerCamelCase ( self : Tuple ) -> Optional[int]:
(
(
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) ,
) :List[Any] = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
SCREAMING_SNAKE_CASE__ :Optional[int] = type
self.model_tester.create_and_check_model(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
def __lowerCamelCase ( self : Dict ) -> Optional[Any]:
(
(
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) ,
) :int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
def __lowerCamelCase ( self : Dict ) -> Any:
(
(
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) ,
) :List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
def __lowerCamelCase ( self : Tuple ) -> str:
(
(
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) , (
SCREAMING_SNAKE_CASE__
) ,
) :Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
@slow
def __lowerCamelCase ( self : Any ) -> Any:
for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE__ :int = TFLayoutLMvaModel.from_pretrained(UpperCamelCase_ )
self.assertIsNotNone(UpperCamelCase_ )
def lowerCamelCase ( ) -> Union[str, Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ :str = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_tf
class _SCREAMING_SNAKE_CASE( unittest.TestCase ):
@cached_property
def __lowerCamelCase ( self : Optional[Any] ) -> List[str]:
return LayoutLMvaImageProcessor(apply_ocr=UpperCamelCase_ ) if is_vision_available() else None
@slow
def __lowerCamelCase ( self : List[Any] ) -> str:
SCREAMING_SNAKE_CASE__ :List[Any] = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' )
SCREAMING_SNAKE_CASE__ :str = self.default_image_processor
SCREAMING_SNAKE_CASE__ :int = prepare_img()
SCREAMING_SNAKE_CASE__ :str = image_processor(images=UpperCamelCase_ , return_tensors='tf' ).pixel_values
SCREAMING_SNAKE_CASE__ :Tuple = tf.constant([[1, 2]] )
SCREAMING_SNAKE_CASE__ :Optional[int] = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 )
# forward pass
SCREAMING_SNAKE_CASE__ :Tuple = model(input_ids=UpperCamelCase_ , bbox=UpperCamelCase_ , pixel_values=UpperCamelCase_ , training=UpperCamelCase_ )
# verify the logits
SCREAMING_SNAKE_CASE__ :List[Any] = (1, 1_99, 7_68)
self.assertEqual(outputs.last_hidden_state.shape , UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ :str = tf.constant(
[[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] )
self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , UpperCamelCase_ , atol=1e-4 ) )
| 209 | 1 |
from collections import defaultdict
class lowercase__ :
def __init__( self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int ):
SCREAMING_SNAKE_CASE__ = total # total no of tasks (N)
# DP table will have a dimension of (2^M)*N
# initially all values are set to -1
SCREAMING_SNAKE_CASE__ = [
[-1 for i in range(total + 1 )] for j in range(2 ** len(UpperCAmelCase_ ) )
]
SCREAMING_SNAKE_CASE__ = defaultdict(UpperCAmelCase_ ) # stores the list of persons for each task
# final_mask is used to check if all persons are included by setting all bits
# to 1
SCREAMING_SNAKE_CASE__ = (1 << len(UpperCAmelCase_ )) - 1
def A_ ( self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ):
# if mask == self.finalmask all persons are distributed tasks, return 1
if mask == self.final_mask:
return 1
# if not everyone gets the task and no more tasks are available, return 0
if task_no > self.total_tasks:
return 0
# if case already considered
if self.dp[mask][task_no] != -1:
return self.dp[mask][task_no]
# Number of ways when we don't this task in the arrangement
SCREAMING_SNAKE_CASE__ = self.count_ways_until(UpperCAmelCase_ , task_no + 1 )
# now assign the tasks one by one to all possible persons and recursively
# assign for the remaining tasks.
if task_no in self.task:
for p in self.task[task_no]:
# if p is already given a task
if mask & (1 << p):
continue
# assign this task to p and change the mask value. And recursively
# assign tasks with the new mask value.
total_ways_util += self.count_ways_until(mask | (1 << p) , task_no + 1 )
# save the value.
SCREAMING_SNAKE_CASE__ = total_ways_util
return self.dp[mask][task_no]
def A_ ( self : Optional[Any] , UpperCAmelCase_ : List[str] ):
# Store the list of persons for each task
for i in range(len(UpperCAmelCase_ ) ):
for j in task_performed[i]:
self.task[j].append(UpperCAmelCase_ )
# call the function to fill the DP table, final answer is stored in dp[0][1]
return self.count_ways_until(0 , 1 )
if __name__ == "__main__":
__snake_case = 5 # total no of tasks (the value of N)
# the list of tasks that can be done by M persons.
__snake_case = [[1, 3, 4], [1, 2, 5], [3, 4]]
print(
AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways(
task_performed
)
)
| 400 |
from collections.abc import Callable
def _lowercase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> float:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ = a
SCREAMING_SNAKE_CASE__ = b
if function(UpperCamelCase_ ) == 0: # one of the a or b is a root for the function
return a
elif function(UpperCamelCase_ ) == 0:
return b
elif (
function(UpperCamelCase_ ) * function(UpperCamelCase_ ) > 0
): # if none of these are root and they are both positive or negative,
# then this algorithm can't find the root
raise ValueError('could not find root in given interval.' )
else:
SCREAMING_SNAKE_CASE__ = start + (end - start) / 2.0
while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7
if function(UpperCamelCase_ ) == 0:
return mid
elif function(UpperCamelCase_ ) * function(UpperCamelCase_ ) < 0:
SCREAMING_SNAKE_CASE__ = mid
else:
SCREAMING_SNAKE_CASE__ = mid
SCREAMING_SNAKE_CASE__ = start + (end - start) / 2.0
return mid
def _lowercase ( UpperCamelCase_ ) -> float:
'''simple docstring'''
return x**3 - 2 * x - 5
if __name__ == "__main__":
print(bisection(f, 1, 10_00))
import doctest
doctest.testmod()
| 400 | 1 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class lowercase_ ( A ):
__lowerCamelCase = ["image_processor", "tokenizer"]
__lowerCamelCase = "ViTImageProcessor"
__lowerCamelCase = ("CLIPTokenizer", "CLIPTokenizerFast")
def __init__( self , __A=None , __A=None , **__A ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE_ : Optional[int] =None
if "feature_extractor" in kwargs:
warnings.warn(
'''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
''' instead.''' , UpperCamelCase_ , )
SCREAMING_SNAKE_CASE_ : Optional[Any] =kwargs.pop('''feature_extractor''' )
SCREAMING_SNAKE_CASE_ : Union[str, Any] =image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('''You need to specify an `image_processor`.''' )
if tokenizer is None:
raise ValueError('''You need to specify a `tokenizer`.''' )
super().__init__(UpperCamelCase_ , UpperCamelCase_ )
def __call__( self , __A=None , __A=None , __A=None , __A=None , **__A ) -> str:
if text is None and visual_prompt is None and images is None:
raise ValueError('''You have to specify either text, visual prompt or images.''' )
if text is not None and visual_prompt is not None:
raise ValueError('''You have to specify exactly one type of prompt. Either text or visual prompt.''' )
if text is not None:
SCREAMING_SNAKE_CASE_ : Optional[Any] =self.tokenizer(UpperCamelCase_ , return_tensors=UpperCamelCase_ , **UpperCamelCase_ )
if visual_prompt is not None:
SCREAMING_SNAKE_CASE_ : List[str] =self.image_processor(UpperCamelCase_ , return_tensors=UpperCamelCase_ , **UpperCamelCase_ )
if images is not None:
SCREAMING_SNAKE_CASE_ : Dict =self.image_processor(UpperCamelCase_ , return_tensors=UpperCamelCase_ , **UpperCamelCase_ )
if visual_prompt is not None and images is not None:
SCREAMING_SNAKE_CASE_ : Tuple ={
"pixel_values": image_features.pixel_values,
"conditional_pixel_values": prompt_features.pixel_values,
}
return encoding
elif text is not None and images is not None:
SCREAMING_SNAKE_CASE_ : Union[str, Any] =image_features.pixel_values
return encoding
elif text is not None:
return encoding
elif visual_prompt is not None:
SCREAMING_SNAKE_CASE_ : Tuple ={
"conditional_pixel_values": prompt_features.pixel_values,
}
return encoding
else:
return BatchEncoding(data=dict(**UpperCamelCase_ ) , tensor_type=UpperCamelCase_ )
def _snake_case ( self , *__A , **__A ) -> str:
return self.tokenizer.batch_decode(*UpperCamelCase_ , **UpperCamelCase_ )
def _snake_case ( self , *__A , **__A ) -> Dict:
return self.tokenizer.decode(*UpperCamelCase_ , **UpperCamelCase_ )
@property
def _snake_case ( self ) -> Tuple:
warnings.warn(
'''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , UpperCamelCase_ , )
return self.image_processor_class
@property
def _snake_case ( self ) -> str:
warnings.warn(
'''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , UpperCamelCase_ , )
return self.image_processor
| 443 | '''simple docstring'''
def _lowercase ( lowerCamelCase__ = 1000 ) -> int:
"""simple docstring"""
__UpperCAmelCase : Union[str, Any] = 2**power
__UpperCAmelCase : Optional[int] = 0
while n:
__UpperCAmelCase , __UpperCAmelCase : Any = r + n % 10, n // 10
return r
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
| 168 | 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
SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE = {
"hustvl/yolos-small": "https://huggingface.co/hustvl/yolos-small/resolve/main/config.json",
# See all YOLOS models at https://huggingface.co/models?filter=yolos
}
class lowerCamelCase ( lowercase__ ):
'''simple docstring'''
lowerCAmelCase_ : List[str] = 'yolos'
def __init__( self , lowerCAmelCase=768 , lowerCAmelCase=12 , lowerCAmelCase=12 , lowerCAmelCase=3072 , lowerCAmelCase="gelu" , lowerCAmelCase=0.0 , lowerCAmelCase=0.0 , lowerCAmelCase=0.02 , lowerCAmelCase=1e-1_2 , lowerCAmelCase=[512, 864] , lowerCAmelCase=16 , lowerCAmelCase=3 , lowerCAmelCase=True , lowerCAmelCase=100 , lowerCAmelCase=True , lowerCAmelCase=False , lowerCAmelCase=1 , lowerCAmelCase=5 , lowerCAmelCase=2 , lowerCAmelCase=5 , lowerCAmelCase=2 , lowerCAmelCase=0.1 , **lowerCAmelCase , ):
super().__init__(**lowerCAmelCase )
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_ = initializer_range
UpperCAmelCase_ = layer_norm_eps
UpperCAmelCase_ = image_size
UpperCAmelCase_ = patch_size
UpperCAmelCase_ = num_channels
UpperCAmelCase_ = qkv_bias
UpperCAmelCase_ = num_detection_tokens
UpperCAmelCase_ = use_mid_position_embeddings
UpperCAmelCase_ = auxiliary_loss
# Hungarian matcher
UpperCAmelCase_ = class_cost
UpperCAmelCase_ = bbox_cost
UpperCAmelCase_ = giou_cost
# Loss coefficients
UpperCAmelCase_ = bbox_loss_coefficient
UpperCAmelCase_ = giou_loss_coefficient
UpperCAmelCase_ = eos_coefficient
class lowerCamelCase ( lowercase__ ):
'''simple docstring'''
lowerCAmelCase_ : Dict = version.parse('1.11' )
@property
def A__ ( self ):
return OrderedDict(
[
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
] )
@property
def A__ ( self ):
return 1e-4
@property
def A__ ( self ):
return 12
| 23 |
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 ( lowercase__, lowercase__ ):
'''simple docstring'''
@register_to_config
def __init__( self , lowerCAmelCase = 768 , ):
super().__init__()
UpperCAmelCase_ = nn.Parameter(torch.zeros(1 , lowerCAmelCase ) )
UpperCAmelCase_ = nn.Parameter(torch.ones(1 , lowerCAmelCase ) )
def A__ ( self , lowerCAmelCase = None , lowerCAmelCase = None , ):
UpperCAmelCase_ = nn.Parameter(self.mean.to(lowerCAmelCase ).to(lowerCAmelCase ) )
UpperCAmelCase_ = nn.Parameter(self.std.to(lowerCAmelCase ).to(lowerCAmelCase ) )
return self
def A__ ( self , lowerCAmelCase ):
UpperCAmelCase_ = (embeds - self.mean) * 1.0 / self.std
return embeds
def A__ ( self , lowerCAmelCase ):
UpperCAmelCase_ = (embeds * self.std) + self.mean
return embeds
| 23 | 1 |
"""simple docstring"""
from ...utils import is_torch_available, is_transformers_available
if is_transformers_available() and is_torch_available():
from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
| 609 |
"""simple docstring"""
import string
import numpy
def UpperCAmelCase__ (snake_case__ : int , snake_case__ : int ):
"""simple docstring"""
return b if a == 0 else greatest_common_divisor(b % a , snake_case__ )
class lowercase:
'''simple docstring'''
lowercase__ = string.ascii_uppercase + string.digits
# This cipher takes alphanumerics into account
# i.e. a total of 36 characters
# take x and return x % len(key_string)
lowercase__ = numpy.vectorize(lambda __a : x % 36 )
lowercase__ = numpy.vectorize(__a )
def __init__( self: str, a_: numpy.ndarray ):
'''simple docstring'''
_snake_case : Optional[Any] = self.modulus(a_ ) # mod36 calc's on the encrypt key
self.check_determinant() # validate the determinant of the encryption key
_snake_case : Tuple = encrypt_key.shape[0]
def UpperCamelCase_ ( self: Dict, a_: str ):
'''simple docstring'''
return self.key_string.index(a_ )
def UpperCamelCase_ ( self: List[Any], a_: int ):
'''simple docstring'''
return self.key_string[round(a_ )]
def UpperCamelCase_ ( self: str ):
'''simple docstring'''
_snake_case : Optional[int] = round(numpy.linalg.det(self.encrypt_key ) )
if det < 0:
_snake_case : str = det % len(self.key_string )
_snake_case : List[Any] = len(self.key_string )
if greatest_common_divisor(a_, len(self.key_string ) ) != 1:
_snake_case : Optional[Any] = (
f"determinant modular {req_l} of encryption key({det}) "
f"is not co prime w.r.t {req_l}.\nTry another key."
)
raise ValueError(a_ )
def UpperCamelCase_ ( self: Union[str, Any], a_: str ):
'''simple docstring'''
_snake_case : Dict = [char for char in text.upper() if char in self.key_string]
_snake_case : str = chars[-1]
while len(a_ ) % self.break_key != 0:
chars.append(a_ )
return "".join(a_ )
def UpperCamelCase_ ( self: List[Any], a_: str ):
'''simple docstring'''
_snake_case : List[Any] = self.process_text(text.upper() )
_snake_case : Any = """"""
for i in range(0, len(a_ ) - self.break_key + 1, self.break_key ):
_snake_case : List[Any] = text[i : i + self.break_key]
_snake_case : Dict = [self.replace_letters(a_ ) for char in batch]
_snake_case : List[Any] = numpy.array([vec] ).T
_snake_case : List[Any] = self.modulus(self.encrypt_key.dot(a_ ) ).T.tolist()[
0
]
_snake_case : str = """""".join(
self.replace_digits(a_ ) for num in batch_encrypted )
encrypted += encrypted_batch
return encrypted
def UpperCamelCase_ ( self: Any ):
'''simple docstring'''
_snake_case : str = round(numpy.linalg.det(self.encrypt_key ) )
if det < 0:
_snake_case : Any = det % len(self.key_string )
_snake_case : Dict = None
for i in range(len(self.key_string ) ):
if (det * i) % len(self.key_string ) == 1:
_snake_case : List[str] = i
break
_snake_case : List[Any] = (
det_inv
* numpy.linalg.det(self.encrypt_key )
* numpy.linalg.inv(self.encrypt_key )
)
return self.to_int(self.modulus(a_ ) )
def UpperCamelCase_ ( self: int, a_: str ):
'''simple docstring'''
_snake_case : List[str] = self.make_decrypt_key()
_snake_case : List[str] = self.process_text(text.upper() )
_snake_case : Any = """"""
for i in range(0, len(a_ ) - self.break_key + 1, self.break_key ):
_snake_case : Union[str, Any] = text[i : i + self.break_key]
_snake_case : int = [self.replace_letters(a_ ) for char in batch]
_snake_case : Optional[Any] = numpy.array([vec] ).T
_snake_case : List[Any] = self.modulus(decrypt_key.dot(a_ ) ).T.tolist()[0]
_snake_case : Dict = """""".join(
self.replace_digits(a_ ) for num in batch_decrypted )
decrypted += decrypted_batch
return decrypted
def UpperCAmelCase__ ():
"""simple docstring"""
_snake_case : List[str] = int(input("""Enter the order of the encryption key: """ ) )
_snake_case : int = []
print("""Enter each row of the encryption key with space separated integers""" )
for _ in range(snake_case__ ):
_snake_case : List[Any] = [int(snake_case__ ) for x in input().split()]
hill_matrix.append(snake_case__ )
_snake_case : Any = HillCipher(numpy.array(snake_case__ ) )
print("""Would you like to encrypt or decrypt some text? (1 or 2)""" )
_snake_case : Any = input("""\n1. Encrypt\n2. Decrypt\n""" )
if option == "1":
_snake_case : Optional[Any] = input("""What text would you like to encrypt?: """ )
print("""Your encrypted text is:""" )
print(hc.encrypt(snake_case__ ) )
elif option == "2":
_snake_case : List[Any] = input("""What text would you like to decrypt?: """ )
print("""Your decrypted text is:""" )
print(hc.decrypt(snake_case__ ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 609 | 1 |
'''simple docstring'''
import math
import qiskit
def _UpperCAmelCase ( a : int = 1 , a : int = 1 , a : int = 1 ) -> qiskit.result.counts.Counts:
"""simple docstring"""
if (
isinstance(a , a )
or isinstance(a , a )
or isinstance(a , a )
):
raise TypeError('inputs must be integers.' )
if (input_a < 0) or (input_a < 0) or (carry_in < 0):
raise ValueError('inputs must be positive.' )
if (
(math.floor(a ) != input_a)
or (math.floor(a ) != input_a)
or (math.floor(a ) != carry_in)
):
raise ValueError('inputs must be exact integers.' )
if (input_a > 2) or (input_a > 2) or (carry_in > 2):
raise ValueError('inputs must be less or equal to 2.' )
# build registers
lowercase_ : Optional[Any] = qiskit.QuantumRegister(4 , 'qr' )
lowercase_ : Dict = qiskit.ClassicalRegister(2 , 'cr' )
# list the entries
lowercase_ : Dict = [input_a, input_a, carry_in]
lowercase_ : Optional[Any] = qiskit.QuantumCircuit(a , a )
for i in range(0 , 3 ):
if entry[i] == 2:
quantum_circuit.h(a ) # for hadamard entries
elif entry[i] == 1:
quantum_circuit.x(a ) # for 1 entries
elif entry[i] == 0:
quantum_circuit.i(a ) # for 0 entries
# build the circuit
quantum_circuit.ccx(0 , 1 , 3 ) # ccx = toffoli gate
quantum_circuit.cx(0 , 1 )
quantum_circuit.ccx(1 , 2 , 3 )
quantum_circuit.cx(1 , 2 )
quantum_circuit.cx(0 , 1 )
quantum_circuit.measure([2, 3] , a ) # measure the last two qbits
lowercase_ : Dict = qiskit.Aer.get_backend('aer_simulator' )
lowercase_ : Tuple = qiskit.execute(a , a , shots=1_0_0_0 )
return job.result().get_counts(a )
if __name__ == "__main__":
print(f"""Total sum count for state is: {quantum_full_adder(1, 1, 1)}""")
| 7 |
'''simple docstring'''
from ..utils import DummyObject, requires_backends
class __magic_name__ ( metaclass=UpperCAmelCase_ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str = ['transformers', 'torch', 'note_seq']
def __init__( self , *_lowercase , **_lowercase ) -> Dict:
requires_backends(self , ['transformers', 'torch', 'note_seq'] )
@classmethod
def lowerCamelCase__ ( cls , *_lowercase , **_lowercase ) -> List[str]:
requires_backends(cls , ['transformers', 'torch', 'note_seq'] )
@classmethod
def lowerCamelCase__ ( cls , *_lowercase , **_lowercase ) -> Dict:
requires_backends(cls , ['transformers', 'torch', 'note_seq'] )
| 7 | 1 |
'''simple docstring'''
def UpperCamelCase__ ( lowerCAmelCase = 1_00_00_00 ):
"""simple docstring"""
_lowerCAmelCase = set(range(3 , lowerCAmelCase , 2 ) )
primes.add(2 )
for p in range(3 , lowerCAmelCase , 2 ):
if p not in primes:
continue
primes.difference_update(set(range(p * p , lowerCAmelCase , lowerCAmelCase ) ) )
_lowerCAmelCase = [float(lowerCAmelCase ) for n in range(limit + 1 )]
for p in primes:
for n in range(lowerCAmelCase , limit + 1 , lowerCAmelCase ):
phi[n] *= 1 - 1 / p
return int(sum(phi[2:] ) )
if __name__ == "__main__":
print(F"""{solution() = }""")
| 207 |
'''simple docstring'''
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
)
A__ : List[str] =logging.getLogger(__name__)
def UpperCamelCase__ ( ):
"""simple docstring"""
_lowerCAmelCase = argparse.ArgumentParser(
description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" )
parser.add_argument("""--file_path""" , type=lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" )
parser.add_argument("""--tokenizer_type""" , type=lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] )
parser.add_argument("""--tokenizer_name""" , type=lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" )
parser.add_argument("""--dump_file""" , type=lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" )
_lowerCAmelCase = parser.parse_args()
logger.info(f"Loading Tokenizer ({args.tokenizer_name})" )
if args.tokenizer_type == "bert":
_lowerCAmelCase = BertTokenizer.from_pretrained(args.tokenizer_name )
_lowerCAmelCase = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]`
_lowerCAmelCase = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]`
elif args.tokenizer_type == "roberta":
_lowerCAmelCase = RobertaTokenizer.from_pretrained(args.tokenizer_name )
_lowerCAmelCase = tokenizer.special_tokens_map["""cls_token"""] # `<s>`
_lowerCAmelCase = tokenizer.special_tokens_map["""sep_token"""] # `</s>`
elif args.tokenizer_type == "gpt2":
_lowerCAmelCase = GPTaTokenizer.from_pretrained(args.tokenizer_name )
_lowerCAmelCase = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>`
_lowerCAmelCase = 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:
_lowerCAmelCase = fp.readlines()
logger.info("""Start encoding""" )
logger.info(f"{len(lowerCAmelCase )} examples to process." )
_lowerCAmelCase = []
_lowerCAmelCase = 0
_lowerCAmelCase = 1_00_00
_lowerCAmelCase = time.time()
for text in data:
_lowerCAmelCase = f"{bos} {text.strip()} {sep}"
_lowerCAmelCase = tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase )
rslt.append(lowerCAmelCase )
iter += 1
if iter % interval == 0:
_lowerCAmelCase = time.time()
logger.info(f"{iter} examples processed. - {(end-start):.2f}s/{interval}expl" )
_lowerCAmelCase = time.time()
logger.info("""Finished binarization""" )
logger.info(f"{len(lowerCAmelCase )} examples processed." )
_lowerCAmelCase = f"{args.dump_file}.{args.tokenizer_name}.pickle"
_lowerCAmelCase = tokenizer.vocab_size
if vocab_size < (1 << 16):
_lowerCAmelCase = [np.uintaa(lowerCAmelCase ) for d in rslt]
else:
_lowerCAmelCase = [np.intaa(lowerCAmelCase ) for d in rslt]
random.shuffle(rslt_ )
logger.info(f"Dump to {dp_file}" )
with open(lowerCAmelCase , """wb""" ) as handle:
pickle.dump(rslt_ , lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL )
if __name__ == "__main__":
main()
| 207 | 1 |
'''simple docstring'''
import io
import os
import unicodedata
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
__lowercase = logging.get_logger(__name__)
__lowercase = '''▁'''
__lowercase = {'''vocab_file''': '''vocab.txt''', '''sentencepiece_model_ckpt''': '''sentencepiece.bpe.model'''}
__lowercase = {
'''sentencepiece_model_file''': '''sentencepiece.bpe.model''',
'''vocab_file''': '''vocab.txt''',
}
__lowercase = {
'''vocab_file''': {
'''ernie-m-base''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt''',
'''ernie-m-large''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt''',
},
'''sentencepiece_model_file''': {
'''ernie-m-base''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model''',
'''ernie-m-large''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model''',
},
}
__lowercase = {
'''ernie-m-base''': 5_14,
'''ernie-m-large''': 5_14,
}
__lowercase = {
'''ernie-m-base''': {'''do_lower_case''': False},
'''ernie-m-large''': {'''do_lower_case''': False},
}
class _snake_case ( lowerCAmelCase_ ):
"""simple docstring"""
_UpperCamelCase : List[str] = ["input_ids"]
_UpperCamelCase : Optional[int] = VOCAB_FILES_NAMES
_UpperCamelCase : int = PRETRAINED_INIT_CONFIGURATION
_UpperCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_UpperCamelCase : str = PRETRAINED_VOCAB_FILES_MAP
_UpperCamelCase : Union[str, Any] = RESOURCE_FILES_NAMES
def __init__( self : List[Any] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : int=None , UpperCamelCase_ : Dict=False , UpperCamelCase_ : str="utf8" , UpperCamelCase_ : Optional[int]="[UNK]" , UpperCamelCase_ : str="[SEP]" , UpperCamelCase_ : int="[PAD]" , UpperCamelCase_ : List[Any]="[CLS]" , UpperCamelCase_ : Optional[Any]="[MASK]" , UpperCamelCase_ : Optional[Dict[str, Any]] = None , **UpperCamelCase_ : str , ):
# Mask token behave like a normal word, i.e. include the space before it and
# is included in the raw text, there should be a match in a non-normalized sentence.
lowerCAmelCase_ : Optional[int] ={} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
do_lower_case=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , vocab_file=UpperCamelCase_ , encoding=UpperCamelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase_ , )
lowerCAmelCase_ : List[str] =do_lower_case
lowerCAmelCase_ : Any =sentencepiece_model_ckpt
lowerCAmelCase_ : List[str] =spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(UpperCamelCase_ )
# to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
if vocab_file is not None:
lowerCAmelCase_ : Tuple =self.load_vocab(filepath=UpperCamelCase_ )
else:
lowerCAmelCase_ : Any ={self.sp_model.id_to_piece(UpperCamelCase_ ): id for id in range(self.sp_model.get_piece_size() )}
lowerCAmelCase_ : Any ={v: k for k, v in self.vocab.items()}
def __A ( self : List[Any] , UpperCamelCase_ : Optional[int] ):
if text is None:
return None
lowerCAmelCase_ : Any =self.tokenize(UpperCamelCase_ )
lowerCAmelCase_ , lowerCAmelCase_ : int ='''''', []
for i, ch in enumerate(UpperCamelCase_ ):
if ch in self.SP_CHAR_MAPPING:
lowerCAmelCase_ : str =self.SP_CHAR_MAPPING.get(UpperCamelCase_ )
else:
lowerCAmelCase_ : Tuple =unicodedata.normalize('''NFKC''' , UpperCamelCase_ )
if self.is_whitespace(UpperCamelCase_ ):
continue
normalized_text += ch
char_mapping.extend([i] * len(UpperCamelCase_ ) )
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : List[str] =normalized_text, [], 0
if self.do_lower_case:
lowerCAmelCase_ : Optional[Any] =text.lower()
for token in split_tokens:
if token[:1] == "▁":
lowerCAmelCase_ : Union[str, Any] =token[1:]
lowerCAmelCase_ : str =text[offset:].index(UpperCamelCase_ ) + offset
lowerCAmelCase_ : Any =start + len(UpperCamelCase_ )
token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) )
lowerCAmelCase_ : Optional[Any] =end
return token_mapping
@property
def __A ( self : List[str] ):
return len(self.vocab )
def __A ( self : List[str] ):
return dict(self.vocab , **self.added_tokens_encoder )
def __getstate__( self : int ):
lowerCAmelCase_ : Union[str, Any] =self.__dict__.copy()
lowerCAmelCase_ : Union[str, Any] =None
return state
def __setstate__( self : str , UpperCamelCase_ : Optional[Any] ):
lowerCAmelCase_ : int =d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
lowerCAmelCase_ : Optional[int] ={}
lowerCAmelCase_ : int =spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.sentencepiece_model_ckpt )
def __A ( self : int , UpperCamelCase_ : Optional[Any] ):
return "".join((self.SP_CHAR_MAPPING.get(UpperCamelCase_ , UpperCamelCase_ ) for c in text) )
def __A ( self : Optional[Any] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Dict=False , UpperCamelCase_ : int=64 , UpperCamelCase_ : Dict=0.1 ):
if self.sp_model_kwargs.get('''enable_sampling''' ) is True:
lowerCAmelCase_ : List[str] =True
if self.sp_model_kwargs.get('''alpha''' ) is not None:
lowerCAmelCase_ : Optional[int] =self.sp_model_kwargs.get('''alpha''' )
if self.sp_model_kwargs.get('''nbest_size''' ) is not None:
lowerCAmelCase_ : Tuple =self.sp_model_kwargs.get('''nbest_size''' )
if not enable_sampling:
lowerCAmelCase_ : List[Any] =self.sp_model.EncodeAsPieces(UpperCamelCase_ )
else:
lowerCAmelCase_ : List[str] =self.sp_model.SampleEncodeAsPieces(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
lowerCAmelCase_ : Tuple =[]
for pi, piece in enumerate(UpperCamelCase_ ):
if piece == SPIECE_UNDERLINE:
if not pieces[pi + 1].startswith(UpperCamelCase_ ) and pi != 0:
new_pieces.append(UpperCamelCase_ )
continue
else:
continue
lowerCAmelCase_ : Optional[Any] =0
for i, chunk in enumerate(UpperCamelCase_ ):
if chunk == SPIECE_UNDERLINE:
continue
if self.is_ch_char(UpperCamelCase_ ) or self.is_punct(UpperCamelCase_ ):
if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
new_pieces.append(piece[lst_i:i] )
new_pieces.append(UpperCamelCase_ )
lowerCAmelCase_ : Dict =i + 1
elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit():
if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
new_pieces.append(piece[lst_i:i] )
lowerCAmelCase_ : Optional[Any] =i
elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit():
if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
new_pieces.append(piece[lst_i:i] )
lowerCAmelCase_ : Optional[Any] =i
if len(UpperCamelCase_ ) > lst_i:
new_pieces.append(piece[lst_i:] )
return new_pieces
def __A ( self : Tuple , UpperCamelCase_ : Optional[int] ):
lowerCAmelCase_ : List[Any] =''''''.join(UpperCamelCase_ ).replace(UpperCamelCase_ , ''' ''' ).strip()
return out_string
def __A ( self : Optional[Any] , UpperCamelCase_ : str ):
lowerCAmelCase_ : Optional[int] =self.convert_ids_to_tokens(UpperCamelCase_ )
lowerCAmelCase_ : Tuple =''''''.join(UpperCamelCase_ ).replace(UpperCamelCase_ , ''' ''' ).strip()
return out_string
def __A ( self : List[str] , UpperCamelCase_ : Optional[int] ):
return self.vocab.get(UpperCamelCase_ , self.vocab.get(self.unk_token ) )
def __A ( self : Union[str, Any] , UpperCamelCase_ : int ):
return self.reverse_vocab.get(UpperCamelCase_ , self.unk_token )
def __A ( self : str , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : List[str]=None ):
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
lowerCAmelCase_ : Optional[Any] =[self.cls_token_id]
lowerCAmelCase_ : List[Any] =[self.sep_token_id]
return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep
def __A ( self : Dict , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Optional[int]=None ):
if offset_mapping_a is None:
return [(0, 0)] + offset_mapping_a + [(0, 0)]
return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)]
def __A ( self : Tuple , UpperCamelCase_ : Dict , UpperCamelCase_ : str=None , UpperCamelCase_ : Union[str, Any]=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 not None:
return [1] + ([0] * len(UpperCamelCase_ )) + [1, 1] + ([0] * len(UpperCamelCase_ )) + [1]
return [1] + ([0] * len(UpperCamelCase_ )) + [1]
def __A ( self : List[str] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ):
# called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method
if token_ids_a is None:
# [CLS] X [SEP]
return (len(UpperCamelCase_ ) + 2) * [0]
# [CLS] A [SEP] [SEP] B [SEP]
return [0] * (len(UpperCamelCase_ ) + 1) + [1] * (len(UpperCamelCase_ ) + 3)
def __A ( self : List[str] , UpperCamelCase_ : Optional[Any] ):
if "\u4e00" <= char <= "\u9fff":
return True
return False
def __A ( self : Tuple , UpperCamelCase_ : Optional[Any] ):
if ("a" <= char <= "z") or ("A" <= char <= "Z"):
return True
return False
def __A ( self : List[Any] , UpperCamelCase_ : int ):
if char in ",;:.?!~,;:。?!《》【】":
return True
return False
def __A ( self : str , UpperCamelCase_ : List[str] ):
if char == " " or char == "\t" or char == "\n" or char == "\r":
return True
if len(UpperCamelCase_ ) == 1:
lowerCAmelCase_ : Optional[int] =unicodedata.category(UpperCamelCase_ )
if cat == "Zs":
return True
return False
def __A ( self : str , UpperCamelCase_ : Optional[Any] ):
lowerCAmelCase_ : Optional[Any] ={}
with io.open(UpperCamelCase_ , '''r''' , encoding='''utf-8''' ) as f:
for index, line in enumerate(UpperCamelCase_ ):
lowerCAmelCase_ : str =line.rstrip('''\n''' )
lowerCAmelCase_ : str =int(UpperCamelCase_ )
return token_to_idx
def __A ( self : Tuple , UpperCamelCase_ : str , UpperCamelCase_ : Optional[str] = None ):
lowerCAmelCase_ : List[Any] =0
if os.path.isdir(UpperCamelCase_ ):
lowerCAmelCase_ : str =os.path.join(
UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
else:
lowerCAmelCase_ : Any =(filename_prefix + '''-''' if filename_prefix else '''''') + save_directory
with open(UpperCamelCase_ , '''w''' , encoding='''utf-8''' ) as writer:
for token, token_index in sorted(self.vocab.items() , key=lambda UpperCamelCase_ : kv[1] ):
if index != token_index:
logger.warning(
F'Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'
''' Please check that the vocabulary is not corrupted!''' )
lowerCAmelCase_ : Dict =token_index
writer.write(token + '''\n''' )
index += 1
lowerCAmelCase_ : List[Any] =os.path.join(UpperCamelCase_ , '''sentencepiece.bpe.model''' )
with open(UpperCamelCase_ , '''wb''' ) as fi:
lowerCAmelCase_ : Dict =self.sp_model.serialized_model_proto()
fi.write(UpperCamelCase_ )
return (vocab_file,)
| 305 |
'''simple docstring'''
from collections import OrderedDict
from typing import Any, Mapping, Optional
from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging
__lowercase = logging.get_logger(__name__)
__lowercase = {
'''Helsinki-NLP/opus-mt-en-de''': '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json''',
# See all Marian models at https://huggingface.co/models?filter=marian
}
class _snake_case ( lowerCAmelCase_ ):
"""simple docstring"""
_UpperCamelCase : Dict = '''marian'''
_UpperCamelCase : List[str] = ['''past_key_values''']
_UpperCamelCase : Tuple = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''}
def __init__( self : Optional[int] , UpperCamelCase_ : Tuple=58101 , UpperCamelCase_ : int=None , UpperCamelCase_ : str=1024 , UpperCamelCase_ : List[str]=12 , UpperCamelCase_ : List[Any]=4096 , UpperCamelCase_ : Union[str, Any]=16 , UpperCamelCase_ : int=12 , UpperCamelCase_ : Optional[Any]=4096 , UpperCamelCase_ : Union[str, Any]=16 , UpperCamelCase_ : Optional[int]=0.0 , UpperCamelCase_ : Optional[Any]=0.0 , UpperCamelCase_ : Dict=True , UpperCamelCase_ : Union[str, Any]=True , UpperCamelCase_ : Optional[int]="gelu" , UpperCamelCase_ : int=1024 , UpperCamelCase_ : Optional[Any]=0.1 , UpperCamelCase_ : Dict=0.0 , UpperCamelCase_ : List[str]=0.0 , UpperCamelCase_ : Optional[int]=0.0_2 , UpperCamelCase_ : Union[str, Any]=58100 , UpperCamelCase_ : Union[str, Any]=False , UpperCamelCase_ : Union[str, Any]=58100 , UpperCamelCase_ : Dict=0 , UpperCamelCase_ : int=0 , UpperCamelCase_ : int=True , **UpperCamelCase_ : Union[str, Any] , ):
lowerCAmelCase_ : Tuple =vocab_size
lowerCAmelCase_ : int =decoder_vocab_size or vocab_size
lowerCAmelCase_ : int =max_position_embeddings
lowerCAmelCase_ : Any =d_model
lowerCAmelCase_ : List[Any] =encoder_ffn_dim
lowerCAmelCase_ : List[Any] =encoder_layers
lowerCAmelCase_ : Any =encoder_attention_heads
lowerCAmelCase_ : Optional[int] =decoder_ffn_dim
lowerCAmelCase_ : List[str] =decoder_layers
lowerCAmelCase_ : Union[str, Any] =decoder_attention_heads
lowerCAmelCase_ : List[str] =dropout
lowerCAmelCase_ : int =attention_dropout
lowerCAmelCase_ : Optional[int] =activation_dropout
lowerCAmelCase_ : Union[str, Any] =activation_function
lowerCAmelCase_ : List[str] =init_std
lowerCAmelCase_ : List[Any] =encoder_layerdrop
lowerCAmelCase_ : Optional[int] =decoder_layerdrop
lowerCAmelCase_ : int =use_cache
lowerCAmelCase_ : Tuple =encoder_layers
lowerCAmelCase_ : Any =scale_embedding # scale factor will be sqrt(d_model) if True
lowerCAmelCase_ : Union[str, Any] =share_encoder_decoder_embeddings
super().__init__(
pad_token_id=UpperCamelCase_ , eos_token_id=UpperCamelCase_ , is_encoder_decoder=UpperCamelCase_ , decoder_start_token_id=UpperCamelCase_ , forced_eos_token_id=UpperCamelCase_ , **UpperCamelCase_ , )
class _snake_case ( lowerCAmelCase_ ):
"""simple docstring"""
@property
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs
def __A ( self : str ):
if self.task in ["default", "seq2seq-lm"]:
lowerCAmelCase_ : List[str] =OrderedDict(
[
('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
] )
if self.use_past:
lowerCAmelCase_ : Any ={0: '''batch'''}
lowerCAmelCase_ : Any ={0: '''batch''', 1: '''past_decoder_sequence + sequence'''}
else:
lowerCAmelCase_ : List[Any] ={0: '''batch''', 1: '''decoder_sequence'''}
lowerCAmelCase_ : int ={0: '''batch''', 1: '''decoder_sequence'''}
if self.use_past:
self.fill_with_past_key_values_(UpperCamelCase_ , direction='''inputs''' )
elif self.task == "causal-lm":
# TODO: figure this case out.
lowerCAmelCase_ : List[str] =OrderedDict(
[
('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
] )
if self.use_past:
lowerCAmelCase_ , lowerCAmelCase_ : Optional[Any] =self.num_layers
for i in range(UpperCamelCase_ ):
lowerCAmelCase_ : int ={0: '''batch''', 2: '''past_sequence + sequence'''}
lowerCAmelCase_ : List[Any] ={0: '''batch''', 2: '''past_sequence + sequence'''}
else:
lowerCAmelCase_ : Optional[Any] =OrderedDict(
[
('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
('''decoder_input_ids''', {0: '''batch''', 1: '''decoder_sequence'''}),
('''decoder_attention_mask''', {0: '''batch''', 1: '''decoder_sequence'''}),
] )
return common_inputs
@property
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
def __A ( self : Union[str, Any] ):
if self.task in ["default", "seq2seq-lm"]:
lowerCAmelCase_ : List[str] =super().outputs
else:
lowerCAmelCase_ : Optional[Any] =super(UpperCamelCase_ , self ).outputs
if self.use_past:
lowerCAmelCase_ , lowerCAmelCase_ : Dict =self.num_layers
for i in range(UpperCamelCase_ ):
lowerCAmelCase_ : Optional[Any] ={0: '''batch''', 2: '''past_sequence + sequence'''}
lowerCAmelCase_ : Optional[Any] ={0: '''batch''', 2: '''past_sequence + sequence'''}
return common_outputs
def __A ( self : int , UpperCamelCase_ : PreTrainedTokenizer , UpperCamelCase_ : int = -1 , UpperCamelCase_ : int = -1 , UpperCamelCase_ : bool = False , UpperCamelCase_ : Optional[TensorType] = None , ):
lowerCAmelCase_ : Optional[Any] =self._generate_dummy_inputs_for_encoder_and_decoder(
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
# Generate decoder inputs
lowerCAmelCase_ : List[Any] =seq_length if not self.use_past else 1
lowerCAmelCase_ : Dict =self._generate_dummy_inputs_for_encoder_and_decoder(
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
lowerCAmelCase_ : Union[str, Any] ={F'decoder_{name}': tensor for name, tensor in decoder_inputs.items()}
lowerCAmelCase_ : List[Any] =dict(**UpperCamelCase_ , **UpperCamelCase_ )
if self.use_past:
if not is_torch_available():
raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' )
else:
import torch
lowerCAmelCase_ , lowerCAmelCase_ : Dict =common_inputs['''input_ids'''].shape
lowerCAmelCase_ : Tuple =common_inputs['''decoder_input_ids'''].shape[1]
lowerCAmelCase_ , lowerCAmelCase_ : Any =self.num_attention_heads
lowerCAmelCase_ : Optional[int] =(
batch,
num_encoder_attention_heads,
encoder_seq_length,
self._config.hidden_size // num_encoder_attention_heads,
)
lowerCAmelCase_ : Optional[int] =decoder_seq_length + 3
lowerCAmelCase_ : List[Any] =(
batch,
num_decoder_attention_heads,
decoder_past_length,
self._config.hidden_size // num_decoder_attention_heads,
)
lowerCAmelCase_ : Dict =torch.cat(
[common_inputs['''decoder_attention_mask'''], torch.ones(UpperCamelCase_ , UpperCamelCase_ )] , dim=1 )
lowerCAmelCase_ : int =[]
# If the number of encoder and decoder layers are present in the model configuration, both are considered
lowerCAmelCase_ , lowerCAmelCase_ : Dict =self.num_layers
lowerCAmelCase_ : Union[str, Any] =min(UpperCamelCase_ , UpperCamelCase_ )
lowerCAmelCase_ : Optional[Any] =max(UpperCamelCase_ , UpperCamelCase_ ) - min_num_layers
lowerCAmelCase_ : Union[str, Any] ='''encoder''' if num_encoder_layers > num_decoder_layers else '''decoder'''
for _ in range(UpperCamelCase_ ):
common_inputs["past_key_values"].append(
(
torch.zeros(UpperCamelCase_ ),
torch.zeros(UpperCamelCase_ ),
torch.zeros(UpperCamelCase_ ),
torch.zeros(UpperCamelCase_ ),
) )
# TODO: test this.
lowerCAmelCase_ : List[str] =encoder_shape if remaining_side_name == '''encoder''' else decoder_shape
for _ in range(UpperCamelCase_ , UpperCamelCase_ ):
common_inputs["past_key_values"].append((torch.zeros(UpperCamelCase_ ), torch.zeros(UpperCamelCase_ )) )
return common_inputs
def __A ( self : Optional[Any] , UpperCamelCase_ : PreTrainedTokenizer , UpperCamelCase_ : int = -1 , UpperCamelCase_ : int = -1 , UpperCamelCase_ : bool = False , UpperCamelCase_ : Optional[TensorType] = None , ):
lowerCAmelCase_ : str =self._generate_dummy_inputs_for_encoder_and_decoder(
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
if self.use_past:
if not is_torch_available():
raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' )
else:
import torch
lowerCAmelCase_ , lowerCAmelCase_ : List[Any] =common_inputs['''input_ids'''].shape
# Not using the same length for past_key_values
lowerCAmelCase_ : int =seqlen + 2
lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] =self.num_layers
lowerCAmelCase_ , lowerCAmelCase_ : List[Any] =self.num_attention_heads
lowerCAmelCase_ : Tuple =(
batch,
num_encoder_attention_heads,
past_key_values_length,
self._config.hidden_size // num_encoder_attention_heads,
)
lowerCAmelCase_ : Any =common_inputs['''attention_mask'''].dtype
lowerCAmelCase_ : List[str] =torch.cat(
[common_inputs['''attention_mask'''], torch.ones(UpperCamelCase_ , UpperCamelCase_ , dtype=UpperCamelCase_ )] , dim=1 )
lowerCAmelCase_ : List[str] =[
(torch.zeros(UpperCamelCase_ ), torch.zeros(UpperCamelCase_ )) for _ in range(UpperCamelCase_ )
]
return common_inputs
def __A ( self : List[Any] , UpperCamelCase_ : PreTrainedTokenizer , UpperCamelCase_ : int = -1 , UpperCamelCase_ : int = -1 , UpperCamelCase_ : bool = False , UpperCamelCase_ : Optional[TensorType] = None , ):
# Copied from OnnxConfig.generate_dummy_inputs
# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
lowerCAmelCase_ : Tuple =compute_effective_axis_dimension(
UpperCamelCase_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 )
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
lowerCAmelCase_ : List[Any] =tokenizer.num_special_tokens_to_add(UpperCamelCase_ )
lowerCAmelCase_ : Tuple =compute_effective_axis_dimension(
UpperCamelCase_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=UpperCamelCase_ )
# Generate dummy inputs according to compute batch and sequence
lowerCAmelCase_ : List[Any] =[''' '''.join([tokenizer.unk_token] ) * seq_length] * batch_size
lowerCAmelCase_ : Any =dict(tokenizer(UpperCamelCase_ , return_tensors=UpperCamelCase_ ) )
return common_inputs
def __A ( self : List[Any] , UpperCamelCase_ : PreTrainedTokenizer , UpperCamelCase_ : int = -1 , UpperCamelCase_ : int = -1 , UpperCamelCase_ : bool = False , UpperCamelCase_ : Optional[TensorType] = None , ):
if self.task in ["default", "seq2seq-lm"]:
lowerCAmelCase_ : Optional[Any] =self._generate_dummy_inputs_for_default_and_seqaseq_lm(
UpperCamelCase_ , batch_size=UpperCamelCase_ , seq_length=UpperCamelCase_ , is_pair=UpperCamelCase_ , framework=UpperCamelCase_ )
else:
lowerCAmelCase_ : int =self._generate_dummy_inputs_for_causal_lm(
UpperCamelCase_ , batch_size=UpperCamelCase_ , seq_length=UpperCamelCase_ , is_pair=UpperCamelCase_ , framework=UpperCamelCase_ )
return common_inputs
def __A ( self : Any , UpperCamelCase_ : List[str] , UpperCamelCase_ : List[str] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : int ):
if self.task in ["default", "seq2seq-lm"]:
lowerCAmelCase_ : Optional[Any] =super()._flatten_past_key_values_(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
else:
lowerCAmelCase_ : Dict =super(UpperCamelCase_ , self )._flatten_past_key_values_(
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
@property
def __A ( self : Union[str, Any] ):
return 1E-4
| 305 | 1 |
'''simple docstring'''
import argparse
import datetime
def _UpperCamelCase ( __UpperCamelCase ) -> str:
lowerCamelCase_ = {
'0': 'Sunday',
'1': 'Monday',
'2': 'Tuesday',
'3': 'Wednesday',
'4': 'Thursday',
'5': 'Friday',
'6': 'Saturday',
}
lowerCamelCase_ = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0}
# Validate
if not 0 < len(__UpperCamelCase ) < 11:
raise ValueError('Must be 10 characters long' )
# Get month
lowerCamelCase_ = int(date_input[0] + date_input[1] )
# Validate
if not 0 < m < 13:
raise ValueError('Month must be between 1 - 12' )
lowerCamelCase_ = date_input[2]
# Validate
if sep_a not in ["-", "/"]:
raise ValueError('Date separator must be \'-\' or \'/\'' )
# Get day
lowerCamelCase_ = int(date_input[3] + date_input[4] )
# Validate
if not 0 < d < 32:
raise ValueError('Date must be between 1 - 31' )
# Get second separator
lowerCamelCase_ = date_input[5]
# Validate
if sep_a not in ["-", "/"]:
raise ValueError('Date separator must be \'-\' or \'/\'' )
# Get year
lowerCamelCase_ = int(date_input[6] + date_input[7] + date_input[8] + date_input[9] )
# Arbitrary year range
if not 45 < y < 85_00:
raise ValueError(
'Year out of range. There has to be some sort of limit...right?' )
# Get datetime obj for validation
lowerCamelCase_ = datetime.date(int(__UpperCamelCase ) ,int(__UpperCamelCase ) ,int(__UpperCamelCase ) )
# Start math
if m <= 2:
lowerCamelCase_ = y - 1
lowerCamelCase_ = m + 12
# maths var
lowerCamelCase_ = int(str(__UpperCamelCase )[:2] )
lowerCamelCase_ = int(str(__UpperCamelCase )[2:] )
lowerCamelCase_ = int(2.6 * m - 5.39 )
lowerCamelCase_ = int(c / 4 )
lowerCamelCase_ = int(k / 4 )
lowerCamelCase_ = int(d + k )
lowerCamelCase_ = int(t + u + v + x )
lowerCamelCase_ = int(z - (2 * c) )
lowerCamelCase_ = round(w % 7 )
# End math
# Validate math
if f != convert_datetime_days[dt_ck.weekday()]:
raise AssertionError('The date was evaluated incorrectly. Contact developer.' )
# Response
lowerCamelCase_ = f'''Your date {date_input}, is a {days[str(__UpperCamelCase )]}!'''
return response
if __name__ == "__main__":
import doctest
doctest.testmod()
A_ = argparse.ArgumentParser(
description=(
"Find out what day of the week nearly any date is or was. Enter "
"date as a string in the mm-dd-yyyy or mm/dd/yyyy format"
)
)
parser.add_argument(
"date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)"
)
A_ = parser.parse_args()
zeller(args.date_input)
| 42 |
from math import ceil
def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> Tuple:
snake_case : Tuple = list(range(0 ,lowercase ) )
snake_case : Any = [item for sublist in list(device_map.values() ) for item in sublist]
# Duplicate check
snake_case : Optional[int] = []
for i in device_map_blocks:
if device_map_blocks.count(lowercase ) > 1 and i not in duplicate_blocks:
duplicate_blocks.append(lowercase )
# Missing blocks
snake_case : List[str] = [i for i in blocks if i not in device_map_blocks]
snake_case : Tuple = [i for i in device_map_blocks if i not in blocks]
if len(lowercase ) != 0:
raise ValueError(
"""Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device."""
""" These attention blocks were specified more than once: """ + str(lowercase ) )
if len(lowercase ) != 0:
raise ValueError(
"""There are attention blocks for this model that are not specified in the device_map. Add these attention """
"""blocks to a device on the device_map: """ + str(lowercase ) )
if len(lowercase ) != 0:
raise ValueError(
"""The device_map contains more attention blocks than this model has. Remove these from the device_map:"""
+ str(lowercase ) )
def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> int:
snake_case : Union[str, Any] = list(range(lowercase ) )
snake_case : Tuple = int(ceil(n_layers / len(lowercase ) ) )
snake_case : List[str] = [layers[i : i + n_blocks] for i in range(0 ,lowercase ,lowercase )]
return dict(zip(lowercase ,lowercase ) )
| 587 | 0 |
import random
import unittest
import torch
from diffusers import IFInpaintingSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device
from ..pipeline_params import (
TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin
@skip_mps
class UpperCAmelCase ( lowercase__ ,lowercase__ ,unittest.TestCase ):
SCREAMING_SNAKE_CASE__ = IFInpaintingSuperResolutionPipeline
SCREAMING_SNAKE_CASE__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''}
SCREAMING_SNAKE_CASE__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({'''original_image'''} )
SCREAMING_SNAKE_CASE__ = PipelineTesterMixin.required_optional_params - {'''latents'''}
def __lowerCAmelCase ( self ):
return self._get_superresolution_dummy_components()
def __lowerCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase=0 ):
if str(__lowerCamelCase ).startswith('''mps''' ):
_lowerCAmelCase = torch.manual_seed(__lowerCamelCase )
else:
_lowerCAmelCase = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase )
_lowerCAmelCase = floats_tensor((1, 3, 16, 16) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase )
_lowerCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase )
_lowerCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase )
_lowerCAmelCase = {
"prompt": "A painting of a squirrel eating a burger",
"image": image,
"original_image": original_image,
"mask_image": mask_image,
"generator": generator,
"num_inference_steps": 2,
"output_type": "numpy",
}
return inputs
@unittest.skipIf(
torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , )
def __lowerCAmelCase ( self ):
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 )
def __lowerCAmelCase ( self ):
self._test_save_load_optional_components()
@unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' )
def __lowerCAmelCase ( self ):
super().test_save_load_floataa(expected_max_diff=1E-1 )
def __lowerCAmelCase ( self ):
self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 )
def __lowerCAmelCase ( self ):
self._test_save_load_local()
def __lowerCAmelCase ( self ):
self._test_inference_batch_single_identical(
expected_max_diff=1E-2 , )
| 705 |
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class UpperCAmelCase ( snake_case_ ):
SCREAMING_SNAKE_CASE__ = '''ClapFeatureExtractor'''
SCREAMING_SNAKE_CASE__ = ('''RobertaTokenizer''', '''RobertaTokenizerFast''')
def __init__( self , _lowerCAmelCase , _lowerCAmelCase ):
super().__init__(_lowerCAmelCase , _lowerCAmelCase )
def __call__( self , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase=None , **_lowerCAmelCase ):
_lowerCAmelCase = kwargs.pop('''sampling_rate''' , _lowerCAmelCase )
if text is None and audios is None:
raise ValueError('''You have to specify either text or audios. Both cannot be none.''' )
if text is not None:
_lowerCAmelCase = self.tokenizer(_lowerCAmelCase , return_tensors=_lowerCAmelCase , **_lowerCAmelCase )
if audios is not None:
_lowerCAmelCase = self.feature_extractor(
_lowerCAmelCase , sampling_rate=_lowerCAmelCase , return_tensors=_lowerCAmelCase , **_lowerCAmelCase )
if text is not None and audios is not None:
_lowerCAmelCase = audio_features.input_features
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**_lowerCAmelCase ) , tensor_type=_lowerCAmelCase )
def __lowerCAmelCase ( self , *_lowerCAmelCase , **_lowerCAmelCase ):
return self.tokenizer.batch_decode(*_lowerCAmelCase , **_lowerCAmelCase )
def __lowerCAmelCase ( self , *_lowerCAmelCase , **_lowerCAmelCase ):
return self.tokenizer.decode(*_lowerCAmelCase , **_lowerCAmelCase )
@property
def __lowerCAmelCase ( self ):
_lowerCAmelCase = self.tokenizer.model_input_names
_lowerCAmelCase = self.feature_extractor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) ) | 664 | 0 |
import math
def lowerCamelCase__ (__lowerCamelCase ):
if not isinstance(__lowerCamelCase, __lowerCamelCase ):
_SCREAMING_SNAKE_CASE : Any = f"""Input value of [number={number}] must be an integer"""
raise TypeError(__lowerCamelCase )
if number < 1:
_SCREAMING_SNAKE_CASE : Union[str, Any] = f"""Input value of [number={number}] must be > 0"""
raise ValueError(__lowerCamelCase )
elif number == 1:
return 3
elif number == 2:
return 5
else:
_SCREAMING_SNAKE_CASE : Tuple = int(math.log(number // 3, 2 ) ) + 2
_SCREAMING_SNAKE_CASE : Optional[int] = [3, 5]
_SCREAMING_SNAKE_CASE : Optional[int] = 2
_SCREAMING_SNAKE_CASE : Union[str, Any] = 3
for block in range(1, __lowerCamelCase ):
for _ in range(__lowerCamelCase ):
proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] )
proth_index += 1
increment *= 2
return proth_list[number - 1]
if __name__ == "__main__":
import doctest
doctest.testmod()
for number in range(11):
UpperCamelCase__ =0
try:
UpperCamelCase__ =proth(number)
except ValueError:
print(f"ValueError: there is no {number}th Proth number")
continue
print(f"The {number}th Proth number: {value}") | 249 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_DEFAULT_MEAN,
IMAGENET_DEFAULT_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
is_batched,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, logging
UpperCamelCase__ =logging.get_logger(__name__)
class lowerCAmelCase__( __lowercase ):
'''simple docstring'''
__snake_case = ['pixel_values']
def __init__( self , __lowerCamelCase = True , __lowerCamelCase = None , __lowerCamelCase = PILImageResampling.BICUBIC , __lowerCamelCase = True , __lowerCamelCase = True , __lowerCamelCase = 1 / 2_5_5 , __lowerCamelCase = None , __lowerCamelCase = True , __lowerCamelCase = None , __lowerCamelCase = None , **__lowerCamelCase , ) -> None:
super().__init__(**__lowerCamelCase )
_SCREAMING_SNAKE_CASE : Union[str, Any] = size if size is not None else {"height": 2_2_4, "width": 2_2_4}
_SCREAMING_SNAKE_CASE : int = get_size_dict(__lowerCamelCase )
_SCREAMING_SNAKE_CASE : int = crop_size if crop_size is not None else {"height": 2_2_4, "width": 2_2_4}
_SCREAMING_SNAKE_CASE : Tuple = get_size_dict(__lowerCamelCase , default_to_square=__lowerCamelCase , param_name="crop_size" )
_SCREAMING_SNAKE_CASE : Optional[Any] = do_resize
_SCREAMING_SNAKE_CASE : str = do_rescale
_SCREAMING_SNAKE_CASE : Tuple = do_normalize
_SCREAMING_SNAKE_CASE : Any = do_center_crop
_SCREAMING_SNAKE_CASE : Dict = crop_size
_SCREAMING_SNAKE_CASE : Optional[int] = size
_SCREAMING_SNAKE_CASE : int = resample
_SCREAMING_SNAKE_CASE : Optional[Any] = rescale_factor
_SCREAMING_SNAKE_CASE : str = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
_SCREAMING_SNAKE_CASE : Any = image_std if image_std is not None else IMAGENET_DEFAULT_STD
def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = PILImageResampling.BILINEAR , __lowerCamelCase = None , **__lowerCamelCase , ) -> np.ndarray:
_SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(__lowerCamelCase )
if "shortest_edge" in size:
_SCREAMING_SNAKE_CASE : Any = get_resize_output_image_size(__lowerCamelCase , size=size["shortest_edge"] , default_to_square=__lowerCamelCase )
# size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
elif "height" in size and "width" in size:
_SCREAMING_SNAKE_CASE : Optional[Any] = (size["height"], size["width"])
else:
raise ValueError(F"""Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}""" )
return resize(__lowerCamelCase , size=__lowerCamelCase , resample=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase )
def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , **__lowerCamelCase , ) -> np.ndarray:
_SCREAMING_SNAKE_CASE : Tuple = get_size_dict(__lowerCamelCase )
if "height" not in size or "width" not in size:
raise ValueError(F"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" )
return center_crop(__lowerCamelCase , size=(size["height"], size["width"]) , data_format=__lowerCamelCase , **__lowerCamelCase )
def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , **__lowerCamelCase ) -> np.ndarray:
return rescale(__lowerCamelCase , scale=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase )
def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , **__lowerCamelCase , ) -> np.ndarray:
return normalize(__lowerCamelCase , mean=__lowerCamelCase , std=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase )
def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = ChannelDimension.FIRST , **__lowerCamelCase , ) -> BatchFeature:
_SCREAMING_SNAKE_CASE : str = do_resize if do_resize is not None else self.do_resize
_SCREAMING_SNAKE_CASE : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale
_SCREAMING_SNAKE_CASE : List[Any] = do_normalize if do_normalize is not None else self.do_normalize
_SCREAMING_SNAKE_CASE : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop
_SCREAMING_SNAKE_CASE : Dict = crop_size if crop_size is not None else self.crop_size
_SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(__lowerCamelCase , param_name="crop_size" , default_to_square=__lowerCamelCase )
_SCREAMING_SNAKE_CASE : List[Any] = resample if resample is not None else self.resample
_SCREAMING_SNAKE_CASE : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor
_SCREAMING_SNAKE_CASE : List[Any] = image_mean if image_mean is not None else self.image_mean
_SCREAMING_SNAKE_CASE : Any = image_std if image_std is not None else self.image_std
_SCREAMING_SNAKE_CASE : List[Any] = size if size is not None else self.size
_SCREAMING_SNAKE_CASE : Dict = get_size_dict(__lowerCamelCase )
if not is_batched(__lowerCamelCase ):
_SCREAMING_SNAKE_CASE : Optional[Any] = [images]
if not valid_images(__lowerCamelCase ):
raise ValueError(
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
"torch.Tensor, tf.Tensor or jax.ndarray." )
if do_resize and size is None:
raise ValueError("Size must be specified if do_resize is True." )
if do_center_crop and crop_size is None:
raise ValueError("Crop size must be specified if do_center_crop is True." )
if do_rescale and rescale_factor is None:
raise ValueError("Rescale factor must be specified if do_rescale is True." )
# All transformations expect numpy arrays.
_SCREAMING_SNAKE_CASE : str = [to_numpy_array(__lowerCamelCase ) for image in images]
if do_resize:
_SCREAMING_SNAKE_CASE : Optional[int] = [self.resize(image=__lowerCamelCase , size=__lowerCamelCase , resample=__lowerCamelCase ) for image in images]
if do_center_crop:
_SCREAMING_SNAKE_CASE : Any = [self.center_crop(image=__lowerCamelCase , size=__lowerCamelCase ) for image in images]
if do_rescale:
_SCREAMING_SNAKE_CASE : int = [self.rescale(image=__lowerCamelCase , scale=__lowerCamelCase ) for image in images]
if do_normalize:
_SCREAMING_SNAKE_CASE : Any = [self.normalize(image=__lowerCamelCase , mean=__lowerCamelCase , std=__lowerCamelCase ) for image in images]
_SCREAMING_SNAKE_CASE : List[Any] = [to_channel_dimension_format(__lowerCamelCase , __lowerCamelCase ) for image in images]
_SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": images}
return BatchFeature(data=__lowerCamelCase , tensor_type=__lowerCamelCase ) | 249 | 1 |
from bisect import bisect
from itertools import accumulate
def lowerCAmelCase__ ( a__ , a__ , a__ , a__ ) ->Tuple:
'''simple docstring'''
_UpperCamelCase = sorted(zip(a__ , a__ ) , key=lambda a__ : x[0] / x[1] , reverse=a__ )
_UpperCamelCase , _UpperCamelCase = [i[0] for i in r], [i[1] for i in r]
_UpperCamelCase = list(accumulate(a__ ) )
_UpperCamelCase = bisect(a__ , a__ )
return (
0
if k == 0
else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k])
if k != n
else sum(vl[:k] )
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 714 | def lowerCAmelCase__ ( a__ ) ->int:
'''simple docstring'''
assert (
isinstance(a__ , a__ ) and number_of_steps > 0
), f'number_of_steps needs to be positive integer, your input {number_of_steps}'
if number_of_steps == 1:
return 1
_UpperCamelCase , _UpperCamelCase = 1, 1
for _ in range(number_of_steps - 1 ):
_UpperCamelCase , _UpperCamelCase = current + previous, current
return current
if __name__ == "__main__":
import doctest
doctest.testmod()
| 82 | 0 |
def __magic_name__ ( __lowerCAmelCase : str ) -> list:
__lowerCamelCase = [0] * len(__lowerCAmelCase )
for i in range(1 , len(__lowerCAmelCase ) ):
# use last results for better performance - dynamic programming
__lowerCamelCase = prefix_result[i - 1]
while j > 0 and input_string[i] != input_string[j]:
__lowerCamelCase = prefix_result[j - 1]
if input_string[i] == input_string[j]:
j += 1
__lowerCamelCase = j
return prefix_result
def __magic_name__ ( __lowerCAmelCase : str ) -> int:
return max(prefix_function(__lowerCAmelCase ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 298 |
import unittest
import numpy as np
import requests
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
SCREAMING_SNAKE_CASE__ : Dict = False
if is_vision_available():
from PIL import Image
from transformers import PixaStructImageProcessor
class lowerCAmelCase__ ( unittest.TestCase ):
def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[Any]=7 , SCREAMING_SNAKE_CASE__ : str=3 , SCREAMING_SNAKE_CASE__ : List[str]=18 , SCREAMING_SNAKE_CASE__ : Optional[int]=30 , SCREAMING_SNAKE_CASE__ : Optional[Any]=4_00 , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : List[str]=None , ) -> Dict:
__lowerCamelCase = size if size is not None else {'''height''': 20, '''width''': 20}
__lowerCamelCase = parent
__lowerCamelCase = batch_size
__lowerCamelCase = num_channels
__lowerCamelCase = image_size
__lowerCamelCase = min_resolution
__lowerCamelCase = max_resolution
__lowerCamelCase = size
__lowerCamelCase = do_normalize
__lowerCamelCase = do_convert_rgb
__lowerCamelCase = [5_12, 10_24, 20_48, 40_96]
__lowerCamelCase = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16}
def __A ( self : Union[str, Any] ) -> Optional[int]:
return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}
def __A ( self : int ) -> Dict:
__lowerCamelCase = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
__lowerCamelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ).convert('''RGB''' )
return raw_image
@unittest.skipIf(
not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , )
@require_torch
@require_vision
class lowerCAmelCase__ ( __lowercase , unittest.TestCase ):
a__ : Optional[Any] = PixaStructImageProcessor if is_vision_available() else None
def __A ( self : Any ) -> Tuple:
__lowerCamelCase = PixaStructImageProcessingTester(self )
@property
def __A ( self : Any ) -> Dict:
return self.image_processor_tester.prepare_image_processor_dict()
def __A ( self : List[str] ) -> Tuple:
__lowerCamelCase = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) )
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) )
def __A ( self : Optional[Any] ) -> List[str]:
__lowerCamelCase = self.image_processor_tester.prepare_dummy_image()
__lowerCamelCase = self.image_processing_class(**self.image_processor_dict )
__lowerCamelCase = 20_48
__lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ )
self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) )
def __A ( self : Optional[int] ) -> Union[str, Any]:
# Initialize image_processor
__lowerCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ )
for image in image_inputs:
self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image )
# Test not batched input
__lowerCamelCase = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* self.image_processor_tester.num_channels
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
__lowerCamelCase = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
__lowerCamelCase = image_processor(
SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
def __A ( self : Any ) -> Dict:
# Initialize image_processor
__lowerCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ )
for image in image_inputs:
self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image )
# Test not batched input
__lowerCamelCase = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* self.image_processor_tester.num_channels
) + 2
__lowerCamelCase = True
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
with self.assertRaises(SCREAMING_SNAKE_CASE__ ):
__lowerCamelCase = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches
__lowerCamelCase = '''Hello'''
__lowerCamelCase = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
__lowerCamelCase = image_processor(
SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
def __A ( self : int ) -> Union[str, Any]:
# Initialize image_processor
__lowerCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ )
for image in image_inputs:
self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray )
__lowerCamelCase = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* self.image_processor_tester.num_channels
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
__lowerCamelCase = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
__lowerCamelCase = image_processor(
SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
def __A ( self : Any ) -> int:
# Initialize image_processor
__lowerCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ )
for image in image_inputs:
self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor )
# Test not batched input
__lowerCamelCase = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* self.image_processor_tester.num_channels
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
__lowerCamelCase = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
__lowerCamelCase = image_processor(
SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
@unittest.skipIf(
not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , )
@require_torch
@require_vision
class lowerCAmelCase__ ( __lowercase , unittest.TestCase ):
a__ : Optional[int] = PixaStructImageProcessor if is_vision_available() else None
def __A ( self : List[str] ) -> Optional[Any]:
__lowerCamelCase = PixaStructImageProcessingTester(self , num_channels=4 )
__lowerCamelCase = 3
@property
def __A ( self : List[Any] ) -> Union[str, Any]:
return self.image_processor_tester.prepare_image_processor_dict()
def __A ( self : Optional[int] ) -> Any:
__lowerCamelCase = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) )
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) )
def __A ( self : Optional[int] ) -> Any:
# Initialize image_processor
__lowerCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ )
for image in image_inputs:
self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image )
# Test not batched input
__lowerCamelCase = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* (self.image_processor_tester.num_channels - 1)
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
__lowerCamelCase = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
__lowerCamelCase = image_processor(
SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
| 298 | 1 |
"""simple docstring"""
import gc
import unittest
from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline
from transformers.pipelines import PipelineException
from transformers.testing_utils import (
is_pipeline_test,
is_torch_available,
nested_simplify,
require_tf,
require_torch,
require_torch_gpu,
slow,
)
from .test_pipelines_common import ANY
@is_pipeline_test
class _a ( unittest.TestCase ):
a_ : Optional[int] = MODEL_FOR_MASKED_LM_MAPPING
a_ : List[Any] = TF_MODEL_FOR_MASKED_LM_MAPPING
def _UpperCamelCase ( self : str ):
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
if is_torch_available():
import torch
torch.cuda.empty_cache()
@require_tf
def _UpperCamelCase ( self : Any ):
lowerCamelCase__ = pipeline(task='fill-mask' , model='sshleifer/tiny-distilroberta-base' , top_k=2 , framework='tf' )
lowerCamelCase__ = unmasker('My name is <mask>' )
self.assertEqual(
nested_simplify(UpperCAmelCase__ , decimals=6 ) , [
{'sequence': 'My name is grouped', 'score': 2.1e-05, 'token': 3_80_15, 'token_str': ' grouped'},
{'sequence': 'My name is accuser', 'score': 2.1e-05, 'token': 2_55_06, 'token_str': ' accuser'},
] , )
lowerCamelCase__ = unmasker('The largest city in France is <mask>' )
self.assertEqual(
nested_simplify(UpperCAmelCase__ , decimals=6 ) , [
{
'sequence': 'The largest city in France is grouped',
'score': 2.1e-05,
'token': 3_80_15,
'token_str': ' grouped',
},
{
'sequence': 'The largest city in France is accuser',
'score': 2.1e-05,
'token': 2_55_06,
'token_str': ' accuser',
},
] , )
lowerCamelCase__ = unmasker('My name is <mask>' , targets=[' Patrick', ' Clara', ' Teven'] , top_k=3 )
self.assertEqual(
nested_simplify(UpperCAmelCase__ , decimals=6 ) , [
{'sequence': 'My name is Clara', 'score': 2e-05, 'token': 1_36_06, 'token_str': ' Clara'},
{'sequence': 'My name is Patrick', 'score': 2e-05, 'token': 34_99, 'token_str': ' Patrick'},
{'sequence': 'My name is Te', 'score': 1.9e-05, 'token': 29_41, 'token_str': ' Te'},
] , )
@require_torch
def _UpperCamelCase ( self : Any ):
lowerCamelCase__ = pipeline(task='fill-mask' , model='sshleifer/tiny-distilroberta-base' , top_k=2 , framework='pt' )
lowerCamelCase__ = unmasker('My name is <mask>' )
self.assertEqual(
nested_simplify(UpperCAmelCase__ , decimals=6 ) , [
{'sequence': 'My name is Maul', 'score': 2.2e-05, 'token': 3_56_76, 'token_str': ' Maul'},
{'sequence': 'My name isELS', 'score': 2.2e-05, 'token': 1_64_16, 'token_str': 'ELS'},
] , )
lowerCamelCase__ = unmasker('The largest city in France is <mask>' )
self.assertEqual(
nested_simplify(UpperCAmelCase__ , decimals=6 ) , [
{
'sequence': 'The largest city in France is Maul',
'score': 2.2e-05,
'token': 3_56_76,
'token_str': ' Maul',
},
{'sequence': 'The largest city in France isELS', 'score': 2.2e-05, 'token': 1_64_16, 'token_str': 'ELS'},
] , )
lowerCamelCase__ = unmasker('My name is <mask>' , targets=[' Patrick', ' Clara', ' Teven'] , top_k=3 )
self.assertEqual(
nested_simplify(UpperCAmelCase__ , decimals=6 ) , [
{'sequence': 'My name is Patrick', 'score': 2.1e-05, 'token': 34_99, 'token_str': ' Patrick'},
{'sequence': 'My name is Te', 'score': 2e-05, 'token': 29_41, 'token_str': ' Te'},
{'sequence': 'My name is Clara', 'score': 2e-05, 'token': 1_36_06, 'token_str': ' Clara'},
] , )
lowerCamelCase__ = unmasker('My name is <mask> <mask>' , top_k=2 )
self.assertEqual(
nested_simplify(UpperCAmelCase__ , decimals=6 ) , [
[
{
'score': 2.2e-05,
'token': 3_56_76,
'token_str': ' Maul',
'sequence': '<s>My name is Maul<mask></s>',
},
{'score': 2.2e-05, 'token': 1_64_16, 'token_str': 'ELS', 'sequence': '<s>My name isELS<mask></s>'},
],
[
{
'score': 2.2e-05,
'token': 3_56_76,
'token_str': ' Maul',
'sequence': '<s>My name is<mask> Maul</s>',
},
{'score': 2.2e-05, 'token': 1_64_16, 'token_str': 'ELS', 'sequence': '<s>My name is<mask>ELS</s>'},
],
] , )
@require_torch_gpu
def _UpperCamelCase ( self : Tuple ):
lowerCamelCase__ = pipeline('fill-mask' , model='hf-internal-testing/tiny-random-distilbert' , device=0 , framework='pt' )
# convert model to fp16
pipe.model.half()
lowerCamelCase__ = pipe('Paris is the [MASK] of France.' )
# We actually don't care about the result, we just want to make sure
# it works, meaning the float16 tensor got casted back to float32
# for postprocessing.
self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ )
@slow
@require_torch
def _UpperCamelCase ( self : Dict ):
lowerCamelCase__ = pipeline(task='fill-mask' , model='distilroberta-base' , top_k=2 , framework='pt' )
self.run_large_test(UpperCAmelCase__ )
@slow
@require_tf
def _UpperCamelCase ( self : Optional[Any] ):
lowerCamelCase__ = pipeline(task='fill-mask' , model='distilroberta-base' , top_k=2 , framework='tf' )
self.run_large_test(UpperCAmelCase__ )
def _UpperCamelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : Dict ):
lowerCamelCase__ = unmasker('My name is <mask>' )
self.assertEqual(
nested_simplify(UpperCAmelCase__ ) , [
{'sequence': 'My name is John', 'score': 0.0_08, 'token': 6_10, 'token_str': ' John'},
{'sequence': 'My name is Chris', 'score': 0.0_07, 'token': 15_73, 'token_str': ' Chris'},
] , )
lowerCamelCase__ = unmasker('The largest city in France is <mask>' )
self.assertEqual(
nested_simplify(UpperCAmelCase__ ) , [
{
'sequence': 'The largest city in France is Paris',
'score': 0.2_51,
'token': 22_01,
'token_str': ' Paris',
},
{
'sequence': 'The largest city in France is Lyon',
'score': 0.2_14,
'token': 1_27_90,
'token_str': ' Lyon',
},
] , )
lowerCamelCase__ = unmasker('My name is <mask>' , targets=[' Patrick', ' Clara', ' Teven'] , top_k=3 )
self.assertEqual(
nested_simplify(UpperCAmelCase__ ) , [
{'sequence': 'My name is Patrick', 'score': 0.0_05, 'token': 34_99, 'token_str': ' Patrick'},
{'sequence': 'My name is Clara', 'score': 0.0_00, 'token': 1_36_06, 'token_str': ' Clara'},
{'sequence': 'My name is Te', 'score': 0.0_00, 'token': 29_41, 'token_str': ' Te'},
] , )
@require_torch
def _UpperCamelCase ( self : Any ):
lowerCamelCase__ = pipeline(task='fill-mask' , model='sshleifer/tiny-distilroberta-base' , framework='pt' )
lowerCamelCase__ = None
lowerCamelCase__ = None
self.run_pipeline_test(UpperCAmelCase__ , [] )
@require_tf
def _UpperCamelCase ( self : Dict ):
lowerCamelCase__ = pipeline(task='fill-mask' , model='sshleifer/tiny-distilroberta-base' , framework='tf' )
lowerCamelCase__ = None
lowerCamelCase__ = None
self.run_pipeline_test(UpperCAmelCase__ , [] )
def _UpperCamelCase ( self : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ):
if tokenizer is None or tokenizer.mask_token_id is None:
self.skipTest('The provided tokenizer has no mask token, (probably reformer or wav2vec2)' )
lowerCamelCase__ = FillMaskPipeline(model=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ )
lowerCamelCase__ = [
F'This is another {tokenizer.mask_token} test',
]
return fill_masker, examples
def _UpperCamelCase ( self : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ):
lowerCamelCase__ = fill_masker.tokenizer
lowerCamelCase__ = fill_masker.model
lowerCamelCase__ = fill_masker(
F'This is a {tokenizer.mask_token}' , )
self.assertEqual(
UpperCAmelCase__ , [
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
] , )
lowerCamelCase__ = fill_masker([F'This is a {tokenizer.mask_token}'] )
self.assertEqual(
UpperCAmelCase__ , [
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
] , )
lowerCamelCase__ = fill_masker([F'This is a {tokenizer.mask_token}', F'Another {tokenizer.mask_token} great test.'] )
self.assertEqual(
UpperCAmelCase__ , [
[
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
],
[
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
],
] , )
with self.assertRaises(UpperCAmelCase__ ):
fill_masker([None] )
# No mask_token is not supported
with self.assertRaises(UpperCAmelCase__ ):
fill_masker('This is' )
self.run_test_top_k(UpperCAmelCase__ , UpperCAmelCase__ )
self.run_test_targets(UpperCAmelCase__ , UpperCAmelCase__ )
self.run_test_top_k_targets(UpperCAmelCase__ , UpperCAmelCase__ )
self.fill_mask_with_duplicate_targets_and_top_k(UpperCAmelCase__ , UpperCAmelCase__ )
self.fill_mask_with_multiple_masks(UpperCAmelCase__ , UpperCAmelCase__ )
def _UpperCamelCase ( self : str , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int ):
lowerCamelCase__ = tokenizer.get_vocab()
lowerCamelCase__ = sorted(vocab.keys() )[:2]
# Pipeline argument
lowerCamelCase__ = FillMaskPipeline(model=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , targets=UpperCAmelCase__ )
lowerCamelCase__ = fill_masker(F'This is a {tokenizer.mask_token}' )
self.assertEqual(
UpperCAmelCase__ , [
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
] , )
lowerCamelCase__ = {vocab[el] for el in targets}
self.assertEqual({el['token'] for el in outputs} , UpperCAmelCase__ )
lowerCamelCase__ = [tokenizer.decode([x] ) for x in target_ids]
self.assertEqual({el['token_str'] for el in outputs} , set(UpperCAmelCase__ ) )
# Call argument
lowerCamelCase__ = FillMaskPipeline(model=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ )
lowerCamelCase__ = fill_masker(F'This is a {tokenizer.mask_token}' , targets=UpperCAmelCase__ )
self.assertEqual(
UpperCAmelCase__ , [
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
] , )
lowerCamelCase__ = {vocab[el] for el in targets}
self.assertEqual({el['token'] for el in outputs} , UpperCAmelCase__ )
lowerCamelCase__ = [tokenizer.decode([x] ) for x in target_ids]
self.assertEqual({el['token_str'] for el in outputs} , set(UpperCAmelCase__ ) )
# Score equivalence
lowerCamelCase__ = fill_masker(F'This is a {tokenizer.mask_token}' , targets=UpperCAmelCase__ )
lowerCamelCase__ = [top_mask['''token_str'''] for top_mask in outputs]
lowerCamelCase__ = [top_mask['''score'''] for top_mask in outputs]
# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
if set(UpperCAmelCase__ ) == set(UpperCAmelCase__ ):
lowerCamelCase__ = fill_masker(F'This is a {tokenizer.mask_token}' , targets=UpperCAmelCase__ )
lowerCamelCase__ = [top_mask['''score'''] for top_mask in unmasked_targets]
self.assertEqual(nested_simplify(UpperCAmelCase__ ) , nested_simplify(UpperCAmelCase__ ) )
# Raises with invalid
with self.assertRaises(UpperCAmelCase__ ):
lowerCamelCase__ = fill_masker(F'This is a {tokenizer.mask_token}' , targets=[] )
# For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised
if "" not in tokenizer.get_vocab():
with self.assertRaises(UpperCAmelCase__ ):
lowerCamelCase__ = fill_masker(F'This is a {tokenizer.mask_token}' , targets=[''] )
with self.assertRaises(UpperCAmelCase__ ):
lowerCamelCase__ = fill_masker(F'This is a {tokenizer.mask_token}' , targets='' )
def _UpperCamelCase ( self : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] ):
lowerCamelCase__ = FillMaskPipeline(model=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , top_k=2 )
lowerCamelCase__ = fill_masker(F'This is a {tokenizer.mask_token}' )
self.assertEqual(
UpperCAmelCase__ , [
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
] , )
lowerCamelCase__ = FillMaskPipeline(model=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ )
lowerCamelCase__ = fill_masker(F'This is a {tokenizer.mask_token}' , top_k=2 )
self.assertEqual(
UpperCAmelCase__ , [
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
] , )
self.assertEqual(nested_simplify(UpperCAmelCase__ ) , nested_simplify(UpperCAmelCase__ ) )
def _UpperCamelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] ):
lowerCamelCase__ = tokenizer.get_vocab()
lowerCamelCase__ = FillMaskPipeline(model=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ )
# top_k=2, ntargets=3
lowerCamelCase__ = sorted(vocab.keys() )[:3]
lowerCamelCase__ = fill_masker(F'This is a {tokenizer.mask_token}' , top_k=2 , targets=UpperCAmelCase__ )
# If we use the most probably targets, and filter differently, we should still
# have the same results
lowerCamelCase__ = [el['''token_str'''] for el in sorted(UpperCAmelCase__ , key=lambda SCREAMING_SNAKE_CASE__ : x["score"] , reverse=UpperCAmelCase__ )]
# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
if set(UpperCAmelCase__ ).issubset(UpperCAmelCase__ ):
lowerCamelCase__ = fill_masker(F'This is a {tokenizer.mask_token}' , top_k=3 , targets=UpperCAmelCase__ )
# They should yield exactly the same result
self.assertEqual(nested_simplify(UpperCAmelCase__ ) , nested_simplify(UpperCAmelCase__ ) )
def _UpperCamelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any ):
lowerCamelCase__ = FillMaskPipeline(model=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ )
lowerCamelCase__ = tokenizer.get_vocab()
# String duplicates + id duplicates
lowerCamelCase__ = sorted(vocab.keys() )[:3]
lowerCamelCase__ = [targets[0], targets[1], targets[0], targets[2], targets[1]]
lowerCamelCase__ = fill_masker(F'My name is {tokenizer.mask_token}' , targets=UpperCAmelCase__ , top_k=10 )
# The target list contains duplicates, so we can't output more
# than them
self.assertEqual(len(UpperCAmelCase__ ) , 3 )
def _UpperCamelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] ):
lowerCamelCase__ = FillMaskPipeline(model=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ )
lowerCamelCase__ = fill_masker(
F'This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}' , top_k=2 )
self.assertEqual(
UpperCAmelCase__ , [
[
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
],
[
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
],
[
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
{'sequence': ANY(UpperCAmelCase__ ), 'score': ANY(UpperCAmelCase__ ), 'token': ANY(UpperCAmelCase__ ), 'token_str': ANY(UpperCAmelCase__ )},
],
] , )
| 700 |
"""simple docstring"""
def snake_case ( _a: int , _a: list[int] , _a: int )-> int:
'''simple docstring'''
def count_of_possible_combinations(_a: int ) -> int:
if target < 0:
return 0
if target == 0:
return 1
return sum(count_of_possible_combinations(target - item ) for item in array )
return count_of_possible_combinations(_a )
def snake_case ( _a: int , _a: list[int] , _a: int )-> int:
'''simple docstring'''
def count_of_possible_combinations_with_dp_array(
_a: int , _a: list[int] ) -> int:
if target < 0:
return 0
if target == 0:
return 1
if dp_array[target] != -1:
return dp_array[target]
lowerCamelCase__ = sum(
count_of_possible_combinations_with_dp_array(target - item , _a )
for item in array )
lowerCamelCase__ = answer
return answer
lowerCamelCase__ = [-1] * (target + 1)
return count_of_possible_combinations_with_dp_array(_a , _a )
def snake_case ( _a: int , _a: list[int] , _a: int )-> int:
'''simple docstring'''
lowerCamelCase__ = [0] * (target + 1)
lowerCamelCase__ = 1
for i in range(1 , target + 1 ):
for j in range(_a ):
if i - array[j] >= 0:
dp_array[i] += dp_array[i - array[j]]
return dp_array[target]
if __name__ == "__main__":
import doctest
doctest.testmod()
_snake_case = 3
_snake_case = 5
_snake_case = [1, 2, 5]
print(combination_sum_iv(n, array, target))
| 659 | 0 |
"""simple docstring"""
from __future__ import annotations
class __a :
def __init__( self , a__ ):
_lowerCamelCase = TypeError(
'Matrices must be formed from a list of zero or more lists containing at '
'least one and the same number of values, each of which must be of type '
'int or float.' )
if len(a__ ) != 0:
_lowerCamelCase = len(rows[0] )
if cols == 0:
raise error
for row in rows:
if len(a__ ) != cols:
raise error
for value in row:
if not isinstance(a__ , (int, float) ):
raise error
_lowerCamelCase = rows
else:
_lowerCamelCase = []
def snake_case_ ( self ):
return [[row[i] for row in self.rows] for i in range(len(self.rows[0] ) )]
@property
def snake_case_ ( self ):
return len(self.rows )
@property
def snake_case_ ( self ):
return len(self.rows[0] )
@property
def snake_case_ ( self ):
return (self.num_rows, self.num_columns)
@property
def snake_case_ ( self ):
return self.order[0] == self.order[1]
def snake_case_ ( self ):
_lowerCamelCase = [
[0 if column_num != row_num else 1 for column_num in range(self.num_rows )]
for row_num in range(self.num_rows )
]
return Matrix(a__ )
def snake_case_ ( self ):
if not self.is_square:
return 0
if self.order == (0, 0):
return 1
if self.order == (1, 1):
return int(self.rows[0][0] )
if self.order == (2, 2):
return int(
(self.rows[0][0] * self.rows[1][1])
- (self.rows[0][1] * self.rows[1][0]) )
else:
return sum(
self.rows[0][column] * self.cofactors().rows[0][column]
for column in range(self.num_columns ) )
def snake_case_ ( self ):
return bool(self.determinant() )
def snake_case_ ( self , a__ , a__ ):
_lowerCamelCase = [
[
self.rows[other_row][other_column]
for other_column in range(self.num_columns )
if other_column != column
]
for other_row in range(self.num_rows )
if other_row != row
]
return Matrix(a__ ).determinant()
def snake_case_ ( self , a__ , a__ ):
if (row + column) % 2 == 0:
return self.get_minor(a__ , a__ )
return -1 * self.get_minor(a__ , a__ )
def snake_case_ ( self ):
return Matrix(
[
[self.get_minor(a__ , a__ ) for column in range(self.num_columns )]
for row in range(self.num_rows )
] )
def snake_case_ ( self ):
return Matrix(
[
[
self.minors().rows[row][column]
if (row + column) % 2 == 0
else self.minors().rows[row][column] * -1
for column in range(self.minors().num_columns )
]
for row in range(self.minors().num_rows )
] )
def snake_case_ ( self ):
_lowerCamelCase = [
[self.cofactors().rows[column][row] for column in range(self.num_columns )]
for row in range(self.num_rows )
]
return Matrix(a__ )
def snake_case_ ( self ):
_lowerCamelCase = self.determinant()
if not determinant:
raise TypeError('Only matrices with a non-zero determinant have an inverse' )
return self.adjugate() * (1 / determinant)
def __repr__( self ):
return str(self.rows )
def __str__( self ):
if self.num_rows == 0:
return "[]"
if self.num_rows == 1:
return "[[" + ". ".join(str(self.rows[0] ) ) + "]]"
return (
"["
+ "\n ".join(
[
'[' + '. '.join([str(a__ ) for value in row] ) + '.]'
for row in self.rows
] )
+ "]"
)
def snake_case_ ( self , a__ , a__ = None ):
_lowerCamelCase = TypeError('Row must be a list containing all ints and/or floats' )
if not isinstance(a__ , a__ ):
raise type_error
for value in row:
if not isinstance(a__ , (int, float) ):
raise type_error
if len(a__ ) != self.num_columns:
raise ValueError(
'Row must be equal in length to the other rows in the matrix' )
if position is None:
self.rows.append(a__ )
else:
_lowerCamelCase = self.rows[0:position] + [row] + self.rows[position:]
def snake_case_ ( self , a__ , a__ = None ):
_lowerCamelCase = TypeError(
'Column must be a list containing all ints and/or floats' )
if not isinstance(a__ , a__ ):
raise type_error
for value in column:
if not isinstance(a__ , (int, float) ):
raise type_error
if len(a__ ) != self.num_rows:
raise ValueError(
'Column must be equal in length to the other columns in the matrix' )
if position is None:
_lowerCamelCase = [self.rows[i] + [column[i]] for i in range(self.num_rows )]
else:
_lowerCamelCase = [
self.rows[i][0:position] + [column[i]] + self.rows[i][position:]
for i in range(self.num_rows )
]
def __eq__( self , a__ ):
if not isinstance(a__ , a__ ):
return NotImplemented
return self.rows == other.rows
def __ne__( self , a__ ):
return not self == other
def __neg__( self ):
return self * -1
def __add__( self , a__ ):
if self.order != other.order:
raise ValueError('Addition requires matrices of the same order' )
return Matrix(
[
[self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns )]
for i in range(self.num_rows )
] )
def __sub__( self , a__ ):
if self.order != other.order:
raise ValueError('Subtraction requires matrices of the same order' )
return Matrix(
[
[self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns )]
for i in range(self.num_rows )
] )
def __mul__( self , a__ ):
if isinstance(a__ , (int, float) ):
return Matrix(
[[int(element * other ) for element in row] for row in self.rows] )
elif isinstance(a__ , a__ ):
if self.num_columns != other.num_rows:
raise ValueError(
'The number of columns in the first matrix must '
'be equal to the number of rows in the second' )
return Matrix(
[
[Matrix.dot_product(a__ , a__ ) for column in other.columns()]
for row in self.rows
] )
else:
raise TypeError(
'A Matrix can only be multiplied by an int, float, or another matrix' )
def __pow__( self , a__ ):
if not isinstance(a__ , a__ ):
raise TypeError('A Matrix can only be raised to the power of an int' )
if not self.is_square:
raise ValueError('Only square matrices can be raised to a power' )
if other == 0:
return self.identity()
if other < 0:
if self.is_invertable():
return self.inverse() ** (-other)
raise ValueError(
'Only invertable matrices can be raised to a negative power' )
_lowerCamelCase = self
for _ in range(other - 1 ):
result *= self
return result
@classmethod
def snake_case_ ( cls , a__ , a__ ):
return sum(row[i] * column[i] for i in range(len(a__ ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 650 | import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import ClassLabel, Features, Value
from .base import TaskTemplate
@dataclass(frozen=UpperCamelCase_ )
class _lowerCamelCase ( UpperCamelCase_ ):
# `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization
__a = field(default="text-classification" , metadata={"include_in_asdict_even_if_is_default": True} )
__a = Features({"text": Value("string" )} )
__a = Features({"labels": ClassLabel} )
__a = "text"
__a = "labels"
def UpperCamelCase_ ( self , lowerCAmelCase ) -> Tuple:
if self.label_column not in features:
raise ValueError(f'Column {self.label_column} is not present in features.' )
if not isinstance(features[self.label_column] , lowerCAmelCase ):
raise ValueError(f'Column {self.label_column} is not a ClassLabel.' )
SCREAMING_SNAKE_CASE__: Union[str, Any]= copy.deepcopy(self )
SCREAMING_SNAKE_CASE__: Tuple= self.label_schema.copy()
SCREAMING_SNAKE_CASE__: Union[str, Any]= features[self.label_column]
SCREAMING_SNAKE_CASE__: List[str]= label_schema
return task_template
@property
def UpperCamelCase_ ( self ) -> Dict[str, str]:
return {
self.text_column: "text",
self.label_column: "labels",
}
| 64 | 0 |
"""simple docstring"""
import argparse
import re
from pathlib import Path
import requests
import torch
from PIL import Image
from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor
from transformers import (
EfficientFormerConfig,
EfficientFormerForImageClassificationWithTeacher,
EfficientFormerImageProcessor,
)
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling
def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Union[str, Any]:
"""simple docstring"""
lowerCAmelCase__ :Tuple = old_name
if "patch_embed" in old_name:
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = old_name.split('.' )
if layer == "0":
lowerCAmelCase__ :Dict = old_name.replace('0' , 'convolution1' )
elif layer == "1":
lowerCAmelCase__ :Dict = old_name.replace('1' , 'batchnorm_before' )
elif layer == "3":
lowerCAmelCase__ :Tuple = old_name.replace('3' , 'convolution2' )
else:
lowerCAmelCase__ :int = old_name.replace('4' , 'batchnorm_after' )
if "network" in old_name and re.search(r'\d\.\d' , _SCREAMING_SNAKE_CASE ):
lowerCAmelCase__ :Any = r'\b\d{2}\b'
if bool(re.search(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ):
lowerCAmelCase__ :Dict = re.search(r'\d\.\d\d.' , _SCREAMING_SNAKE_CASE ).group()
else:
lowerCAmelCase__ :Any = re.search(r'\d\.\d.' , _SCREAMING_SNAKE_CASE ).group()
if int(match[0] ) < 6:
lowerCAmelCase__ :Optional[Any] = old_name.replace(_SCREAMING_SNAKE_CASE , '' )
lowerCAmelCase__ :int = trimmed_name.replace('network' , match[0] + '.meta4D_layers.blocks.' + match[2:-1] )
lowerCAmelCase__ :str = 'intermediate_stages.' + trimmed_name
else:
lowerCAmelCase__ :Tuple = old_name.replace(_SCREAMING_SNAKE_CASE , '' )
if int(match[2] ) < num_meta4D_last_stage:
lowerCAmelCase__ :Any = trimmed_name.replace('network' , 'meta4D_layers.blocks.' + match[2] )
else:
lowerCAmelCase__ :int = str(int(match[2] ) - num_meta4D_last_stage )
lowerCAmelCase__ :List[Any] = trimmed_name.replace('network' , 'meta3D_layers.blocks.' + layer_index )
if "norm1" in old_name:
lowerCAmelCase__ :List[Any] = trimmed_name.replace('norm1' , 'layernorm1' )
elif "norm2" in old_name:
lowerCAmelCase__ :Tuple = trimmed_name.replace('norm2' , 'layernorm2' )
elif "fc1" in old_name:
lowerCAmelCase__ :List[Any] = trimmed_name.replace('fc1' , 'linear_in' )
elif "fc2" in old_name:
lowerCAmelCase__ :Optional[int] = trimmed_name.replace('fc2' , 'linear_out' )
lowerCAmelCase__ :Optional[Any] = 'last_stage.' + trimmed_name
elif "network" in old_name and re.search(r'.\d.' , _SCREAMING_SNAKE_CASE ):
lowerCAmelCase__ :Optional[int] = old_name.replace('network' , 'intermediate_stages' )
if "fc" in new_name:
lowerCAmelCase__ :Dict = new_name.replace('fc' , 'convolution' )
elif ("norm1" in new_name) and ("layernorm1" not in new_name):
lowerCAmelCase__ :str = new_name.replace('norm1' , 'batchnorm_before' )
elif ("norm2" in new_name) and ("layernorm2" not in new_name):
lowerCAmelCase__ :Dict = new_name.replace('norm2' , 'batchnorm_after' )
if "proj" in new_name:
lowerCAmelCase__ :str = new_name.replace('proj' , 'projection' )
if "dist_head" in new_name:
lowerCAmelCase__ :Union[str, Any] = new_name.replace('dist_head' , 'distillation_classifier' )
elif "head" in new_name:
lowerCAmelCase__ :List[str] = new_name.replace('head' , 'classifier' )
elif "patch_embed" in new_name:
lowerCAmelCase__ :Optional[int] = 'efficientformer.' + new_name
elif new_name == "norm.weight" or new_name == "norm.bias":
lowerCAmelCase__ :Any = new_name.replace('norm' , 'layernorm' )
lowerCAmelCase__ :Optional[Any] = 'efficientformer.' + new_name
else:
lowerCAmelCase__ :Union[str, Any] = 'efficientformer.encoder.' + new_name
return new_name
def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[str]:
"""simple docstring"""
for key in checkpoint.copy().keys():
lowerCAmelCase__ :Tuple = checkpoint.pop(_SCREAMING_SNAKE_CASE )
lowerCAmelCase__ :List[Any] = val
return checkpoint
def __A () ->str:
"""simple docstring"""
lowerCAmelCase__ :List[str] = 'http://images.cocodataset.org/val2017/000000039769.jpg'
lowerCAmelCase__ :Optional[int] = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw )
return image
def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[int]:
"""simple docstring"""
lowerCAmelCase__ :Optional[Any] = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' )['model']
lowerCAmelCase__ :Dict = EfficientFormerConfig.from_json_file(_SCREAMING_SNAKE_CASE )
lowerCAmelCase__ :List[Any] = EfficientFormerForImageClassificationWithTeacher(_SCREAMING_SNAKE_CASE )
lowerCAmelCase__ :Dict = '_'.join(checkpoint_path.split('/' )[-1].split('.' )[0].split('_' )[:-1] )
lowerCAmelCase__ :Dict = config.depths[-1] - config.num_metaad_blocks + 1
lowerCAmelCase__ :Any = convert_torch_checkpoint(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
model.load_state_dict(_SCREAMING_SNAKE_CASE )
model.eval()
lowerCAmelCase__ :Optional[Any] = {
'bilinear': PILImageResampling.BILINEAR,
'bicubic': PILImageResampling.BICUBIC,
'nearest': PILImageResampling.NEAREST,
}
# prepare image
lowerCAmelCase__ :Union[str, Any] = prepare_img()
lowerCAmelCase__ :Union[str, Any] = 256
lowerCAmelCase__ :Optional[Any] = 224
lowerCAmelCase__ :Tuple = EfficientFormerImageProcessor(
size={'shortest_edge': image_size} , crop_size={'height': crop_size, 'width': crop_size} , resample=pillow_resamplings['bicubic'] , )
lowerCAmelCase__ :Any = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values
# original processing pipeline
lowerCAmelCase__ :Optional[Any] = Compose(
[
Resize(_SCREAMING_SNAKE_CASE , interpolation=pillow_resamplings['bicubic'] ),
CenterCrop(_SCREAMING_SNAKE_CASE ),
ToTensor(),
Normalize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ),
] )
lowerCAmelCase__ :str = image_transforms(_SCREAMING_SNAKE_CASE ).unsqueeze(0 )
assert torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
lowerCAmelCase__ :Dict = model(_SCREAMING_SNAKE_CASE )
lowerCAmelCase__ :int = outputs.logits
lowerCAmelCase__ :Union[str, Any] = (1, 1000)
if "l1" in model_name:
lowerCAmelCase__ :Optional[Any] = torch.Tensor(
[-0.1_3_1_2, 0.4_3_5_3, -1.0_4_9_9, -0.5_1_2_4, 0.4_1_8_3, -0.6_7_9_3, -1.3_7_7_7, -0.0_8_9_3, -0.7_3_5_8, -2.4_3_2_8] )
assert torch.allclose(logits[0, :10] , _SCREAMING_SNAKE_CASE , atol=1e-3 )
assert logits.shape == expected_shape
elif "l3" in model_name:
lowerCAmelCase__ :int = torch.Tensor(
[-1.3_1_5_0, -1.5_4_5_6, -1.2_5_5_6, -0.8_4_9_6, -0.7_1_2_7, -0.7_8_9_7, -0.9_7_2_8, -0.3_0_5_2, 0.3_7_5_1, -0.3_1_2_7] )
assert torch.allclose(logits[0, :10] , _SCREAMING_SNAKE_CASE , atol=1e-3 )
assert logits.shape == expected_shape
elif "l7" in model_name:
lowerCAmelCase__ :Dict = torch.Tensor(
[-1.0_2_8_3, -1.4_1_3_1, -0.5_6_4_4, -1.3_1_1_5, -0.5_7_8_5, -1.2_0_4_9, -0.7_5_2_8, 0.1_9_9_2, -0.3_8_2_2, -0.0_8_7_8] )
assert logits.shape == expected_shape
else:
raise ValueError(
F"Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7" )
# Save Checkpoints
Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE )
model.save_pretrained(_SCREAMING_SNAKE_CASE )
print(F"Checkpoint successfuly converted. Model saved at {pytorch_dump_path}" )
processor.save_pretrained(_SCREAMING_SNAKE_CASE )
print(F"Processor successfuly saved at {pytorch_dump_path}" )
if push_to_hub:
print('Pushing model to the hub...' )
model.push_to_hub(
repo_id=F"Bearnardd/{pytorch_dump_path}" , commit_message='Add model' , use_temp_dir=_SCREAMING_SNAKE_CASE , )
processor.push_to_hub(
repo_id=F"Bearnardd/{pytorch_dump_path}" , commit_message='Add image processor' , use_temp_dir=_SCREAMING_SNAKE_CASE , )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--pytorch_model_path""",
default=None,
type=str,
required=True,
help="""Path to EfficientFormer pytorch checkpoint.""",
)
parser.add_argument(
"""--config_file""",
default=None,
type=str,
required=True,
help="""The json file for EfficientFormer model config.""",
)
parser.add_argument(
"""--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
)
parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Push model and image processor to the hub""")
parser.add_argument(
"""--no-push_to_hub""",
dest="""push_to_hub""",
action="""store_false""",
help="""Do not push model and image processor to the hub""",
)
parser.set_defaults(push_to_hub=True)
__A = parser.parse_args()
convert_efficientformer_checkpoint(
checkpoint_path=args.pytorch_model_path,
efficientformer_config_file=args.config_file,
pytorch_dump_path=args.pytorch_dump_path,
push_to_hub=args.push_to_hub,
)
| 560 |
"""simple docstring"""
# This script creates a super tiny model that is useful inside tests, when we just want to test that
# the machinery works, without needing to the check the quality of the outcomes.
#
# This version creates a tiny model through reduction of a normal pre-trained model, but keeping the
# full vocab, merges file, and thus also resulting in a larger model due to a large vocab size.
# This gives ~3MB in total for all files.
#
# If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated
#
#
# It will be used then as "stas/tiny-wmt19-en-de"
# Build
from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration
__A = """facebook/wmt19-en-de"""
__A = FSMTTokenizer.from_pretrained(mname)
# get the correct vocab sizes, etc. from the master model
__A = FSMTConfig.from_pretrained(mname)
config.update(
dict(
d_model=4,
encoder_layers=1,
decoder_layers=1,
encoder_ffn_dim=4,
decoder_ffn_dim=4,
encoder_attention_heads=1,
decoder_attention_heads=1,
)
)
__A = FSMTForConditionalGeneration(config)
print(F'''num of params {tiny_model.num_parameters()}''')
# Test
__A = tokenizer(["""Making tiny model"""], return_tensors="""pt""")
__A = tiny_model(**batch)
print("""test output:""", len(outputs.logits[0]))
# Save
__A = """tiny-wmt19-en-de"""
tiny_model.half() # makes it smaller
tiny_model.save_pretrained(mname_tiny)
tokenizer.save_pretrained(mname_tiny)
print(F'''Generated {mname_tiny}''')
# Upload
# transformers-cli upload tiny-wmt19-en-de
| 560 | 1 |
from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
try:
if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import (
VersatileDiffusionDualGuidedPipeline,
VersatileDiffusionImageVariationPipeline,
VersatileDiffusionPipeline,
VersatileDiffusionTextToImagePipeline,
)
else:
from .modeling_text_unet import UNetFlatConditionModel
from .pipeline_versatile_diffusion import VersatileDiffusionPipeline
from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline
from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline
from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
| 652 |
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 DetaImageProcessor
class A_ ( unittest.TestCase ):
def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : str=7 ,SCREAMING_SNAKE_CASE__ : Any=3 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_0 ,SCREAMING_SNAKE_CASE__ : int=4_0_0 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=[0.5, 0.5, 0.5] ,SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] ,SCREAMING_SNAKE_CASE__ : List[str]=True ,SCREAMING_SNAKE_CASE__ : List[str]=1 / 2_5_5 ,SCREAMING_SNAKE_CASE__ : Tuple=True ,):
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
__lowerCamelCase : List[Any] = size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}
__lowerCamelCase : str = parent
__lowerCamelCase : Union[str, Any] = batch_size
__lowerCamelCase : int = num_channels
__lowerCamelCase : Dict = min_resolution
__lowerCamelCase : Tuple = max_resolution
__lowerCamelCase : Dict = do_resize
__lowerCamelCase : List[Any] = size
__lowerCamelCase : Tuple = do_normalize
__lowerCamelCase : Any = image_mean
__lowerCamelCase : List[str] = image_std
__lowerCamelCase : List[Any] = do_rescale
__lowerCamelCase : str = rescale_factor
__lowerCamelCase : Tuple = do_pad
def lowerCAmelCase ( self : Dict):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_pad": self.do_pad,
}
def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : List[str]=False):
if not batched:
__lowerCamelCase : Optional[Any] = image_inputs[0]
if isinstance(SCREAMING_SNAKE_CASE__ ,Image.Image):
__lowerCamelCase , __lowerCamelCase : Any = image.size
else:
__lowerCamelCase , __lowerCamelCase : Any = image.shape[1], image.shape[2]
if w < h:
__lowerCamelCase : Optional[int] = int(self.size['shortest_edge'] * h / w)
__lowerCamelCase : Tuple = self.size['shortest_edge']
elif w > h:
__lowerCamelCase : Union[str, Any] = self.size['shortest_edge']
__lowerCamelCase : Union[str, Any] = int(self.size['shortest_edge'] * w / h)
else:
__lowerCamelCase : List[Any] = self.size['shortest_edge']
__lowerCamelCase : Optional[int] = self.size['shortest_edge']
else:
__lowerCamelCase : List[str] = []
for image in image_inputs:
__lowerCamelCase , __lowerCamelCase : List[Any] = self.get_expected_values([image])
expected_values.append((expected_height, expected_width))
__lowerCamelCase : Tuple = max(SCREAMING_SNAKE_CASE__ ,key=lambda SCREAMING_SNAKE_CASE__: item[0])[0]
__lowerCamelCase : Dict = max(SCREAMING_SNAKE_CASE__ ,key=lambda SCREAMING_SNAKE_CASE__: item[1])[1]
return expected_height, expected_width
@require_torch
@require_vision
class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_UpperCAmelCase : Optional[int] = DetaImageProcessor if is_vision_available() else None
def lowerCAmelCase ( self : Optional[Any]):
__lowerCamelCase : List[str] = DetaImageProcessingTester(self)
@property
def lowerCAmelCase ( self : Any):
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCAmelCase ( self : Dict):
__lowerCamelCase : Any = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'image_mean'))
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'image_std'))
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_normalize'))
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_resize'))
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_rescale'))
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'do_pad'))
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ ,'size'))
def lowerCAmelCase ( self : str):
__lowerCamelCase : Optional[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 ,SCREAMING_SNAKE_CASE__)
def lowerCAmelCase ( self : Any):
pass
def lowerCAmelCase ( self : List[str]):
# Initialize image_processing
__lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
__lowerCamelCase : List[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__)
for image in image_inputs:
self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,Image.Image)
# Test not batched input
__lowerCamelCase : List[Any] = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values
__lowerCamelCase , __lowerCamelCase : Tuple = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__)
self.assertEqual(
encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,)
# Test batched
__lowerCamelCase , __lowerCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__)
__lowerCamelCase : Optional[int] = image_processing(SCREAMING_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 lowerCAmelCase ( self : str):
# Initialize image_processing
__lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
__lowerCamelCase : str = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__ ,numpify=SCREAMING_SNAKE_CASE__)
for image in image_inputs:
self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,np.ndarray)
# Test not batched input
__lowerCamelCase : Tuple = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values
__lowerCamelCase , __lowerCamelCase : int = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__)
self.assertEqual(
encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,)
# Test batched
__lowerCamelCase : str = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values
__lowerCamelCase , __lowerCamelCase : Optional[int] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_SNAKE_CASE__)
self.assertEqual(
encoded_images.shape ,(
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) ,)
def lowerCAmelCase ( self : int):
# Initialize image_processing
__lowerCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
__lowerCamelCase : List[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=SCREAMING_SNAKE_CASE__ ,torchify=SCREAMING_SNAKE_CASE__)
for image in image_inputs:
self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,torch.Tensor)
# Test not batched input
__lowerCamelCase : Union[str, Any] = image_processing(image_inputs[0] ,return_tensors='pt').pixel_values
__lowerCamelCase , __lowerCamelCase : int = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__)
self.assertEqual(
encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,)
# Test batched
__lowerCamelCase : List[Any] = image_processing(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').pixel_values
__lowerCamelCase , __lowerCamelCase : Optional[int] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ,batched=SCREAMING_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 lowerCAmelCase ( self : Optional[Any]):
# prepare image and target
__lowerCamelCase : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' ,'r') as f:
__lowerCamelCase : List[str] = json.loads(f.read())
__lowerCamelCase : Union[str, Any] = {'image_id': 3_9_7_6_9, 'annotations': target}
# encode them
__lowerCamelCase : Optional[int] = DetaImageProcessor()
__lowerCamelCase : int = image_processing(images=SCREAMING_SNAKE_CASE__ ,annotations=SCREAMING_SNAKE_CASE__ ,return_tensors='pt')
# verify pixel values
__lowerCamelCase : List[str] = torch.Size([1, 3, 8_0_0, 1_0_6_6])
self.assertEqual(encoding['pixel_values'].shape ,SCREAMING_SNAKE_CASE__)
__lowerCamelCase : List[Any] = torch.tensor([0.2796, 0.3138, 0.3481])
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
# verify area
__lowerCamelCase : Dict = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438])
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] ,SCREAMING_SNAKE_CASE__))
# verify boxes
__lowerCamelCase : int = torch.Size([6, 4])
self.assertEqual(encoding['labels'][0]['boxes'].shape ,SCREAMING_SNAKE_CASE__)
__lowerCamelCase : Optional[int] = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215])
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] ,SCREAMING_SNAKE_CASE__ ,atol=1E-3))
# verify image_id
__lowerCamelCase : Tuple = torch.tensor([3_9_7_6_9])
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] ,SCREAMING_SNAKE_CASE__))
# verify is_crowd
__lowerCamelCase : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0])
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] ,SCREAMING_SNAKE_CASE__))
# verify class_labels
__lowerCamelCase : List[Any] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7])
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] ,SCREAMING_SNAKE_CASE__))
# verify orig_size
__lowerCamelCase : str = torch.tensor([4_8_0, 6_4_0])
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] ,SCREAMING_SNAKE_CASE__))
# verify size
__lowerCamelCase : int = torch.tensor([8_0_0, 1_0_6_6])
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] ,SCREAMING_SNAKE_CASE__))
@slow
def lowerCAmelCase ( self : str):
# prepare image, target and masks_path
__lowerCamelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' ,'r') as f:
__lowerCamelCase : Tuple = json.loads(f.read())
__lowerCamelCase : List[Any] = {'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target}
__lowerCamelCase : Optional[int] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic')
# encode them
__lowerCamelCase : List[str] = DetaImageProcessor(format='coco_panoptic')
__lowerCamelCase : Optional[Any] = image_processing(images=SCREAMING_SNAKE_CASE__ ,annotations=SCREAMING_SNAKE_CASE__ ,masks_path=SCREAMING_SNAKE_CASE__ ,return_tensors='pt')
# verify pixel values
__lowerCamelCase : List[str] = torch.Size([1, 3, 8_0_0, 1_0_6_6])
self.assertEqual(encoding['pixel_values'].shape ,SCREAMING_SNAKE_CASE__)
__lowerCamelCase : Any = torch.tensor([0.2796, 0.3138, 0.3481])
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
# verify area
__lowerCamelCase : Optional[Any] = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147])
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] ,SCREAMING_SNAKE_CASE__))
# verify boxes
__lowerCamelCase : Tuple = torch.Size([6, 4])
self.assertEqual(encoding['labels'][0]['boxes'].shape ,SCREAMING_SNAKE_CASE__)
__lowerCamelCase : Any = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625])
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] ,SCREAMING_SNAKE_CASE__ ,atol=1E-3))
# verify image_id
__lowerCamelCase : int = torch.tensor([3_9_7_6_9])
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] ,SCREAMING_SNAKE_CASE__))
# verify is_crowd
__lowerCamelCase : Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0])
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] ,SCREAMING_SNAKE_CASE__))
# verify class_labels
__lowerCamelCase : int = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3])
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] ,SCREAMING_SNAKE_CASE__))
# verify masks
__lowerCamelCase : Optional[Any] = 8_2_2_8_7_3
self.assertEqual(encoding['labels'][0]['masks'].sum().item() ,SCREAMING_SNAKE_CASE__)
# verify orig_size
__lowerCamelCase : Any = torch.tensor([4_8_0, 6_4_0])
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] ,SCREAMING_SNAKE_CASE__))
# verify size
__lowerCamelCase : Any = torch.tensor([8_0_0, 1_0_6_6])
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] ,SCREAMING_SNAKE_CASE__))
| 652 | 1 |
"""simple docstring"""
from __future__ import annotations
__a = list[tuple[int, int]]
__a = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
__a = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right
class lowerCamelCase :
'''simple docstring'''
def __init__( self: Optional[int] , snake_case: Union[str, Any] , snake_case: Tuple , snake_case: List[str] , snake_case: Tuple , snake_case: Union[str, Any] , snake_case: Optional[int] , ) -> Optional[int]:
snake_case_ :Union[str, Any] = pos_x
snake_case_ :Optional[Any] = pos_y
snake_case_ :Optional[Any] = (pos_y, pos_x)
snake_case_ :List[Any] = goal_x
snake_case_ :int = goal_y
snake_case_ :Optional[Any] = g_cost
snake_case_ :List[Any] = parent
snake_case_ :Any = self.calculate_heuristic()
def lowerCAmelCase_ ( self: str ) -> float:
snake_case_ :Optional[int] = abs(self.pos_x - self.goal_x )
snake_case_ :List[Any] = abs(self.pos_y - self.goal_y )
return dx + dy
def __lt__( self: Optional[int] , snake_case: Optional[int] ) -> bool:
return self.f_cost < other.f_cost
class lowerCamelCase :
'''simple docstring'''
def __init__( self: Optional[Any] , snake_case: int , snake_case: Optional[Any] ) -> Union[str, Any]:
snake_case_ :Optional[int] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , lowerCAmelCase_ )
snake_case_ :List[Any] = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99_999 , lowerCAmelCase_ )
snake_case_ :Any = [self.start]
snake_case_ :Union[str, Any] = []
snake_case_ :int = False
def lowerCAmelCase_ ( self: str ) -> Path | None:
while self.open_nodes:
# Open Nodes are sorted using __lt__
self.open_nodes.sort()
snake_case_ :Tuple = self.open_nodes.pop(0 )
if current_node.pos == self.target.pos:
snake_case_ :Optional[Any] = True
return self.retrace_path(lowerCAmelCase_ )
self.closed_nodes.append(lowerCAmelCase_ )
snake_case_ :Any = self.get_successors(lowerCAmelCase_ )
for child_node in successors:
if child_node in self.closed_nodes:
continue
if child_node not in self.open_nodes:
self.open_nodes.append(lowerCAmelCase_ )
else:
# retrieve the best current path
snake_case_ :Optional[Any] = self.open_nodes.pop(self.open_nodes.index(lowerCAmelCase_ ) )
if child_node.g_cost < better_node.g_cost:
self.open_nodes.append(lowerCAmelCase_ )
else:
self.open_nodes.append(lowerCAmelCase_ )
if not self.reached:
return [self.start.pos]
return None
def lowerCAmelCase_ ( self: Any , snake_case: str ) -> list[Node]:
snake_case_ :Optional[Any] = []
for action in delta:
snake_case_ :Dict = parent.pos_x + action[1]
snake_case_ :Any = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(lowerCAmelCase_ ) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(
lowerCAmelCase_ , lowerCAmelCase_ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , lowerCAmelCase_ , ) )
return successors
def lowerCAmelCase_ ( self: Dict , snake_case: Optional[Any] ) -> Path:
snake_case_ :Dict = node
snake_case_ :List[str] = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x) )
snake_case_ :Optional[int] = current_node.parent
path.reverse()
return path
if __name__ == "__main__":
__a = (0, 0)
__a = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
print("------")
__a = GreedyBestFirst(init, goal)
__a = greedy_bf.search()
if path:
for pos_x, pos_y in path:
__a = 2
for elem in grid:
print(elem)
| 717 |
"""simple docstring"""
from typing import Callable, List, Optional, Tuple, Union
import torch
from transformers import CLIPTextModel, CLIPTokenizer
from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin, TransformeraDModel, VQModel
from ...schedulers import VQDiffusionScheduler
from ...utils import logging
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
__a = logging.get_logger(__name__) # pylint: disable=invalid-name
class lowerCamelCase ( _lowerCAmelCase , _lowerCAmelCase ):
'''simple docstring'''
@register_to_config
def __init__( self: int , snake_case: bool , snake_case: Optional[int] = None , snake_case: Optional[int] = None ) -> Dict:
super().__init__()
snake_case_ :int = learnable
if self.learnable:
assert hidden_size is not None, "learnable=True requires `hidden_size` to be set"
assert length is not None, "learnable=True requires `length` to be set"
snake_case_ :str = torch.zeros(snake_case , snake_case )
else:
snake_case_ :Optional[int] = None
snake_case_ :Union[str, Any] = torch.nn.Parameter(snake_case )
class lowerCamelCase ( _lowerCAmelCase ):
'''simple docstring'''
_A : VQModel
_A : CLIPTextModel
_A : CLIPTokenizer
_A : TransformeraDModel
_A : LearnedClassifierFreeSamplingEmbeddings
_A : VQDiffusionScheduler
def __init__( self: Any , snake_case: VQModel , snake_case: CLIPTextModel , snake_case: CLIPTokenizer , snake_case: TransformeraDModel , snake_case: VQDiffusionScheduler , snake_case: LearnedClassifierFreeSamplingEmbeddings , ) -> Union[str, Any]:
super().__init__()
self.register_modules(
vqvae=snake_case , transformer=snake_case , text_encoder=snake_case , tokenizer=snake_case , scheduler=snake_case , learned_classifier_free_sampling_embeddings=snake_case , )
def lowerCAmelCase_ ( self: Tuple , snake_case: Union[str, Any] , snake_case: List[Any] , snake_case: List[str] ) -> Any:
snake_case_ :List[str] = len(snake_case ) if isinstance(snake_case , snake_case ) else 1
# get prompt text embeddings
snake_case_ :List[str] = self.tokenizer(
snake_case , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , )
snake_case_ :List[Any] = text_inputs.input_ids
if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
snake_case_ :int = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] )
logger.warning(
"""The following part of your input was truncated because CLIP can only handle sequences up to"""
f""" {self.tokenizer.model_max_length} tokens: {removed_text}""" )
snake_case_ :Optional[Any] = text_input_ids[:, : self.tokenizer.model_max_length]
snake_case_ :Any = self.text_encoder(text_input_ids.to(self.device ) )[0]
# NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion.
# While CLIP does normalize the pooled output of the text transformer when combining
# the image and text embeddings, CLIP does not directly normalize the last hidden state.
#
# CLIP normalizing the pooled output.
# https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053
snake_case_ :int = prompt_embeds / prompt_embeds.norm(dim=-1 , keepdim=snake_case )
# duplicate text embeddings for each generation per prompt
snake_case_ :str = prompt_embeds.repeat_interleave(snake_case , dim=0 )
if do_classifier_free_guidance:
if self.learned_classifier_free_sampling_embeddings.learnable:
snake_case_ :Optional[Any] = self.learned_classifier_free_sampling_embeddings.embeddings
snake_case_ :Any = negative_prompt_embeds.unsqueeze(0 ).repeat(snake_case , 1 , 1 )
else:
snake_case_ :Any = [""""""] * batch_size
snake_case_ :Optional[Any] = text_input_ids.shape[-1]
snake_case_ :Dict = self.tokenizer(
snake_case , padding="""max_length""" , max_length=snake_case , truncation=snake_case , return_tensors="""pt""" , )
snake_case_ :str = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]
# See comment for normalizing text embeddings
snake_case_ :Union[str, Any] = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 , keepdim=snake_case )
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
snake_case_ :Tuple = negative_prompt_embeds.shape[1]
snake_case_ :int = negative_prompt_embeds.repeat(1 , snake_case , 1 )
snake_case_ :int = negative_prompt_embeds.view(batch_size * num_images_per_prompt , snake_case , -1 )
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
snake_case_ :str = torch.cat([negative_prompt_embeds, prompt_embeds] )
return prompt_embeds
@torch.no_grad()
def __call__( self: Dict , snake_case: Union[str, List[str]] , snake_case: int = 100 , snake_case: float = 5.0 , snake_case: float = 1.0 , snake_case: int = 1 , snake_case: Optional[Union[torch.Generator, List[torch.Generator]]] = None , snake_case: Optional[torch.FloatTensor] = None , snake_case: Optional[str] = "pil" , snake_case: bool = True , snake_case: Optional[Callable[[int, int, torch.FloatTensor], None]] = None , snake_case: int = 1 , ) -> Union[ImagePipelineOutput, Tuple]:
if isinstance(snake_case , snake_case ):
snake_case_ :Any = 1
elif isinstance(snake_case , snake_case ):
snake_case_ :int = len(snake_case )
else:
raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(snake_case )}""" )
snake_case_ :Tuple = batch_size * num_images_per_prompt
snake_case_ :Optional[Any] = guidance_scale > 1.0
snake_case_ :Dict = self._encode_prompt(snake_case , snake_case , snake_case )
if (callback_steps is None) or (
callback_steps is not None and (not isinstance(snake_case , snake_case ) or callback_steps <= 0)
):
raise ValueError(
f"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
f""" {type(snake_case )}.""" )
# get the initial completely masked latents unless the user supplied it
snake_case_ :List[str] = (batch_size, self.transformer.num_latent_pixels)
if latents is None:
snake_case_ :Tuple = self.transformer.num_vector_embeds - 1
snake_case_ :Optional[int] = torch.full(snake_case , snake_case ).to(self.device )
else:
if latents.shape != latents_shape:
raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" )
if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any():
raise ValueError(
"""Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,"""
f""" {self.transformer.num_vector_embeds - 1} (inclusive).""" )
snake_case_ :str = latents.to(self.device )
# set timesteps
self.scheduler.set_timesteps(snake_case , device=self.device )
snake_case_ :Optional[Any] = self.scheduler.timesteps.to(self.device )
snake_case_ :List[Any] = latents
for i, t in enumerate(self.progress_bar(snake_case ) ):
# expand the sample if we are doing classifier free guidance
snake_case_ :List[Any] = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample
# predict the un-noised image
# model_output == `log_p_x_0`
snake_case_ :Any = self.transformer(snake_case , encoder_hidden_states=snake_case , timestep=snake_case ).sample
if do_classifier_free_guidance:
snake_case_, snake_case_ :Optional[Any] = model_output.chunk(2 )
snake_case_ :Any = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond)
model_output -= torch.logsumexp(snake_case , dim=1 , keepdim=snake_case )
snake_case_ :str = self.truncate(snake_case , snake_case )
# remove `log(0)`'s (`-inf`s)
snake_case_ :List[str] = model_output.clamp(-70 )
# compute the previous noisy sample x_t -> x_t-1
snake_case_ :Any = self.scheduler.step(snake_case , timestep=snake_case , sample=snake_case , generator=snake_case ).prev_sample
# call the callback, if provided
if callback is not None and i % callback_steps == 0:
callback(snake_case , snake_case , snake_case )
snake_case_ :Optional[int] = self.vqvae.config.vq_embed_dim
snake_case_ :Tuple = (batch_size, self.transformer.height, self.transformer.width, embedding_channels)
snake_case_ :List[Any] = self.vqvae.quantize.get_codebook_entry(snake_case , shape=snake_case )
snake_case_ :Dict = self.vqvae.decode(snake_case , force_not_quantize=snake_case ).sample
snake_case_ :List[Any] = (image / 2 + 0.5).clamp(0 , 1 )
snake_case_ :Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
snake_case_ :Any = self.numpy_to_pil(snake_case )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=snake_case )
def lowerCAmelCase_ ( self: int , snake_case: torch.FloatTensor , snake_case: float ) -> torch.FloatTensor:
snake_case_, snake_case_ :List[Any] = torch.sort(snake_case , 1 , descending=snake_case )
snake_case_ :Optional[int] = torch.exp(snake_case )
snake_case_ :int = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate
# Ensure that at least the largest probability is not zeroed out
snake_case_ :Union[str, Any] = torch.full_like(keep_mask[:, 0:1, :] , snake_case )
snake_case_ :List[str] = torch.cat((all_true, keep_mask) , dim=1 )
snake_case_ :List[str] = keep_mask[:, :-1, :]
snake_case_ :str = keep_mask.gather(1 , indices.argsort(1 ) )
snake_case_ :int = log_p_x_0.clone()
snake_case_ :List[Any] = -torch.inf # -inf = log(0)
return rv
| 310 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCamelCase__ = logging.get_logger(__name__)
lowerCamelCase__ = {
'''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json''',
# See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox
}
class _lowerCAmelCase ( __UpperCamelCase ):
"""simple docstring"""
lowerCAmelCase__ ='''gpt_neox'''
def __init__( self , __SCREAMING_SNAKE_CASE=5_0432 , __SCREAMING_SNAKE_CASE=6144 , __SCREAMING_SNAKE_CASE=44 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=2_4576 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.25 , __SCREAMING_SNAKE_CASE=1_0000 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=2048 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-5 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ) -> List[Any]:
"""simple docstring"""
super().__init__(bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
snake_case__ : str =vocab_size
snake_case__ : Optional[int] =max_position_embeddings
snake_case__ : Optional[int] =hidden_size
snake_case__ : Optional[Any] =num_hidden_layers
snake_case__ : Optional[Any] =num_attention_heads
snake_case__ : List[Any] =intermediate_size
snake_case__ : int =hidden_act
snake_case__ : Dict =rotary_pct
snake_case__ : str =rotary_emb_base
snake_case__ : List[Any] =attention_dropout
snake_case__ : Optional[int] =hidden_dropout
snake_case__ : Optional[Any] =classifier_dropout
snake_case__ : List[Any] =initializer_range
snake_case__ : Optional[int] =layer_norm_eps
snake_case__ : str =use_cache
snake_case__ : Any =tie_word_embeddings
snake_case__ : List[Any] =use_parallel_residual
snake_case__ : Dict =rope_scaling
self._rope_scaling_validation()
if self.hidden_size % self.num_attention_heads != 0:
raise ValueError(
'''The hidden size is not divisble by the number of attention heads! Make sure to update them!''' )
def UpperCAmelCase ( self ) -> Union[str, Any]:
"""simple docstring"""
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , __SCREAMING_SNAKE_CASE ) or len(self.rope_scaling ) != 2:
raise ValueError(
'''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '''
f'''got {self.rope_scaling}''' )
snake_case__ : Optional[Any] =self.rope_scaling.get('''type''' , __SCREAMING_SNAKE_CASE )
snake_case__ : Optional[Any] =self.rope_scaling.get('''factor''' , __SCREAMING_SNAKE_CASE )
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' )
if rope_scaling_factor is None or not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or rope_scaling_factor <= 1.0:
raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
| 381 |
from collections import OrderedDict
from typing import List, Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
lowerCamelCase__ = logging.get_logger(__name__)
lowerCamelCase__ = {
'''google/efficientnet-b7''': '''https://huggingface.co/google/efficientnet-b7/resolve/main/config.json''',
}
class _lowerCAmelCase ( __UpperCamelCase ):
"""simple docstring"""
lowerCAmelCase__ ='''efficientnet'''
def __init__( self , __SCREAMING_SNAKE_CASE = 3 , __SCREAMING_SNAKE_CASE = 600 , __SCREAMING_SNAKE_CASE = 2.0 , __SCREAMING_SNAKE_CASE = 3.1 , __SCREAMING_SNAKE_CASE = 8 , __SCREAMING_SNAKE_CASE = [3, 3, 5, 3, 5, 5, 3] , __SCREAMING_SNAKE_CASE = [32, 16, 24, 40, 80, 112, 192] , __SCREAMING_SNAKE_CASE = [16, 24, 40, 80, 112, 192, 320] , __SCREAMING_SNAKE_CASE = [] , __SCREAMING_SNAKE_CASE = [1, 2, 2, 2, 1, 2, 1] , __SCREAMING_SNAKE_CASE = [1, 2, 2, 3, 3, 4, 1] , __SCREAMING_SNAKE_CASE = [1, 6, 6, 6, 6, 6, 6] , __SCREAMING_SNAKE_CASE = 0.25 , __SCREAMING_SNAKE_CASE = "swish" , __SCREAMING_SNAKE_CASE = 2560 , __SCREAMING_SNAKE_CASE = "mean" , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = 0.001 , __SCREAMING_SNAKE_CASE = 0.99 , __SCREAMING_SNAKE_CASE = 0.5 , __SCREAMING_SNAKE_CASE = 0.2 , **__SCREAMING_SNAKE_CASE , ) -> Any:
"""simple docstring"""
super().__init__(**__SCREAMING_SNAKE_CASE )
snake_case__ : Union[str, Any] =num_channels
snake_case__ : Tuple =image_size
snake_case__ : int =width_coefficient
snake_case__ : List[str] =depth_coefficient
snake_case__ : Optional[int] =depth_divisor
snake_case__ : Any =kernel_sizes
snake_case__ : int =in_channels
snake_case__ : Union[str, Any] =out_channels
snake_case__ : Tuple =depthwise_padding
snake_case__ : List[str] =strides
snake_case__ : int =num_block_repeats
snake_case__ : Optional[Any] =expand_ratios
snake_case__ : List[Any] =squeeze_expansion_ratio
snake_case__ : int =hidden_act
snake_case__ : Union[str, Any] =hidden_dim
snake_case__ : int =pooling_type
snake_case__ : Union[str, Any] =initializer_range
snake_case__ : str =batch_norm_eps
snake_case__ : List[str] =batch_norm_momentum
snake_case__ : Union[str, Any] =dropout_rate
snake_case__ : List[Any] =drop_connect_rate
snake_case__ : Any =sum(__SCREAMING_SNAKE_CASE ) * 4
class _lowerCAmelCase ( __UpperCamelCase ):
"""simple docstring"""
lowerCAmelCase__ =version.parse('''1.11''' )
@property
def UpperCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]:
"""simple docstring"""
return OrderedDict(
[
('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
] )
@property
def UpperCAmelCase ( self ) -> float:
"""simple docstring"""
return 1e-5
| 381 | 1 |
'''simple docstring'''
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert 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 AlignProcessor, EfficientNetImageProcessor
@require_vision
class __A ( unittest.TestCase ):
'''simple docstring'''
def __lowerCamelCase ( self ):
'''simple docstring'''
lowerCamelCase__ = tempfile.mkdtemp()
lowerCamelCase__ = [
'''[UNK]''',
'''[CLS]''',
'''[SEP]''',
'''[PAD]''',
'''[MASK]''',
'''want''',
'''##want''',
'''##ed''',
'''wa''',
'''un''',
'''runn''',
'''##ing''',
''',''',
'''low''',
'''lowest''',
]
lowerCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
lowerCamelCase__ = {
'''do_resize''': True,
'''size''': 2_0,
'''do_center_crop''': True,
'''crop_size''': 1_8,
'''do_normalize''': True,
'''image_mean''': [0.4814_5466, 0.457_8275, 0.4082_1073],
'''image_std''': [0.2686_2954, 0.2613_0258, 0.2757_7711],
}
lowerCamelCase__ = os.path.join(self.tmpdirname , __lowerCAmelCase )
with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp:
json.dump(__lowerCAmelCase , __lowerCAmelCase )
def __lowerCamelCase ( self , **__lowerCAmelCase ):
'''simple docstring'''
return BertTokenizer.from_pretrained(self.tmpdirname , **__lowerCAmelCase )
def __lowerCamelCase ( self , **__lowerCAmelCase ):
'''simple docstring'''
return BertTokenizerFast.from_pretrained(self.tmpdirname , **__lowerCAmelCase )
def __lowerCamelCase ( self , **__lowerCAmelCase ):
'''simple docstring'''
return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **__lowerCAmelCase )
def __lowerCamelCase ( self ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def __lowerCamelCase ( self ):
'''simple docstring'''
lowerCamelCase__ = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )]
lowerCamelCase__ = [Image.fromarray(np.moveaxis(__lowerCAmelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def __lowerCamelCase ( self ):
'''simple docstring'''
lowerCamelCase__ = self.get_tokenizer()
lowerCamelCase__ = self.get_rust_tokenizer()
lowerCamelCase__ = self.get_image_processor()
lowerCamelCase__ = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase )
processor_slow.save_pretrained(self.tmpdirname )
lowerCamelCase__ = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=__lowerCAmelCase )
lowerCamelCase__ = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase )
processor_fast.save_pretrained(self.tmpdirname )
lowerCamelCase__ = AlignProcessor.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 , __lowerCAmelCase )
self.assertIsInstance(processor_fast.tokenizer , __lowerCAmelCase )
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 , __lowerCAmelCase )
self.assertIsInstance(processor_fast.image_processor , __lowerCAmelCase )
def __lowerCamelCase ( self ):
'''simple docstring'''
lowerCamelCase__ = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
lowerCamelCase__ = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' )
lowerCamelCase__ = self.get_image_processor(do_normalize=__lowerCAmelCase , padding_value=1.0 )
lowerCamelCase__ = AlignProcessor.from_pretrained(
self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__lowerCAmelCase , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , __lowerCAmelCase )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , __lowerCAmelCase )
def __lowerCamelCase ( self ):
'''simple docstring'''
lowerCamelCase__ = self.get_image_processor()
lowerCamelCase__ = self.get_tokenizer()
lowerCamelCase__ = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase )
lowerCamelCase__ = self.prepare_image_inputs()
lowerCamelCase__ = image_processor(__lowerCAmelCase , return_tensors='''np''' )
lowerCamelCase__ = processor(images=__lowerCAmelCase , return_tensors='''np''' )
for key in input_image_proc.keys():
self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 )
def __lowerCamelCase ( self ):
'''simple docstring'''
lowerCamelCase__ = self.get_image_processor()
lowerCamelCase__ = self.get_tokenizer()
lowerCamelCase__ = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase )
lowerCamelCase__ = '''lower newer'''
lowerCamelCase__ = processor(text=__lowerCAmelCase )
lowerCamelCase__ = tokenizer(__lowerCAmelCase , padding='''max_length''' , max_length=6_4 )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def __lowerCamelCase ( self ):
'''simple docstring'''
lowerCamelCase__ = self.get_image_processor()
lowerCamelCase__ = self.get_tokenizer()
lowerCamelCase__ = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase )
lowerCamelCase__ = '''lower newer'''
lowerCamelCase__ = self.prepare_image_inputs()
lowerCamelCase__ = processor(text=__lowerCAmelCase , images=__lowerCAmelCase )
self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] )
# test if it raises when no input is passed
with pytest.raises(__lowerCAmelCase ):
processor()
def __lowerCamelCase ( self ):
'''simple docstring'''
lowerCamelCase__ = self.get_image_processor()
lowerCamelCase__ = self.get_tokenizer()
lowerCamelCase__ = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase )
lowerCamelCase__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
lowerCamelCase__ = processor.batch_decode(__lowerCAmelCase )
lowerCamelCase__ = tokenizer.batch_decode(__lowerCAmelCase )
self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
def __lowerCamelCase ( self ):
'''simple docstring'''
lowerCamelCase__ = self.get_image_processor()
lowerCamelCase__ = self.get_tokenizer()
lowerCamelCase__ = AlignProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase )
lowerCamelCase__ = '''lower newer'''
lowerCamelCase__ = self.prepare_image_inputs()
lowerCamelCase__ = processor(text=__lowerCAmelCase , images=__lowerCAmelCase )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 711 |
import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union
import torch
from filelock import FileLock
from torch.utils.data import Dataset
from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures
_a = logging.get_logger(__name__)
@dataclass
class __A :
'''simple docstring'''
lowerCAmelCase_ = field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys() )} )
lowerCAmelCase_ = field(
metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""} )
lowerCAmelCase_ = 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_ = field(
default=lowerCAmelCase , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} )
def __lowerCamelCase ( self ):
'''simple docstring'''
lowerCamelCase__ = self.task_name.lower()
class __A ( lowerCAmelCase ):
'''simple docstring'''
lowerCAmelCase_ = """train"""
lowerCAmelCase_ = """dev"""
lowerCAmelCase_ = """test"""
class __A ( lowerCAmelCase ):
'''simple docstring'''
lowerCAmelCase_ = 42
lowerCAmelCase_ = 42
lowerCAmelCase_ = 42
def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = None , __lowerCAmelCase = Split.train , __lowerCAmelCase = None , ):
'''simple docstring'''
warnings.warn(
'''This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets '''
'''library. You can have a look at this example script for pointers: '''
'''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' , __lowerCAmelCase , )
lowerCamelCase__ = args
lowerCamelCase__ = glue_processors[args.task_name]()
lowerCamelCase__ = glue_output_modes[args.task_name]
if isinstance(__lowerCAmelCase , __lowerCAmelCase ):
try:
lowerCamelCase__ = Split[mode]
except KeyError:
raise KeyError('''mode is not a valid split name''' )
# Load data features from cache or dataset file
lowerCamelCase__ = 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}_{args.task_name}' , )
lowerCamelCase__ = self.processor.get_labels()
if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
"RobertaTokenizer",
"RobertaTokenizerFast",
"XLMRobertaTokenizer",
"BartTokenizer",
"BartTokenizerFast",
):
# HACK(label indices are swapped in RoBERTa pretrained model)
lowerCamelCase__ , lowerCamelCase__ = label_list[2], label_list[1]
lowerCamelCase__ = label_list
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
lowerCamelCase__ = cached_features_file + '''.lock'''
with FileLock(__lowerCAmelCase ):
if os.path.exists(__lowerCAmelCase ) and not args.overwrite_cache:
lowerCamelCase__ = time.time()
lowerCamelCase__ = torch.load(__lowerCAmelCase )
logger.info(
F'Loading features from cached file {cached_features_file} [took %.3f s]' , time.time() - start )
else:
logger.info(F'Creating features from dataset file at {args.data_dir}' )
if mode == Split.dev:
lowerCamelCase__ = self.processor.get_dev_examples(args.data_dir )
elif mode == Split.test:
lowerCamelCase__ = self.processor.get_test_examples(args.data_dir )
else:
lowerCamelCase__ = self.processor.get_train_examples(args.data_dir )
if limit_length is not None:
lowerCamelCase__ = examples[:limit_length]
lowerCamelCase__ = glue_convert_examples_to_features(
__lowerCAmelCase , __lowerCAmelCase , max_length=args.max_seq_length , label_list=__lowerCAmelCase , output_mode=self.output_mode , )
lowerCamelCase__ = time.time()
torch.save(self.features , __lowerCAmelCase )
# ^ 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 ):
'''simple docstring'''
return len(self.features )
def __getitem__( self , __lowerCAmelCase ):
'''simple docstring'''
return self.features[i]
def __lowerCamelCase ( self ):
'''simple docstring'''
return self.label_list
| 29 | 0 |
import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional
import pyarrow as pa
import pyarrow.json as paj
import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline
lowerCAmelCase_ = datasets.utils.logging.get_logger(__name__)
@dataclass
class A (datasets.BuilderConfig ):
_SCREAMING_SNAKE_CASE = None
_SCREAMING_SNAKE_CASE = "utf-8"
_SCREAMING_SNAKE_CASE = None
_SCREAMING_SNAKE_CASE = None
_SCREAMING_SNAKE_CASE = True # deprecated
_SCREAMING_SNAKE_CASE = None # deprecated
_SCREAMING_SNAKE_CASE = 10 << 20 # 10MB
_SCREAMING_SNAKE_CASE = None
class A (datasets.ArrowBasedBuilder ):
_SCREAMING_SNAKE_CASE = JsonConfig
def __a ( self ) -> Tuple:
'''simple docstring'''
if self.config.block_size is not None:
logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead''' )
_snake_case : Optional[int] = self.config.block_size
if self.config.use_threads is not True:
logger.warning(
'''The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.''' )
if self.config.newlines_in_values is not None:
raise ValueError('''The JSON loader parameter `newlines_in_values` is no longer supported''' )
return datasets.DatasetInfo(features=self.config.features )
def __a ( self , lowercase_ ) -> List[str]:
'''simple docstring'''
if not self.config.data_files:
raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}''' )
_snake_case : List[str] = dl_manager.download_and_extract(self.config.data_files )
if isinstance(lowercase_ , (str, list, tuple) ):
_snake_case : List[Any] = data_files
if isinstance(lowercase_ , lowercase_ ):
_snake_case : List[str] = [files]
_snake_case : str = [dl_manager.iter_files(lowercase_ ) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )]
_snake_case : str = []
for split_name, files in data_files.items():
if isinstance(lowercase_ , lowercase_ ):
_snake_case : Optional[int] = [files]
_snake_case : List[str] = [dl_manager.iter_files(lowercase_ ) for file in files]
splits.append(datasets.SplitGenerator(name=lowercase_ , gen_kwargs={'''files''': files} ) )
return splits
def __a ( self , lowercase_ ) -> pa.Table:
'''simple docstring'''
if self.config.features is not None:
# adding missing columns
for column_name in set(self.config.features ) - set(pa_table.column_names ):
_snake_case : Union[str, Any] = self.config.features.arrow_schema.field(lowercase_ ).type
_snake_case : str = pa_table.append_column(lowercase_ , pa.array([None] * len(lowercase_ ) , type=lowercase_ ) )
# more expensive cast to support nested structures with keys in a different order
# allows str <-> int/float or str to Audio for example
_snake_case : Tuple = table_cast(lowercase_ , self.config.features.arrow_schema )
return pa_table
def __a ( self , lowercase_ ) -> List[str]:
'''simple docstring'''
for file_idx, file in enumerate(itertools.chain.from_iterable(lowercase_ ) ):
# If the file is one json object and if we need to look at the list of items in one specific field
if self.config.field is not None:
with open(lowercase_ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f:
_snake_case : Tuple = json.load(lowercase_ )
# We keep only the field we are interested in
_snake_case : str = dataset[self.config.field]
# We accept two format: a list of dicts or a dict of lists
if isinstance(lowercase_ , (list, tuple) ):
_snake_case : List[str] = set().union(*[row.keys() for row in dataset] )
_snake_case : Optional[int] = {col: [row.get(lowercase_ ) for row in dataset] for col in keys}
else:
_snake_case : int = dataset
_snake_case : Union[str, Any] = pa.Table.from_pydict(lowercase_ )
yield file_idx, self._cast_table(lowercase_ )
# If the file has one json object per line
else:
with open(lowercase_ , '''rb''' ) as f:
_snake_case : List[str] = 0
# Use block_size equal to the chunk size divided by 32 to leverage multithreading
# Set a default minimum value of 16kB if the chunk size is really small
_snake_case : Tuple = max(self.config.chunksize // 32 , 16 << 10 )
_snake_case : List[str] = (
self.config.encoding_errors if self.config.encoding_errors is not None else """strict"""
)
while True:
_snake_case : Any = f.read(self.config.chunksize )
if not batch:
break
# Finish current line
try:
batch += f.readline()
except (AttributeError, io.UnsupportedOperation):
batch += readline(lowercase_ )
# PyArrow only accepts utf-8 encoded bytes
if self.config.encoding != "utf-8":
_snake_case : Any = batch.decode(self.config.encoding , errors=lowercase_ ).encode('''utf-8''' )
try:
while True:
try:
_snake_case : Dict = paj.read_json(
io.BytesIO(lowercase_ ) , read_options=paj.ReadOptions(block_size=lowercase_ ) )
break
except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
if (
isinstance(lowercase_ , pa.ArrowInvalid )
and "straddling" not in str(lowercase_ )
or block_size > len(lowercase_ )
):
raise
else:
# Increase the block size in case it was too small.
# The block size will be reset for the next file.
logger.debug(
F'''Batch of {len(lowercase_ )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.''' )
block_size *= 2
except pa.ArrowInvalid as e:
try:
with open(
lowercase_ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f:
_snake_case : Optional[Any] = json.load(lowercase_ )
except json.JSONDecodeError:
logger.error(F'''Failed to read file \'{file}\' with error {type(lowercase_ )}: {e}''' )
raise e
# If possible, parse the file as a list of json objects and exit the loop
if isinstance(lowercase_ , lowercase_ ): # list is the only sequence type supported in JSON
try:
_snake_case : Optional[int] = set().union(*[row.keys() for row in dataset] )
_snake_case : str = {col: [row.get(lowercase_ ) for row in dataset] for col in keys}
_snake_case : List[Any] = pa.Table.from_pydict(lowercase_ )
except (pa.ArrowInvalid, AttributeError) as e:
logger.error(F'''Failed to read file \'{file}\' with error {type(lowercase_ )}: {e}''' )
raise ValueError(F'''Not able to read records in the JSON file at {file}.''' ) from None
yield file_idx, self._cast_table(lowercase_ )
break
else:
logger.error(F'''Failed to read file \'{file}\' with error {type(lowercase_ )}: {e}''' )
raise ValueError(
F'''Not able to read records in the JSON file at {file}. '''
F'''You should probably indicate the field of the JSON file containing your records. '''
F'''This JSON file contain the following fields: {str(list(dataset.keys() ) )}. '''
F'''Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ''' ) from None
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield (file_idx, batch_idx), self._cast_table(lowercase_ )
batch_idx += 1
| 326 |
"""simple docstring"""
from unittest.mock import Mock, patch
from file_transfer.send_file import send_file
@patch("""socket.socket""" )
@patch("""builtins.open""" )
def __magic_name__ ( lowercase , lowercase ):
# ===== initialization =====
SCREAMING_SNAKE_CASE_: int =Mock()
SCREAMING_SNAKE_CASE_: int =conn, Mock()
SCREAMING_SNAKE_CASE_: Tuple =iter([1, None] )
SCREAMING_SNAKE_CASE_: Optional[Any] =lambda lowercase : next(lowercase )
# ===== invoke =====
send_file(filename="""mytext.txt""" , testing=lowercase )
# ===== ensurance =====
sock.assert_called_once()
sock.return_value.bind.assert_called_once()
sock.return_value.listen.assert_called_once()
sock.return_value.accept.assert_called_once()
conn.recv.assert_called_once()
file.return_value.__enter__.assert_called_once()
file.return_value.__enter__.return_value.read.assert_called()
conn.send.assert_called_once()
conn.close.assert_called_once()
sock.return_value.shutdown.assert_called_once()
sock.return_value.close.assert_called_once()
| 409 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
UpperCAmelCase__ = {
"configuration_funnel": ["FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP", "FunnelConfig"],
"convert_funnel_original_tf_checkpoint_to_pytorch": [],
"tokenization_funnel": ["FunnelTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase__ = ["FunnelTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase__ = [
"FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST",
"FunnelBaseModel",
"FunnelForMaskedLM",
"FunnelForMultipleChoice",
"FunnelForPreTraining",
"FunnelForQuestionAnswering",
"FunnelForSequenceClassification",
"FunnelForTokenClassification",
"FunnelModel",
"FunnelPreTrainedModel",
"load_tf_weights_in_funnel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase__ = [
"TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFFunnelBaseModel",
"TFFunnelForMaskedLM",
"TFFunnelForMultipleChoice",
"TFFunnelForPreTraining",
"TFFunnelForQuestionAnswering",
"TFFunnelForSequenceClassification",
"TFFunnelForTokenClassification",
"TFFunnelModel",
"TFFunnelPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig
from .tokenization_funnel import FunnelTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_funnel_fast import FunnelTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_funnel import (
FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST,
FunnelBaseModel,
FunnelForMaskedLM,
FunnelForMultipleChoice,
FunnelForPreTraining,
FunnelForQuestionAnswering,
FunnelForSequenceClassification,
FunnelForTokenClassification,
FunnelModel,
FunnelPreTrainedModel,
load_tf_weights_in_funnel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_funnel import (
TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST,
TFFunnelBaseModel,
TFFunnelForMaskedLM,
TFFunnelForMultipleChoice,
TFFunnelForPreTraining,
TFFunnelForQuestionAnswering,
TFFunnelForSequenceClassification,
TFFunnelForTokenClassification,
TFFunnelModel,
TFFunnelPreTrainedModel,
)
else:
import sys
UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 639 |
import logging
from pathlib import Path
import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only
from utils_rag import save_json
def A ( _UpperCAmelCase : List[Any] ) -> int:
'''simple docstring'''
_UpperCAmelCase = filter(lambda _UpperCAmelCase : p.requires_grad , model.parameters() )
_UpperCAmelCase = sum([np.prod(p.size() ) for p in model_parameters] )
return params
UpperCAmelCase__ = logging.getLogger(__name__)
def A ( _UpperCAmelCase : List[Any] , _UpperCAmelCase : Union[str, Any] ) -> Any:
'''simple docstring'''
if metric == "rouge2":
_UpperCAmelCase = '{val_avg_rouge2:.4f}-{step_count}'
elif metric == "bleu":
_UpperCAmelCase = '{val_avg_bleu:.4f}-{step_count}'
elif metric == "em":
_UpperCAmelCase = '{val_avg_em:.4f}-{step_count}'
elif metric == "loss":
_UpperCAmelCase = '{val_avg_loss:.4f}-{step_count}'
else:
raise NotImplementedError(
F"seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this"
' function.' )
_UpperCAmelCase = ModelCheckpoint(
dirpath=_UpperCAmelCase , filename=_UpperCAmelCase , monitor=F"val_{metric}" , mode='max' , save_top_k=1 , every_n_epochs=1 , )
return checkpoint_callback
def A ( _UpperCAmelCase : Any , _UpperCAmelCase : int ) -> str:
'''simple docstring'''
return EarlyStopping(
monitor=F"val_{metric}" , mode='min' if 'loss' in metric else 'max' , patience=_UpperCAmelCase , verbose=_UpperCAmelCase , )
class __lowerCAmelCase ( pl.Callback ):
def _lowerCamelCase ( self : Optional[int] , A : List[Any] , A : int) -> Dict:
"""simple docstring"""
_UpperCAmelCase = {F"lr_group_{i}": param['lr'] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups)}
pl_module.logger.log_metrics(A)
@rank_zero_only
def _lowerCamelCase ( self : Optional[Any] , A : pl.Trainer , A : pl.LightningModule , A : str , A : int=True) -> None:
"""simple docstring"""
logger.info(F"***** {type_path} results at step {trainer.global_step:05d} *****")
_UpperCAmelCase = trainer.callback_metrics
trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['log', 'progress_bar', 'preds']})
# Log results
_UpperCAmelCase = Path(pl_module.hparams.output_dir)
if type_path == "test":
_UpperCAmelCase = od / 'test_results.txt'
_UpperCAmelCase = od / 'test_generations.txt'
else:
# this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json
# If people want this it will be easy enough to add back.
_UpperCAmelCase = od / F"{type_path}_results/{trainer.global_step:05d}.txt"
_UpperCAmelCase = od / F"{type_path}_generations/{trainer.global_step:05d}.txt"
results_file.parent.mkdir(exist_ok=A)
generations_file.parent.mkdir(exist_ok=A)
with open(A , 'a+') as writer:
for key in sorted(A):
if key in ["log", "progress_bar", "preds"]:
continue
_UpperCAmelCase = metrics[key]
if isinstance(A , torch.Tensor):
_UpperCAmelCase = val.item()
_UpperCAmelCase = F"{key}: {val:.6f}\n"
writer.write(A)
if not save_generations:
return
if "preds" in metrics:
_UpperCAmelCase = '\n'.join(metrics['preds'])
generations_file.open('w+').write(A)
@rank_zero_only
def _lowerCamelCase ( self : str , A : Optional[int] , A : List[str]) -> Optional[Any]:
"""simple docstring"""
try:
_UpperCAmelCase = pl_module.model.model.num_parameters()
except AttributeError:
_UpperCAmelCase = pl_module.model.num_parameters()
_UpperCAmelCase = count_trainable_parameters(A)
# mp stands for million parameters
trainer.logger.log_metrics({'n_params': npars, 'mp': npars / 1E6, 'grad_mp': n_trainable_pars / 1E6})
@rank_zero_only
def _lowerCamelCase ( self : Dict , A : pl.Trainer , A : pl.LightningModule) -> int:
"""simple docstring"""
save_json(pl_module.metrics , pl_module.metrics_save_path)
return self._write_logs(A , A , 'test')
@rank_zero_only
def _lowerCamelCase ( self : Tuple , A : pl.Trainer , A : str) -> Dict:
"""simple docstring"""
save_json(pl_module.metrics , pl_module.metrics_save_path)
# Uncommenting this will save val generations
# return self._write_logs(trainer, pl_module, "valid")
| 639 | 1 |
import argparse
import json
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.utils.deepspeed import DummyOptim, DummyScheduler
lowerCAmelCase : str = 16
lowerCAmelCase : int = 32
def lowerCAmelCase ( UpperCamelCase__ : Any , UpperCamelCase__ : str = 16 , UpperCamelCase__ : Optional[Any] = "bert-base-cased" ) -> List[Any]:
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Union[str, Any] = AutoTokenizer.from_pretrained(UpperCamelCase_ )
__SCREAMING_SNAKE_CASE: List[str] = load_dataset('''glue''' , '''mrpc''' )
def tokenize_function(UpperCamelCase__ : Optional[Any] ):
# max_length=None => use the model max length (it's actually the default)
__SCREAMING_SNAKE_CASE: Tuple = 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
__SCREAMING_SNAKE_CASE: Any = datasets.map(
UpperCamelCase_ , batched=UpperCamelCase_ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , load_from_cache_file=UpperCamelCase_ )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
__SCREAMING_SNAKE_CASE: Optional[int] = tokenized_datasets.rename_column('''label''' , '''labels''' )
def collate_fn(UpperCamelCase__ : int ):
# On TPU it's best to pad everything to the same length or training will be very slow.
if accelerator.distributed_type == DistributedType.TPU:
return tokenizer.pad(UpperCamelCase_ , padding='''max_length''' , max_length=128 , return_tensors='''pt''' )
return tokenizer.pad(UpperCamelCase_ , padding='''longest''' , return_tensors='''pt''' )
# Instantiate dataloaders.
__SCREAMING_SNAKE_CASE: Union[str, Any] = DataLoader(
tokenized_datasets['''train'''] , shuffle=UpperCamelCase_ , collate_fn=UpperCamelCase_ , batch_size=UpperCamelCase_ )
__SCREAMING_SNAKE_CASE: Optional[int] = DataLoader(
tokenized_datasets['''validation'''] , shuffle=UpperCamelCase_ , collate_fn=UpperCamelCase_ , batch_size=UpperCamelCase_ )
return train_dataloader, eval_dataloader
def lowerCAmelCase ( UpperCamelCase__ : Any , UpperCamelCase__ : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[Any] ) -> Union[str, Any]:
"""simple docstring"""
model.eval()
__SCREAMING_SNAKE_CASE: Union[str, Any] = 0
for step, batch in enumerate(UpperCamelCase_ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
__SCREAMING_SNAKE_CASE: Optional[int] = model(**UpperCamelCase_ )
__SCREAMING_SNAKE_CASE: Tuple = outputs.logits.argmax(dim=-1 )
# It is slightly faster to call this once, than multiple times
__SCREAMING_SNAKE_CASE: Union[str, Any] = accelerator.gather(
(predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates
if accelerator.use_distributed:
if step == len(UpperCamelCase_ ) - 1:
__SCREAMING_SNAKE_CASE: str = predictions[: len(eval_dataloader.dataset ) - samples_seen]
__SCREAMING_SNAKE_CASE: Tuple = references[: len(eval_dataloader.dataset ) - samples_seen]
else:
samples_seen += references.shape[0]
metric.add_batch(
predictions=UpperCamelCase_ , references=UpperCamelCase_ , )
__SCREAMING_SNAKE_CASE: int = metric.compute()
return eval_metric["accuracy"]
def lowerCAmelCase ( UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[Any] ) -> List[Any]:
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Any = Accelerator()
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
__SCREAMING_SNAKE_CASE: List[str] = config['''lr''']
__SCREAMING_SNAKE_CASE: List[Any] = int(config['''num_epochs'''] )
__SCREAMING_SNAKE_CASE: Optional[Any] = int(config['''seed'''] )
__SCREAMING_SNAKE_CASE: List[Any] = int(config['''batch_size'''] )
__SCREAMING_SNAKE_CASE: Optional[Any] = args.model_name_or_path
set_seed(UpperCamelCase_ )
__SCREAMING_SNAKE_CASE: Optional[int] = get_dataloaders(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
__SCREAMING_SNAKE_CASE: Any = AutoModelForSequenceClassification.from_pretrained(UpperCamelCase_ , return_dict=UpperCamelCase_ )
# Instantiate optimizer
__SCREAMING_SNAKE_CASE: List[str] = (
AdamW
if accelerator.state.deepspeed_plugin is None
or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config
else DummyOptim
)
__SCREAMING_SNAKE_CASE: int = optimizer_cls(params=model.parameters() , lr=UpperCamelCase_ )
if accelerator.state.deepspeed_plugin is not None:
__SCREAMING_SNAKE_CASE: Union[str, Any] = accelerator.state.deepspeed_plugin.deepspeed_config[
'''gradient_accumulation_steps'''
]
else:
__SCREAMING_SNAKE_CASE: List[str] = 1
__SCREAMING_SNAKE_CASE: List[Any] = (len(UpperCamelCase_ ) * num_epochs) // gradient_accumulation_steps
# Instantiate scheduler
if (
accelerator.state.deepspeed_plugin is None
or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
):
__SCREAMING_SNAKE_CASE: List[str] = get_linear_schedule_with_warmup(
optimizer=UpperCamelCase_ , num_warmup_steps=0 , num_training_steps=UpperCamelCase_ , )
else:
__SCREAMING_SNAKE_CASE: Optional[int] = DummyScheduler(UpperCamelCase_ , total_num_steps=UpperCamelCase_ , warmup_num_steps=0 )
# 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.
__SCREAMING_SNAKE_CASE: List[str] = accelerator.prepare(
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
# We need to keep track of how many total steps we have iterated over
__SCREAMING_SNAKE_CASE: Any = 0
# We also need to keep track of the stating epoch so files are named properly
__SCREAMING_SNAKE_CASE: Optional[int] = 0
__SCREAMING_SNAKE_CASE: int = evaluate.load('''glue''' , '''mrpc''' )
__SCREAMING_SNAKE_CASE: List[Any] = num_epochs
if args.partial_train_epoch is not None:
__SCREAMING_SNAKE_CASE: Optional[int] = args.partial_train_epoch
if args.resume_from_checkpoint:
accelerator.load_state(args.resume_from_checkpoint )
__SCREAMING_SNAKE_CASE: Union[str, Any] = args.resume_from_checkpoint.split('''epoch_''' )[1]
__SCREAMING_SNAKE_CASE: List[Any] = ''''''
for char in epoch_string:
if char.isdigit():
state_epoch_num += char
else:
break
__SCREAMING_SNAKE_CASE: Any = int(UpperCamelCase_ ) + 1
__SCREAMING_SNAKE_CASE: str = evaluation_loop(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
accelerator.print('''resumed checkpoint performance:''' , UpperCamelCase_ )
accelerator.print('''resumed checkpoint\'s scheduler\'s lr:''' , lr_scheduler.get_lr()[0] )
accelerator.print('''resumed optimizers\'s lr:''' , optimizer.param_groups[0]['''lr'''] )
with open(os.path.join(args.output_dir , F"""state_{starting_epoch-1}.json""" ) , '''r''' ) as f:
__SCREAMING_SNAKE_CASE: List[Any] = json.load(UpperCamelCase_ )
assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed"
assert (
resumed_state["lr"] == lr_scheduler.get_lr()[0]
), "Scheduler learning rate mismatch, loading from checkpoint failed"
assert (
resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"]
), "Optimizer learning rate mismatch, loading from checkpoint failed"
assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed"
return
# Now we train the model
__SCREAMING_SNAKE_CASE: Any = {}
for epoch in range(UpperCamelCase_ , UpperCamelCase_ ):
model.train()
for step, batch in enumerate(UpperCamelCase_ ):
__SCREAMING_SNAKE_CASE: List[Any] = model(**UpperCamelCase_ )
__SCREAMING_SNAKE_CASE: Optional[int] = outputs.loss
__SCREAMING_SNAKE_CASE: Union[str, Any] = loss / gradient_accumulation_steps
accelerator.backward(UpperCamelCase_ )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
__SCREAMING_SNAKE_CASE: int = F"""epoch_{epoch}"""
__SCREAMING_SNAKE_CASE: Optional[Any] = os.path.join(args.output_dir , UpperCamelCase_ )
accelerator.save_state(UpperCamelCase_ )
__SCREAMING_SNAKE_CASE: int = evaluation_loop(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
__SCREAMING_SNAKE_CASE: Optional[Any] = accuracy
__SCREAMING_SNAKE_CASE: int = lr_scheduler.get_lr()[0]
__SCREAMING_SNAKE_CASE: List[str] = optimizer.param_groups[0]['''lr''']
__SCREAMING_SNAKE_CASE: str = epoch
__SCREAMING_SNAKE_CASE: List[Any] = overall_step
accelerator.print(F"""epoch {epoch}:""" , UpperCamelCase_ )
accelerator.wait_for_everyone()
if accelerator.is_main_process:
with open(os.path.join(args.output_dir , F"""state_{epoch}.json""" ) , '''w''' ) as f:
json.dump(UpperCamelCase_ , UpperCamelCase_ )
def lowerCAmelCase ( ) -> List[Any]:
"""simple docstring"""
__SCREAMING_SNAKE_CASE: List[str] = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' )
parser.add_argument(
'''--model_name_or_path''' , type=UpperCamelCase_ , default='''bert-base-cased''' , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=UpperCamelCase_ , )
parser.add_argument(
'''--output_dir''' , type=UpperCamelCase_ , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , )
parser.add_argument(
'''--resume_from_checkpoint''' , type=UpperCamelCase_ , default=UpperCamelCase_ , help='''If the training should continue from a checkpoint folder.''' , )
parser.add_argument(
'''--partial_train_epoch''' , type=UpperCamelCase_ , default=UpperCamelCase_ , help='''If passed, the training will stop after this number of epochs.''' , )
parser.add_argument(
'''--num_epochs''' , type=UpperCamelCase_ , default=2 , help='''Number of train epochs.''' , )
__SCREAMING_SNAKE_CASE: List[Any] = parser.parse_args()
__SCREAMING_SNAKE_CASE: Optional[Any] = {'''lr''': 2E-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16}
training_function(UpperCamelCase_ , UpperCamelCase_ )
if __name__ == "__main__":
main()
| 202 |
import re
def lowerCamelCase_ ( UpperCamelCase_ ):
_a : Dict = re.compile(
R'''^(?:0|94|\+94|0{2}94)''' R'''7(0|1|2|4|5|6|7|8)''' R'''(-| |)''' R'''\d{7}$''' )
return bool(re.search(UpperCamelCase_ , UpperCamelCase_ ) )
if __name__ == "__main__":
__UpperCAmelCase : List[Any] = '0094702343221'
print(is_sri_lankan_phone_number(phone))
| 471 | 0 |
import os
import zipfile
import pytest
from datasets.utils.extract import (
BzipaExtractor,
Extractor,
GzipExtractor,
LzaExtractor,
SevenZipExtractor,
TarExtractor,
XzExtractor,
ZipExtractor,
ZstdExtractor,
)
from .utils import require_lza, require_pyazr, require_zstandard
@pytest.mark.parametrize(
"compression_format, is_archive" ,[
("7z", True),
("bz2", False),
("gzip", False),
("lz4", False),
("tar", True),
("xz", False),
("zip", True),
("zstd", False),
] ,)
def snake_case_ ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,) -> List[Any]:
lowercase__ : List[str] = {
"7z": (seven_zip_file, SevenZipExtractor),
"bz2": (bza_file, BzipaExtractor),
"gzip": (gz_file, GzipExtractor),
"lz4": (lza_file, LzaExtractor),
"tar": (tar_file, TarExtractor),
"xz": (xz_file, XzExtractor),
"zip": (zip_file, ZipExtractor),
"zstd": (zstd_file, ZstdExtractor),
}
lowercase__ , lowercase__ : Tuple = input_paths_and_base_extractors[compression_format]
if input_path is None:
lowercase__ : List[Any] = F"""for '{compression_format}' compression_format, """
if compression_format == "7z":
reason += require_pyazr.kwargs["reason"]
elif compression_format == "lz4":
reason += require_lza.kwargs["reason"]
elif compression_format == "zstd":
reason += require_zstandard.kwargs["reason"]
pytest.skip(SCREAMING_SNAKE_CASE_ )
assert base_extractor.is_extractable(SCREAMING_SNAKE_CASE_ )
lowercase__ : str = tmp_path / ("extracted" if is_archive else "extracted.txt")
base_extractor.extract(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
if is_archive:
assert output_path.is_dir()
for file_path in output_path.iterdir():
assert file_path.name == text_file.name
lowercase__ : Tuple = file_path.read_text(encoding="utf-8" )
else:
lowercase__ : List[str] = output_path.read_text(encoding="utf-8" )
lowercase__ : Dict = text_file.read_text(encoding="utf-8" )
assert extracted_file_content == expected_file_content
@pytest.mark.parametrize(
"compression_format, is_archive" ,[
("7z", True),
("bz2", False),
("gzip", False),
("lz4", False),
("tar", True),
("xz", False),
("zip", True),
("zstd", False),
] ,)
def snake_case_ ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,) -> Optional[Any]:
lowercase__ : Optional[Any] = {
"7z": seven_zip_file,
"bz2": bza_file,
"gzip": gz_file,
"lz4": lza_file,
"tar": tar_file,
"xz": xz_file,
"zip": zip_file,
"zstd": zstd_file,
}
lowercase__ : List[Any] = input_paths[compression_format]
if input_path is None:
lowercase__ : Union[str, Any] = F"""for '{compression_format}' compression_format, """
if compression_format == "7z":
reason += require_pyazr.kwargs["reason"]
elif compression_format == "lz4":
reason += require_lza.kwargs["reason"]
elif compression_format == "zstd":
reason += require_zstandard.kwargs["reason"]
pytest.skip(SCREAMING_SNAKE_CASE_ )
lowercase__ : List[Any] = Extractor.infer_extractor_format(SCREAMING_SNAKE_CASE_ )
assert extractor_format is not None
lowercase__ : Optional[int] = tmp_path / ("extracted" if is_archive else "extracted.txt")
Extractor.extract(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
if is_archive:
assert output_path.is_dir()
for file_path in output_path.iterdir():
assert file_path.name == text_file.name
lowercase__ : Tuple = file_path.read_text(encoding="utf-8" )
else:
lowercase__ : Dict = output_path.read_text(encoding="utf-8" )
lowercase__ : Optional[Any] = text_file.read_text(encoding="utf-8" )
assert extracted_file_content == expected_file_content
@pytest.fixture
def snake_case_ ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) -> int:
import tarfile
lowercase__ : Any = tmp_path / "data_dot_dot"
directory.mkdir()
lowercase__ : Union[str, Any] = directory / "tar_file_with_dot_dot.tar"
with tarfile.TarFile(SCREAMING_SNAKE_CASE_ ,"w" ) as f:
f.add(SCREAMING_SNAKE_CASE_ ,arcname=os.path.join(".." ,text_file.name ) )
return path
@pytest.fixture
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> int:
import tarfile
lowercase__ : List[str] = tmp_path / "data_sym_link"
directory.mkdir()
lowercase__ : Tuple = directory / "tar_file_with_sym_link.tar"
os.symlink(".." ,directory / "subdir" ,target_is_directory=SCREAMING_SNAKE_CASE_ )
with tarfile.TarFile(SCREAMING_SNAKE_CASE_ ,"w" ) as f:
f.add(str(directory / "subdir" ) ,arcname="subdir" ) # str required by os.readlink on Windows and Python < 3.8
return path
@pytest.mark.parametrize(
"insecure_tar_file, error_log" ,[("tar_file_with_dot_dot", "illegal path"), ("tar_file_with_sym_link", "Symlink")] ,)
def snake_case_ ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) -> Tuple:
lowercase__ : Dict = {
"tar_file_with_dot_dot": tar_file_with_dot_dot,
"tar_file_with_sym_link": tar_file_with_sym_link,
}
lowercase__ : Dict = insecure_tar_files[insecure_tar_file]
lowercase__ : Optional[int] = tmp_path / "extracted"
TarExtractor.extract(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
assert caplog.text
for record in caplog.records:
assert record.levelname == "ERROR"
assert error_log in record.msg
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> List[Any]:
# We should have less false positives than zipfile.is_zipfile
# We do that by checking only the magic number
lowercase__ : Dict = tmpdir / "not_a_zip_file"
# From: https://github.com/python/cpython/pull/5053
lowercase__ : str = (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00"
b"\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6'\x00\x00\x00\x15I"
b"DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07"
b"\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82"
)
with not_a_zip_file.open("wb" ) as f:
f.write(SCREAMING_SNAKE_CASE_ )
assert zipfile.is_zipfile(str(SCREAMING_SNAKE_CASE_ ) ) # is a false positive for `zipfile`
assert not ZipExtractor.is_extractable(SCREAMING_SNAKE_CASE_ ) # but we're right | 298 |
import inspect
import os
import unittest
import torch
import accelerate
from accelerate import debug_launcher
from accelerate.test_utils import (
execute_subprocess_async,
require_cpu,
require_huggingface_suite,
require_multi_gpu,
require_single_gpu,
)
from accelerate.utils import patch_environment
@require_huggingface_suite
class UpperCAmelCase( unittest.TestCase ):
"""simple docstring"""
def __a ( self ) -> Optional[Any]:
"""simple docstring"""
lowercase__ : Optional[int] = inspect.getfile(accelerate.test_utils )
lowercase__ : Union[str, Any] = os.path.sep.join(
mod_file.split(os.path.sep )[:-1] + ["scripts", "external_deps", "test_metrics.py"] )
from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401
lowercase__ : Optional[int] = test_metrics
@require_cpu
def __a ( self ) -> List[Any]:
"""simple docstring"""
debug_launcher(self.test_metrics.main , num_processes=1 )
@require_cpu
def __a ( self ) -> Union[str, Any]:
"""simple docstring"""
debug_launcher(self.test_metrics.main )
@require_single_gpu
def __a ( self ) -> Dict:
"""simple docstring"""
self.test_metrics.main()
@require_multi_gpu
def __a ( self ) -> str:
"""simple docstring"""
print(f"""Found {torch.cuda.device_count()} devices.""" )
lowercase__ : Optional[Any] = ["torchrun", f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path]
with patch_environment(omp_num_threads=1 ):
execute_subprocess_async(lowerCamelCase , env=os.environ.copy() ) | 298 | 1 |
import doctest
from collections import deque
import numpy as np
class _a :
"""simple docstring"""
def __init__( self ) -> None:
UpperCamelCase_ = [2, 1, 2, -1]
UpperCamelCase_ = [1, 2, 3, 4]
def _UpperCAmelCase ( self ) -> list[float]:
UpperCamelCase_ = len(self.first_signal )
UpperCamelCase_ = len(self.second_signal )
UpperCamelCase_ = max(_UpperCAmelCase , _UpperCAmelCase )
# create a zero matrix of max_length x max_length
UpperCamelCase_ = [[0] * max_length for i in range(_UpperCAmelCase )]
# fills the smaller signal with zeros to make both signals of same length
if length_first_signal < length_second_signal:
self.first_signal += [0] * (max_length - length_first_signal)
elif length_first_signal > length_second_signal:
self.second_signal += [0] * (max_length - length_second_signal)
for i in range(_UpperCAmelCase ):
UpperCamelCase_ = deque(self.second_signal )
rotated_signal.rotate(_UpperCAmelCase )
for j, item in enumerate(_UpperCAmelCase ):
matrix[i][j] += item
# multiply the matrix with the first signal
UpperCamelCase_ = np.matmul(np.transpose(_UpperCAmelCase ) , np.transpose(self.first_signal ) )
# rounding-off to two decimal places
return [round(_UpperCAmelCase , 2 ) for i in final_signal]
if __name__ == "__main__":
doctest.testmod()
| 23 |
def a__ ( A__ = 5_0_0_0_0_0_0_0 ):
SCREAMING_SNAKE_CASE_ : Union[str, Any] = set()
SCREAMING_SNAKE_CASE_ : Optional[int] = int((limit - 2_4) ** (1 / 2) )
SCREAMING_SNAKE_CASE_ : Dict = 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:
SCREAMING_SNAKE_CASE_ : int = primea * primea
for primea in primes:
SCREAMING_SNAKE_CASE_ : Dict = primea * primea * primea
if square + cube >= limit - 1_6:
break
for primea in primes:
SCREAMING_SNAKE_CASE_ : Optional[int] = primea * primea * primea * primea
SCREAMING_SNAKE_CASE_ : str = square + cube + tetr
if total >= limit:
break
ret.add(A__ )
return len(A__ )
if __name__ == "__main__":
print(F"""{solution() = }""")
| 101 | 0 |
"""simple docstring"""
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
SCREAMING_SNAKE_CASE_ = {
"""albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""",
"""albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""",
"""albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""",
"""albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""",
"""albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""",
"""albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""",
"""albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""",
"""albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""",
}
class snake_case_ ( a_ ):
__lowerCAmelCase = "albert"
def __init__( self , a_=3_0_0_0_0 , a_=1_2_8 , a_=4_0_9_6 , a_=1_2 , a_=1 , a_=6_4 , a_=1_6_3_8_4 , a_=1 , a_="gelu_new" , a_=0 , a_=0 , a_=5_1_2 , a_=2 , a_=0.02 , a_=1e-12 , a_=0.1 , a_="absolute" , a_=0 , a_=2 , a_=3 , **a_ , ):
super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ )
a_ : Optional[Any] = vocab_size
a_ : Dict = embedding_size
a_ : Optional[Any] = hidden_size
a_ : Optional[int] = num_hidden_layers
a_ : Optional[Any] = num_hidden_groups
a_ : Optional[Any] = num_attention_heads
a_ : Union[str, Any] = inner_group_num
a_ : List[Any] = hidden_act
a_ : Optional[int] = intermediate_size
a_ : int = hidden_dropout_prob
a_ : List[str] = attention_probs_dropout_prob
a_ : Dict = max_position_embeddings
a_ : Any = type_vocab_size
a_ : Dict = initializer_range
a_ : Dict = layer_norm_eps
a_ : Union[str, Any] = classifier_dropout_prob
a_ : str = position_embedding_type
class snake_case_ ( a_ ):
@property
def snake_case_ ( self ):
if self.task == "multiple-choice":
a_ : Union[str, Any] = {0: "batch", 1: "choice", 2: "sequence"}
else:
a_ : Optional[int] = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
("token_type_ids", dynamic_axis),
] ) | 370 |
"""simple docstring"""
import argparse
import os
import torch
from transformers import (
XLNetConfig,
XLNetForQuestionAnswering,
XLNetForSequenceClassification,
XLNetLMHeadModel,
load_tf_weights_in_xlnet,
)
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
SCREAMING_SNAKE_CASE_ = {
"""cola""": 2,
"""mnli""": 3,
"""mrpc""": 2,
"""sst-2""": 2,
"""sts-b""": 1,
"""qqp""": 2,
"""qnli""": 2,
"""rte""": 2,
"""wnli""": 2,
}
logging.set_verbosity_info()
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__=None ) -> int:
# Initialise PyTorch model
a_ : Optional[int] = XLNetConfig.from_json_file(SCREAMING_SNAKE_CASE__ )
a_ : List[Any] = finetuning_task.lower() if finetuning_task is not None else ""
if finetuning_task in GLUE_TASKS_NUM_LABELS:
print(F"""Building PyTorch XLNetForSequenceClassification model from configuration: {config}""" )
a_ : Tuple = finetuning_task
a_ : Dict = GLUE_TASKS_NUM_LABELS[finetuning_task]
a_ : Tuple = XLNetForSequenceClassification(SCREAMING_SNAKE_CASE__ )
elif "squad" in finetuning_task:
a_ : Tuple = finetuning_task
a_ : List[Any] = XLNetForQuestionAnswering(SCREAMING_SNAKE_CASE__ )
else:
a_ : Any = XLNetLMHeadModel(SCREAMING_SNAKE_CASE__ )
# Load weights from tf checkpoint
load_tf_weights_in_xlnet(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
# Save pytorch-model
a_ : Tuple = os.path.join(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
a_ : str = os.path.join(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
print(F"""Save PyTorch model to {os.path.abspath(SCREAMING_SNAKE_CASE__ )}""" )
torch.save(model.state_dict(), SCREAMING_SNAKE_CASE__ )
print(F"""Save configuration file to {os.path.abspath(SCREAMING_SNAKE_CASE__ )}""" )
with open(SCREAMING_SNAKE_CASE__, "w", encoding="utf-8" ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
)
parser.add_argument(
"""--xlnet_config_file""",
default=None,
type=str,
required=True,
help=(
"""The config json file corresponding to the pre-trained XLNet model. \n"""
"""This specifies the model architecture."""
),
)
parser.add_argument(
"""--pytorch_dump_folder_path""",
default=None,
type=str,
required=True,
help="""Path to the folder to store the PyTorch model or dataset/vocab.""",
)
parser.add_argument(
"""--finetuning_task""",
default=None,
type=str,
help="""Name of a task on which the XLNet TensorFlow model was fine-tuned""",
)
SCREAMING_SNAKE_CASE_ = parser.parse_args()
print(args)
convert_xlnet_checkpoint_to_pytorch(
args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task
) | 370 | 1 |
'''simple docstring'''
import ast
import os
import re
import shutil
import tempfile
import unittest
from unittest import mock
import torch
from accelerate.test_utils.examples import compare_against_test
from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow
from accelerate.utils import write_basic_config
# DataLoaders built from `test_samples/MRPC` for quick testing
# Should mock `{script_name}.get_dataloaders` via:
# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders)
__UpperCAmelCase = [
'''cross_validation.py''',
'''gradient_accumulation.py''',
'''local_sgd.py''',
'''multi_process_metrics.py''',
'''memory.py''',
'''automatic_gradient_accumulation.py''',
'''fsdp_with_peak_mem_tracking.py''',
'''deepspeed_with_config_support.py''',
'''megatron_lm_gpt_pretraining.py''',
]
class a__ ( unittest.TestCase ):
'''simple docstring'''
def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = None , lowerCamelCase_ = None ) -> Any:
lowerCAmelCase__ = None
lowerCAmelCase__ = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) )
lowerCAmelCase__ = os.path.abspath('''examples''' )
for item in os.listdir(lowerCamelCase_ ):
if item not in EXCLUDE_EXAMPLES:
lowerCAmelCase__ = os.path.join(lowerCamelCase_ , lowerCamelCase_ )
if os.path.isfile(lowerCamelCase_ ) and ".py" in item_path:
with self.subTest(
tested_script=lowerCamelCase_ , feature_script=lowerCamelCase_ , tested_section='''main()''' if parser_only else '''training_function()''' , ):
lowerCAmelCase__ = compare_against_test(
os.path.join(lowerCamelCase_ , lowerCamelCase_ ) , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
lowerCAmelCase__ = '''\n'''.join(lowerCamelCase_ )
if special_strings is not None:
for string in special_strings:
lowerCAmelCase__ = diff.replace(lowerCamelCase_ , '''''' )
self.assertEqual(lowerCamelCase_ , '''''' )
def __SCREAMING_SNAKE_CASE ( self ) -> Any:
self.one_complete_example('''complete_nlp_example.py''' , lowerCamelCase_ )
self.one_complete_example('''complete_nlp_example.py''' , lowerCamelCase_ )
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
lowerCAmelCase__ = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) )
lowerCAmelCase__ = [
''' ''' * 16 + '''{\n\n''',
''' ''' * 20 + '''"accuracy": eval_metric["accuracy"],\n\n''',
''' ''' * 20 + '''"f1": eval_metric["f1"],\n\n''',
''' ''' * 20 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''',
''' ''' * 20 + '''"epoch": epoch,\n\n''',
''' ''' * 16 + '''},\n\n''',
''' ''' * 16 + '''step=epoch,\n''',
''' ''' * 12,
''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''',
]
self.one_complete_example('''complete_cv_example.py''' , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
self.one_complete_example('''complete_cv_example.py''' , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
@mock.patch.dict(os.environ , {"TESTING_MOCKED_DATALOADERS": "1"} )
class a__ ( a__ ):
'''simple docstring'''
lowercase__ : Optional[Any] = False
@classmethod
def __SCREAMING_SNAKE_CASE ( cls ) -> Optional[Any]:
super().setUpClass()
lowerCAmelCase__ = tempfile.mkdtemp()
lowerCAmelCase__ = os.path.join(cls._tmpdir , '''default_config.yml''' )
write_basic_config(save_location=cls.configPath )
lowerCAmelCase__ = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath]
@classmethod
def __SCREAMING_SNAKE_CASE ( cls ) -> str:
super().tearDownClass()
shutil.rmtree(cls._tmpdir )
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
lowerCAmelCase__ = F"""
examples/by_feature/checkpointing.py
--checkpointing_steps epoch
--output_dir {self.tmpdir}
""".split()
run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) )
def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
lowerCAmelCase__ = F"""
examples/by_feature/checkpointing.py
--checkpointing_steps 1
--output_dir {self.tmpdir}
""".split()
lowerCAmelCase__ = run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) )
def __SCREAMING_SNAKE_CASE ( self ) -> str:
lowerCAmelCase__ = F"""
examples/by_feature/checkpointing.py
--resume_from_checkpoint {os.path.join(self.tmpdir , "epoch_0" )}
""".split()
lowerCAmelCase__ = run_command(self._launch_args + testargs , return_stdout=lowerCamelCase_ )
self.assertNotIn('''epoch 0:''' , lowerCamelCase_ )
self.assertIn('''epoch 1:''' , lowerCamelCase_ )
def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
lowerCAmelCase__ = F"""
examples/by_feature/checkpointing.py
--resume_from_checkpoint {os.path.join(self.tmpdir , "step_2" )}
""".split()
lowerCAmelCase__ = run_command(self._launch_args + testargs , return_stdout=lowerCamelCase_ )
if torch.cuda.is_available():
lowerCAmelCase__ = torch.cuda.device_count()
else:
lowerCAmelCase__ = 1
if num_processes > 1:
self.assertNotIn('''epoch 0:''' , lowerCamelCase_ )
self.assertIn('''epoch 1:''' , lowerCamelCase_ )
else:
self.assertIn('''epoch 0:''' , lowerCamelCase_ )
self.assertIn('''epoch 1:''' , lowerCamelCase_ )
@slow
def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
lowerCAmelCase__ = '''
examples/by_feature/cross_validation.py
--num_folds 2
'''.split()
with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ):
lowerCAmelCase__ = run_command(self._launch_args + testargs , return_stdout=lowerCamelCase_ )
lowerCAmelCase__ = re.findall('''({.+})''' , lowerCamelCase_ )
lowerCAmelCase__ = [r for r in results if '''accuracy''' in r][-1]
lowerCAmelCase__ = ast.literal_eval(lowerCamelCase_ )
self.assertGreaterEqual(results['''accuracy'''] , 0.75 )
def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
lowerCAmelCase__ = ['''examples/by_feature/multi_process_metrics.py''']
run_command(self._launch_args + testargs )
@require_trackers
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def __SCREAMING_SNAKE_CASE ( self ) -> List[str]:
with tempfile.TemporaryDirectory() as tmpdir:
lowerCAmelCase__ = F"""
examples/by_feature/tracking.py
--with_tracking
--project_dir {tmpdir}
""".split()
run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(lowerCamelCase_ , '''tracking''' ) ) )
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]:
lowerCAmelCase__ = ['''examples/by_feature/gradient_accumulation.py''']
run_command(self._launch_args + testargs )
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
lowerCAmelCase__ = ['''examples/by_feature/local_sgd.py''']
run_command(self._launch_args + testargs ) | 90 |
"""simple docstring"""
from statistics import mean, stdev
def _A ( _a : list , _a : int = 3 ):
"""simple docstring"""
A = min(_a )
A = max(_a )
# normalize data
return [round((x - x_min) / (x_max - x_min) , _a ) for x in data]
def _A ( _a : list , _a : int = 3 ):
"""simple docstring"""
A = mean(_a )
A = stdev(_a )
# standardize data
return [round((x - mu) / (sigma) , _a ) for x in data]
| 617 | 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
__UpperCAmelCase : Optional[Any] = logging.get_logger(__name__)
__UpperCAmelCase : Optional[Any] = {
"hustvl/yolos-small": "https://huggingface.co/hustvl/yolos-small/resolve/main/config.json",
# See all YOLOS models at https://huggingface.co/models?filter=yolos
}
class __snake_case ( __lowerCamelCase ):
'''simple docstring'''
lowerCAmelCase__ = """yolos"""
def __init__( self : Optional[int] , A : Optional[Any]=768 , A : Any=12 , A : List[str]=12 , A : List[str]=3_072 , A : Union[str, Any]="gelu" , A : List[Any]=0.0 , A : Optional[int]=0.0 , A : List[str]=0.02 , A : Optional[Any]=1E-12 , A : Any=[512, 864] , A : Optional[Any]=16 , A : Tuple=3 , A : str=True , A : Any=100 , A : Tuple=True , A : Tuple=False , A : str=1 , A : Optional[int]=5 , A : Dict=2 , A : Union[str, Any]=5 , A : Optional[int]=2 , A : Optional[Any]=0.1 , **A : Optional[int] , ):
super().__init__(**A )
__snake_case: str = hidden_size
__snake_case: Optional[Any] = num_hidden_layers
__snake_case: Optional[int] = num_attention_heads
__snake_case: List[Any] = intermediate_size
__snake_case: Optional[Any] = hidden_act
__snake_case: Optional[int] = hidden_dropout_prob
__snake_case: Dict = attention_probs_dropout_prob
__snake_case: List[str] = initializer_range
__snake_case: str = layer_norm_eps
__snake_case: str = image_size
__snake_case: Any = patch_size
__snake_case: Dict = num_channels
__snake_case: int = qkv_bias
__snake_case: List[Any] = num_detection_tokens
__snake_case: Any = use_mid_position_embeddings
__snake_case: str = auxiliary_loss
# Hungarian matcher
__snake_case: Optional[int] = class_cost
__snake_case: int = bbox_cost
__snake_case: Optional[Any] = giou_cost
# Loss coefficients
__snake_case: Tuple = bbox_loss_coefficient
__snake_case: int = giou_loss_coefficient
__snake_case: Tuple = eos_coefficient
class __snake_case ( __lowerCamelCase ):
'''simple docstring'''
lowerCAmelCase__ = version.parse("""1.11""" )
@property
def UpperCAmelCase__ ( self : int ):
return OrderedDict(
[
("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
] )
@property
def UpperCAmelCase__ ( self : Optional[int] ):
return 1E-4
@property
def UpperCAmelCase__ ( self : List[str] ):
return 12
| 155 |
import json
import os
import subprocess
import unittest
from ast import literal_eval
import pytest
from parameterized import parameterized, parameterized_class
from . import is_sagemaker_available
if is_sagemaker_available():
from sagemaker import Session, TrainingJobAnalytics
from sagemaker.huggingface import HuggingFace
@pytest.mark.skipif(
literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""" ) ) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , )
@pytest.mark.usefixtures("""sm_env""" )
@parameterized_class(
[
{
"""framework""": """pytorch""",
"""script""": """run_glue.py""",
"""model_name_or_path""": """distilbert-base-cased""",
"""instance_type""": """ml.p3.16xlarge""",
"""results""": {"""train_runtime""": 6_50, """eval_accuracy""": 0.7, """eval_loss""": 0.6},
},
{
"""framework""": """pytorch""",
"""script""": """run_ddp.py""",
"""model_name_or_path""": """distilbert-base-cased""",
"""instance_type""": """ml.p3.16xlarge""",
"""results""": {"""train_runtime""": 6_00, """eval_accuracy""": 0.7, """eval_loss""": 0.6},
},
{
"""framework""": """tensorflow""",
"""script""": """run_tf_dist.py""",
"""model_name_or_path""": """distilbert-base-cased""",
"""instance_type""": """ml.p3.16xlarge""",
"""results""": {"""train_runtime""": 6_00, """eval_accuracy""": 0.6, """eval_loss""": 0.7},
},
] )
class __snake_case ( unittest.TestCase ):
'''simple docstring'''
def UpperCAmelCase__ ( self : Optional[Any] ):
if self.framework == "pytorch":
subprocess.run(
f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding="""utf-8""" , check=A , )
assert hasattr(self , """env""" )
def UpperCAmelCase__ ( self : int , A : List[Any] ):
__snake_case: Optional[int] = f'''{self.env.base_job_name}-{instance_count}-{'ddp' if 'ddp' in self.script else 'smd'}'''
# distributed data settings
__snake_case: Optional[int] = {"""smdistributed""": {"""dataparallel""": {"""enabled""": True}}} if self.script != """run_ddp.py""" else None
# creates estimator
return HuggingFace(
entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=A , instance_count=A , instance_type=self.instance_type , debugger_hook_config=A , hyperparameters={**self.env.distributed_hyperparameters, """model_name_or_path""": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=A , py_version="""py36""" , )
def UpperCAmelCase__ ( self : List[Any] , A : int ):
TrainingJobAnalytics(A ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' )
@parameterized.expand([(2,)] )
def UpperCAmelCase__ ( self : str , A : Any ):
# create estimator
__snake_case: str = self.create_estimator(A )
# run training
estimator.fit()
# result dataframe
__snake_case: Optional[int] = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe()
# extract kpis
__snake_case: Union[str, Any] = list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""] )
__snake_case: List[str] = list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""] )
# get train time from SageMaker job, this includes starting, preprocessing, stopping
__snake_case: Tuple = (
Session().describe_training_job(estimator.latest_training_job.name ).get("""TrainingTimeInSeconds""" , 999_999 )
)
# assert kpis
assert train_runtime <= self.results["train_runtime"]
assert all(t >= self.results["""eval_accuracy"""] for t in eval_accuracy )
assert all(t <= self.results["""eval_loss"""] for t in eval_loss )
# dump tests result into json file to share in PR
with open(f'''{estimator.latest_training_job.name}.json''' , """w""" ) as outfile:
json.dump({"""train_time""": train_runtime, """eval_accuracy""": eval_accuracy, """eval_loss""": eval_loss} , A )
| 155 | 1 |
"""simple docstring"""
import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional
import evaluate
import numpy as np
import torch
from datasets import load_dataset
from PIL import Image
from torchvision.transforms import (
CenterCrop,
Compose,
Normalize,
RandomHorizontalFlip,
RandomResizedCrop,
Resize,
ToTensor,
)
import transformers
from transformers import (
MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
AutoConfig,
AutoImageProcessor,
AutoModelForImageClassification,
HfArgumentParser,
Trainer,
TrainingArguments,
set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
A : Any = logging.getLogger(__name__)
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('4.31.0')
require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/image-classification/requirements.txt')
A : Union[str, Any] = list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys())
A : Any = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
def snake_case__ ( _snake_case : str ):
"""simple docstring"""
with open(_snake_case , "rb" ) as f:
UpperCamelCase__ = Image.open(_snake_case )
return im.convert("RGB" )
@dataclass
class lowerCAmelCase :
'''simple docstring'''
A = field(
default=snake_case__ , metadata={
'help': 'Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).'
} , )
A = field(
default=snake_case__ , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} )
A = field(default=snake_case__ , metadata={'help': 'A folder containing the training data.'} )
A = field(default=snake_case__ , metadata={'help': 'A folder containing the validation data.'} )
A = field(
default=0.15 , metadata={'help': 'Percent to split off of train for validation.'} )
A = field(
default=snake_case__ , metadata={
'help': (
'For debugging purposes or quicker training, truncate the number of training examples to this '
'value if set.'
)
} , )
A = field(
default=snake_case__ , metadata={
'help': (
'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
'value if set.'
)
} , )
def lowerCamelCase__ ( self :Tuple ) -> Any:
"""simple docstring"""
if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
raise ValueError(
"You must specify either a dataset name from the hub or a train and/or validation directory." )
@dataclass
class lowerCAmelCase :
'''simple docstring'''
A = field(
default='google/vit-base-patch16-224-in21k' , metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} , )
A = field(
default=snake_case__ , metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(snake_case__ )} , )
A = field(
default=snake_case__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} )
A = field(
default=snake_case__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'} )
A = field(
default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , )
A = field(default=snake_case__ , metadata={'help': 'Name or path of preprocessor config.'} )
A = field(
default=snake_case__ , metadata={
'help': (
'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
'with private models).'
)
} , )
A = field(
default=snake_case__ , metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'} , )
def snake_case__ ( _snake_case : Dict ):
"""simple docstring"""
UpperCamelCase__ = torch.stack([example["pixel_values"] for example in examples] )
UpperCamelCase__ = torch.tensor([example["labels"] for example in examples] )
return {"pixel_values": pixel_values, "labels": labels}
def snake_case__ ( ):
"""simple docstring"""
UpperCamelCase__ = 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.
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = parser.parse_args_into_dataclasses()
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_image_classification" , _snake_case , _snake_case )
# 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 )] , )
if training_args.should_log:
# The default of training_args.log_level is passive, so we set log level at info here to have that default.
transformers.utils.logging.set_verbosity_info()
UpperCamelCase__ = training_args.get_process_log_level()
logger.setLevel(_snake_case )
transformers.utils.logging.set_verbosity(_snake_case )
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# 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}' )
logger.info(F'Training/evaluation parameters {training_args}' )
# Detecting last checkpoint.
UpperCamelCase__ = None
if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
UpperCamelCase__ = 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 and training_args.resume_from_checkpoint is 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." )
# Set seed before initializing model.
set_seed(training_args.seed )
# Initialize our dataset and prepare it for the 'image-classification' task.
if data_args.dataset_name is not None:
UpperCamelCase__ = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir , task="image-classification" , use_auth_token=True if model_args.use_auth_token else None , )
else:
UpperCamelCase__ = {}
if data_args.train_dir is not None:
UpperCamelCase__ = os.path.join(data_args.train_dir , "**" )
if data_args.validation_dir is not None:
UpperCamelCase__ = os.path.join(data_args.validation_dir , "**" )
UpperCamelCase__ = load_dataset(
"imagefolder" , data_files=_snake_case , cache_dir=model_args.cache_dir , task="image-classification" , )
# If we don't have a validation split, split off a percentage of train as validation.
UpperCamelCase__ = None if "validation" in dataset.keys() else data_args.train_val_split
if isinstance(data_args.train_val_split , _snake_case ) and data_args.train_val_split > 0.0:
UpperCamelCase__ = dataset["train"].train_test_split(data_args.train_val_split )
UpperCamelCase__ = split["train"]
UpperCamelCase__ = split["test"]
# Prepare label mappings.
# We'll include these in the model's config to get human readable labels in the Inference API.
UpperCamelCase__ = dataset["train"].features["labels"].names
UpperCamelCase__ , UpperCamelCase__ = {}, {}
for i, label in enumerate(_snake_case ):
UpperCamelCase__ = str(_snake_case )
UpperCamelCase__ = label
# Load the accuracy metric from the datasets package
UpperCamelCase__ = evaluate.load("accuracy" )
# Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
# predictions and label_ids field) and has to return a dictionary string to float.
def compute_metrics(_snake_case : Optional[int] ):
return metric.compute(predictions=np.argmax(p.predictions , axis=1 ) , references=p.label_ids )
UpperCamelCase__ = AutoConfig.from_pretrained(
model_args.config_name or model_args.model_name_or_path , num_labels=len(_snake_case ) , labelaid=_snake_case , idalabel=_snake_case , finetuning_task="image-classification" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
UpperCamelCase__ = AutoModelForImageClassification.from_pretrained(
model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=_snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , )
UpperCamelCase__ = AutoImageProcessor.from_pretrained(
model_args.image_processor_name or model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
# Define torchvision transforms to be applied to each image.
if "shortest_edge" in image_processor.size:
UpperCamelCase__ = image_processor.size["shortest_edge"]
else:
UpperCamelCase__ = (image_processor.size["height"], image_processor.size["width"])
UpperCamelCase__ = Normalize(mean=image_processor.image_mean , std=image_processor.image_std )
UpperCamelCase__ = Compose(
[
RandomResizedCrop(_snake_case ),
RandomHorizontalFlip(),
ToTensor(),
normalize,
] )
UpperCamelCase__ = Compose(
[
Resize(_snake_case ),
CenterCrop(_snake_case ),
ToTensor(),
normalize,
] )
def train_transforms(_snake_case : Tuple ):
UpperCamelCase__ = [
_train_transforms(pil_img.convert("RGB" ) ) for pil_img in example_batch["image"]
]
return example_batch
def val_transforms(_snake_case : List[Any] ):
UpperCamelCase__ = [_val_transforms(pil_img.convert("RGB" ) ) for pil_img in example_batch["image"]]
return example_batch
if training_args.do_train:
if "train" not in dataset:
raise ValueError("--do_train requires a train dataset" )
if data_args.max_train_samples is not None:
UpperCamelCase__ = (
dataset["train"].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) )
)
# Set the training transforms
dataset["train"].set_transform(_snake_case )
if training_args.do_eval:
if "validation" not in dataset:
raise ValueError("--do_eval requires a validation dataset" )
if data_args.max_eval_samples is not None:
UpperCamelCase__ = (
dataset["validation"].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) )
)
# Set the validation transforms
dataset["validation"].set_transform(_snake_case )
# Initalize our trainer
UpperCamelCase__ = Trainer(
model=_snake_case , args=_snake_case , train_dataset=dataset["train"] if training_args.do_train else None , eval_dataset=dataset["validation"] if training_args.do_eval else None , compute_metrics=_snake_case , tokenizer=_snake_case , data_collator=_snake_case , )
# Training
if training_args.do_train:
UpperCamelCase__ = None
if training_args.resume_from_checkpoint is not None:
UpperCamelCase__ = training_args.resume_from_checkpoint
elif last_checkpoint is not None:
UpperCamelCase__ = last_checkpoint
UpperCamelCase__ = trainer.train(resume_from_checkpoint=_snake_case )
trainer.save_model()
trainer.log_metrics("train" , train_result.metrics )
trainer.save_metrics("train" , train_result.metrics )
trainer.save_state()
# Evaluation
if training_args.do_eval:
UpperCamelCase__ = trainer.evaluate()
trainer.log_metrics("eval" , _snake_case )
trainer.save_metrics("eval" , _snake_case )
# Write model card and (optionally) push to hub
UpperCamelCase__ = {
"finetuned_from": model_args.model_name_or_path,
"tasks": "image-classification",
"dataset": data_args.dataset_name,
"tags": ["image-classification", "vision"],
}
if training_args.push_to_hub:
trainer.push_to_hub(**_snake_case )
else:
trainer.create_model_card(**_snake_case )
if __name__ == "__main__":
main() | 516 | """simple docstring"""
class lowerCAmelCase :
'''simple docstring'''
def __init__( self :str ) -> Optional[int]:
"""simple docstring"""
UpperCamelCase__ = {}
def lowerCamelCase__ ( self :Optional[int] ) -> None:
"""simple docstring"""
print(self.vertex )
for i in self.vertex:
print(lowerCamelCase_ , " -> " , " -> ".join([str(lowerCamelCase_ ) for j in self.vertex[i]] ) )
def lowerCamelCase__ ( self :List[Any] , lowerCamelCase_ :int , lowerCamelCase_ :int ) -> None:
"""simple docstring"""
if from_vertex in self.vertex:
self.vertex[from_vertex].append(lowerCamelCase_ )
else:
# else make a new vertex
UpperCamelCase__ = [to_vertex]
def lowerCamelCase__ ( self :Optional[int] ) -> None:
"""simple docstring"""
UpperCamelCase__ = [False] * len(self.vertex )
# call the recursive helper function
for i in range(len(self.vertex ) ):
if not visited[i]:
self.dfs_recursive(lowerCamelCase_ , lowerCamelCase_ )
def lowerCamelCase__ ( self :Union[str, Any] , lowerCamelCase_ :int , lowerCamelCase_ :list ) -> None:
"""simple docstring"""
UpperCamelCase__ = True
print(lowerCamelCase_ , end=" " )
# Recur for all the vertices that are adjacent to this node
for i in self.vertex:
if not visited[i]:
self.dfs_recursive(lowerCamelCase_ , lowerCamelCase_ )
if __name__ == "__main__":
A : Optional[int] = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)
g.print_graph()
print('DFS:')
g.dfs()
# OUTPUT:
# 0 -> 1 -> 2
# 1 -> 2
# 2 -> 0 -> 3
# 3 -> 3
# DFS:
# 0 1 2 3 | 516 | 1 |
from typing import Optional
from .. import Features, NamedSplit
from ..packaged_modules.text.text import Text
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
class snake_case_ ( __lowerCAmelCase ):
'''simple docstring'''
def __init__( self : Dict , __magic_name__ : NestedDataStructureLike[PathLike] , __magic_name__ : Optional[NamedSplit] = None , __magic_name__ : Optional[Features] = None , __magic_name__ : str = None , __magic_name__ : bool = False , __magic_name__ : bool = False , __magic_name__ : Optional[int] = None , **__magic_name__ : Tuple , ) -> Union[str, Any]:
super().__init__(
_UpperCamelCase , split=_UpperCamelCase , features=_UpperCamelCase , cache_dir=_UpperCamelCase , keep_in_memory=_UpperCamelCase , streaming=_UpperCamelCase , num_proc=_UpperCamelCase , **_UpperCamelCase , )
lowerCamelCase_ : List[Any] = path_or_paths if isinstance(_UpperCamelCase , _UpperCamelCase ) else {self.split: path_or_paths}
lowerCamelCase_ : Any = Text(
cache_dir=_UpperCamelCase , data_files=_UpperCamelCase , features=_UpperCamelCase , **_UpperCamelCase , )
def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]:
if self.streaming:
lowerCamelCase_ : Tuple = self.builder.as_streaming_dataset(split=self.split )
# Build regular (map-style) dataset
else:
lowerCamelCase_ : List[Any] = None
lowerCamelCase_ : Any = None
lowerCamelCase_ : List[str] = None
lowerCamelCase_ : Dict = None
self.builder.download_and_prepare(
download_config=_UpperCamelCase , download_mode=_UpperCamelCase , verification_mode=_UpperCamelCase , base_path=_UpperCamelCase , num_proc=self.num_proc , )
lowerCamelCase_ : Optional[int] = self.builder.as_dataset(
split=self.split , verification_mode=_UpperCamelCase , in_memory=self.keep_in_memory )
return dataset
| 715 |
def __a ( __UpperCAmelCase : str ) -> bool:
"""simple docstring"""
return credit_card_number.startswith(("34", "35", "37", "4", "5", "6") )
def __a ( __UpperCAmelCase : str ) -> bool:
"""simple docstring"""
lowerCamelCase_ : str = credit_card_number
lowerCamelCase_ : int = 0
lowerCamelCase_ : str = len(__UpperCAmelCase ) - 2
for i in range(__UpperCAmelCase , -1 , -2 ):
# double the value of every second digit
lowerCamelCase_ : Dict = int(cc_number[i] )
digit *= 2
# If doubling of a number results in a two digit number
# i.e greater than 9(e.g., 6 × 2 = 12),
# then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6),
# to get a single digit number.
if digit > 9:
digit %= 10
digit += 1
lowerCamelCase_ : List[str] = cc_number[:i] + str(__UpperCAmelCase ) + cc_number[i + 1 :]
total += digit
# Sum up the remaining digits
for i in range(len(__UpperCAmelCase ) - 1 , -1 , -2 ):
total += int(cc_number[i] )
return total % 10 == 0
def __a ( __UpperCAmelCase : str ) -> bool:
"""simple docstring"""
lowerCamelCase_ : Union[str, Any] = f"{credit_card_number} is an invalid credit card number because"
if not credit_card_number.isdigit():
print(f"{error_message} it has nonnumerical characters." )
return False
if not 13 <= len(__UpperCAmelCase ) <= 16:
print(f"{error_message} of its length." )
return False
if not validate_initial_digits(__UpperCAmelCase ):
print(f"{error_message} of its first two digits." )
return False
if not luhn_validation(__UpperCAmelCase ):
print(f"{error_message} it fails the Luhn check." )
return False
print(f"{credit_card_number} is a valid credit card number." )
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
validate_credit_card_number("4111111111111111")
validate_credit_card_number("32323")
| 253 | 0 |
def __snake_case ( lowerCAmelCase_ ) -> bool:
if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ):
raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' )
if len(lowerCAmelCase_ ) == 0:
raise ValueError('''Input list must be a non empty list''' )
if len(lowerCAmelCase_ ) == 1:
return True
SCREAMING_SNAKE_CASE__ = series[1] - series[0]
for index in range(len(lowerCAmelCase_ ) - 1 ):
if series[index + 1] - series[index] != common_diff:
return False
return True
def __snake_case ( lowerCAmelCase_ ) -> float:
if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ):
raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' )
if len(lowerCAmelCase_ ) == 0:
raise ValueError('''Input list must be a non empty list''' )
SCREAMING_SNAKE_CASE__ = 0
for val in series:
answer += val
return answer / len(lowerCAmelCase_ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 100 |
import argparse
import os
from pathlib import Path
import torch
from bark.generation import _load_model as _bark_load_model
from huggingface_hub import hf_hub_download
from transformers import EncodecConfig, EncodecModel, set_seed
from transformers.models.bark.configuration_bark import (
BarkCoarseConfig,
BarkConfig,
BarkFineConfig,
BarkSemanticConfig,
)
from transformers.models.bark.generation_configuration_bark import (
BarkCoarseGenerationConfig,
BarkFineGenerationConfig,
BarkGenerationConfig,
BarkSemanticGenerationConfig,
)
from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel
from transformers.utils import logging
logging.set_verbosity_info()
SCREAMING_SNAKE_CASE_ : Dict = logging.get_logger(__name__)
set_seed(770)
SCREAMING_SNAKE_CASE_ : List[Any] = {
'''c_attn''': '''att_proj''',
'''c_proj''': '''out_proj''',
'''c_fc''': '''in_proj''',
'''transformer.''': '''''',
'''h.''': '''layers.''',
'''ln_1''': '''layernorm_1''',
'''ln_2''': '''layernorm_2''',
'''ln_f''': '''layernorm_final''',
'''wpe''': '''position_embeds_layer''',
'''wte''': '''input_embeds_layer''',
}
SCREAMING_SNAKE_CASE_ : Optional[Any] = {
'''text_small''': {
'''repo_id''': '''suno/bark''',
'''file_name''': '''text.pt''',
},
'''coarse_small''': {
'''repo_id''': '''suno/bark''',
'''file_name''': '''coarse.pt''',
},
'''fine_small''': {
'''repo_id''': '''suno/bark''',
'''file_name''': '''fine.pt''',
},
'''text''': {
'''repo_id''': '''suno/bark''',
'''file_name''': '''text_2.pt''',
},
'''coarse''': {
'''repo_id''': '''suno/bark''',
'''file_name''': '''coarse_2.pt''',
},
'''fine''': {
'''repo_id''': '''suno/bark''',
'''file_name''': '''fine_2.pt''',
},
}
SCREAMING_SNAKE_CASE_ : List[str] = os.path.dirname(os.path.abspath(__file__))
SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join(os.path.expanduser('''~'''), '''.cache''')
SCREAMING_SNAKE_CASE_ : Any = os.path.join(os.getenv('''XDG_CACHE_HOME''', default_cache_dir), '''suno''', '''bark_v0''')
def SCREAMING_SNAKE_CASE ( snake_case , snake_case=False ) -> Union[str, Any]:
__lowercase = model_type
if use_small:
key += "_small"
return os.path.join(snake_case , REMOTE_MODEL_PATHS[key]['file_name'] )
def SCREAMING_SNAKE_CASE ( snake_case , snake_case ) -> List[str]:
os.makedirs(snake_case , exist_ok=snake_case )
hf_hub_download(repo_id=snake_case , filename=snake_case , local_dir=snake_case )
def SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case=False , snake_case="text" ) -> List[Any]:
if model_type == "text":
__lowercase = BarkSemanticModel
__lowercase = BarkSemanticConfig
__lowercase = BarkSemanticGenerationConfig
elif model_type == "coarse":
__lowercase = BarkCoarseModel
__lowercase = BarkCoarseConfig
__lowercase = BarkCoarseGenerationConfig
elif model_type == "fine":
__lowercase = BarkFineModel
__lowercase = BarkFineConfig
__lowercase = BarkFineGenerationConfig
else:
raise NotImplementedError()
__lowercase = F"{model_type}_small" if use_small else model_type
__lowercase = REMOTE_MODEL_PATHS[model_key]
if not os.path.exists(snake_case ):
logger.info(F"{model_type} model not found, downloading into `{CACHE_DIR}`." )
_download(model_info['repo_id'] , model_info['file_name'] )
__lowercase = torch.load(snake_case , map_location=snake_case )
# this is a hack
__lowercase = checkpoint['model_args']
if "input_vocab_size" not in model_args:
__lowercase = model_args['vocab_size']
__lowercase = model_args['vocab_size']
del model_args["vocab_size"]
# convert Bark model arguments to HF Bark model arguments
__lowercase = model_args.pop('n_head' )
__lowercase = model_args.pop('n_embd' )
__lowercase = model_args.pop('n_layer' )
__lowercase = ConfigClass(**checkpoint['model_args'] )
__lowercase = ModelClass(config=snake_case )
__lowercase = GenerationConfigClass()
__lowercase = model_generation_config
__lowercase = checkpoint['model']
# fixup checkpoint
__lowercase = '_orig_mod.'
for k, v in list(state_dict.items() ):
if k.startswith(snake_case ):
# replace part of the key with corresponding layer name in HF implementation
__lowercase = k[len(snake_case ) :]
for old_layer_name in new_layer_name_dict:
__lowercase = new_k.replace(snake_case , new_layer_name_dict[old_layer_name] )
__lowercase = state_dict.pop(snake_case )
__lowercase = set(state_dict.keys() ) - set(model.state_dict().keys() )
__lowercase = {k for k in extra_keys if not k.endswith('.attn.bias' )}
__lowercase = set(model.state_dict().keys() ) - set(state_dict.keys() )
__lowercase = {k for k in missing_keys if not k.endswith('.attn.bias' )}
if len(snake_case ) != 0:
raise ValueError(F"extra keys found: {extra_keys}" )
if len(snake_case ) != 0:
raise ValueError(F"missing keys: {missing_keys}" )
model.load_state_dict(snake_case , strict=snake_case )
__lowercase = model.num_parameters(exclude_embeddings=snake_case )
__lowercase = checkpoint['best_val_loss'].item()
logger.info(F"model loaded: {round(n_params/1E6 , 1 )}M params, {round(snake_case , 3 )} loss" )
model.eval()
model.to(snake_case )
del checkpoint, state_dict
return model
def SCREAMING_SNAKE_CASE ( snake_case , snake_case=False , snake_case="text" ) -> Tuple:
if model_type not in ("text", "coarse", "fine"):
raise NotImplementedError()
__lowercase = 'cpu' # do conversion on cpu
__lowercase = _get_ckpt_path(snake_case , use_small=snake_case )
__lowercase = _load_model(snake_case , snake_case , model_type=snake_case , use_small=snake_case )
# load bark initial model
__lowercase = _bark_load_model(snake_case , 'cpu' , model_type=snake_case , use_small=snake_case )
if model_type == "text":
__lowercase = bark_model['model']
if model.num_parameters(exclude_embeddings=snake_case ) != bark_model.get_num_params():
raise ValueError('initial and new models don\'t have the same number of parameters' )
# check if same output as the bark model
__lowercase = 5
__lowercase = 10
if model_type in ["text", "coarse"]:
__lowercase = torch.randint(256 , (batch_size, sequence_length) , dtype=torch.int )
__lowercase = bark_model(snake_case )[0]
__lowercase = model(snake_case )
# take last logits
__lowercase = output_new_model_total.logits[:, [-1], :]
else:
__lowercase = 3
__lowercase = 8
__lowercase = torch.randint(256 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int )
__lowercase = model(snake_case , snake_case )
__lowercase = bark_model(snake_case , snake_case )
__lowercase = output_new_model_total.logits
# output difference should come from the difference of self-attention implementation design
if output_new_model.shape != output_old_model.shape:
raise ValueError('initial and new outputs don\'t have the same shape' )
if (output_new_model - output_old_model).abs().max().item() > 1E-3:
raise ValueError('initial and new outputs are not equal' )
Path(snake_case ).mkdir(exist_ok=snake_case )
model.save_pretrained(snake_case )
def SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ) -> List[str]:
__lowercase = os.path.join(snake_case , snake_case )
__lowercase = BarkSemanticConfig.from_pretrained(os.path.join(snake_case , 'config.json' ) )
__lowercase = BarkCoarseConfig.from_pretrained(os.path.join(snake_case , 'config.json' ) )
__lowercase = BarkFineConfig.from_pretrained(os.path.join(snake_case , 'config.json' ) )
__lowercase = EncodecConfig.from_pretrained('facebook/encodec_24khz' )
__lowercase = BarkSemanticModel.from_pretrained(snake_case )
__lowercase = BarkCoarseModel.from_pretrained(snake_case )
__lowercase = BarkFineModel.from_pretrained(snake_case )
__lowercase = EncodecModel.from_pretrained('facebook/encodec_24khz' )
__lowercase = BarkConfig.from_sub_model_configs(
snake_case , snake_case , snake_case , snake_case )
__lowercase = BarkGenerationConfig.from_sub_model_configs(
semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config )
__lowercase = BarkModel(snake_case )
__lowercase = semantic
__lowercase = coarseAcoustic
__lowercase = fineAcoustic
__lowercase = codec
__lowercase = bark_generation_config
Path(snake_case ).mkdir(exist_ok=snake_case )
bark.save_pretrained(snake_case , repo_id=snake_case , push_to_hub=snake_case )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE_ : Optional[int] = argparse.ArgumentParser()
# Required parameters
parser.add_argument('''model_type''', type=str, help='''text, coarse or fine.''')
parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument('''--is_small''', action='''store_true''', help='''convert the small version instead of the large.''')
SCREAMING_SNAKE_CASE_ : Optional[int] = parser.parse_args()
load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
| 375 | 0 |
"""simple docstring"""
from __future__ import annotations
from math import ceil, floor, sqrt
def _SCREAMING_SNAKE_CASE (__lowerCAmelCase = 2_00_00_00 ) -> int:
'''simple docstring'''
lowercase_ = [0]
lowercase_ = 42
for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ):
triangle_numbers.append(triangle_numbers[-1] + idx )
# we want this to be as close as possible to target
lowercase_ = 0
# the area corresponding to the grid that gives the product closest to target
lowercase_ = 0
# an estimate of b, using the quadratic formula
lowercase_ = 42
# the largest integer less than b_estimate
lowercase_ = 42
# the largest integer less than b_estimate
lowercase_ = 42
# the triangle number corresponding to b_floor
lowercase_ = 42
# the triangle number corresponding to b_ceil
lowercase_ = 42
for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ):
lowercase_ = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2
lowercase_ = floor(__lowerCAmelCase )
lowercase_ = ceil(__lowerCAmelCase )
lowercase_ = triangle_numbers[b_floor]
lowercase_ = triangle_numbers[b_ceil]
if abs(target - triangle_b_first_guess * triangle_a ) < abs(
target - best_product ):
lowercase_ = triangle_b_first_guess * triangle_a
lowercase_ = idx_a * b_floor
if abs(target - triangle_b_second_guess * triangle_a ) < abs(
target - best_product ):
lowercase_ = triangle_b_second_guess * triangle_a
lowercase_ = idx_a * b_ceil
return area
if __name__ == "__main__":
print(F"{solution() = }")
| 100 |
"""simple docstring"""
def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> int:
'''simple docstring'''
while a != 0:
lowercase_ , lowercase_ = b % a, a
return b
def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> int:
'''simple docstring'''
if gcd(__lowerCAmelCase , __lowerCAmelCase ) != 1:
lowercase_ = F'''mod inverse of {a!r} and {m!r} does not exist'''
raise ValueError(__lowerCAmelCase )
lowercase_ , lowercase_ , lowercase_ = 1, 0, a
lowercase_ , lowercase_ , lowercase_ = 0, 1, m
while va != 0:
lowercase_ = ua // va
lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va
return ua % m
| 100 | 1 |
'''simple docstring'''
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
from ...utils import logging
UpperCamelCase_ = logging.get_logger(__name__)
UpperCamelCase_ = "▁"
UpperCamelCase_ = {"vocab_file": "sentencepiece.bpe.model"}
UpperCamelCase_ = {
"vocab_file": {
"facebook/mbart-large-en-ro": (
"https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model"
),
"facebook/mbart-large-cc25": (
"https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model"
),
}
}
UpperCamelCase_ = {
"facebook/mbart-large-en-ro": 1_0_2_4,
"facebook/mbart-large-cc25": 1_0_2_4,
}
# fmt: off
UpperCamelCase_ = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"]
class _a ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
A : List[str] = VOCAB_FILES_NAMES
A : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
A : List[str] = PRETRAINED_VOCAB_FILES_MAP
A : Dict = ['''input_ids''', '''attention_mask''']
A : List[int] = []
A : List[int] = []
def __init__( self, A, A="<s>", A="</s>", A="</s>", A="<s>", A="<unk>", A="<pad>", A="<mask>", A=None, A=None, A=None, A = None, A=None, **A, ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Union[str, Any] = AddedToken(A, lstrip=A, rstrip=A ) if isinstance(A, A ) else mask_token
SCREAMING_SNAKE_CASE : Tuple = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=A, eos_token=A, unk_token=A, sep_token=A, cls_token=A, pad_token=A, mask_token=A, tokenizer_file=A, src_lang=A, tgt_lang=A, additional_special_tokens=A, sp_model_kwargs=self.sp_model_kwargs, **A, )
SCREAMING_SNAKE_CASE : int = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(A ) )
SCREAMING_SNAKE_CASE : str = 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'
# Mimic fairseq token-to-id alignment for the first 4 token
SCREAMING_SNAKE_CASE : str = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3}
# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
SCREAMING_SNAKE_CASE : Optional[Any] = 1
SCREAMING_SNAKE_CASE : Dict = len(self.sp_model )
SCREAMING_SNAKE_CASE : Optional[Any] = {
code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(A )
}
SCREAMING_SNAKE_CASE : Optional[Any] = {v: k for k, v in self.lang_code_to_id.items()}
SCREAMING_SNAKE_CASE : int = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset
self.fairseq_tokens_to_ids.update(self.lang_code_to_id )
SCREAMING_SNAKE_CASE : str = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
SCREAMING_SNAKE_CASE : Tuple = list(self.lang_code_to_id.keys() )
if additional_special_tokens is not None:
# Only add those special tokens if they are not already there.
self._additional_special_tokens.extend(
[t for t in additional_special_tokens if t not in self._additional_special_tokens] )
SCREAMING_SNAKE_CASE : Dict = src_lang if src_lang is not None else 'en_XX'
SCREAMING_SNAKE_CASE : Tuple = self.lang_code_to_id[self._src_lang]
SCREAMING_SNAKE_CASE : Tuple = tgt_lang
self.set_src_lang_special_tokens(self._src_lang )
def __getstate__( self ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : List[Any] = self.__dict__.copy()
SCREAMING_SNAKE_CASE : str = None
SCREAMING_SNAKE_CASE : str = self.sp_model.serialized_model_proto()
return state
def __setstate__( self, A ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : int = d
# for backward compatibility
if not hasattr(self, 'sp_model_kwargs' ):
SCREAMING_SNAKE_CASE : Tuple = {}
SCREAMING_SNAKE_CASE : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.LoadFromSerializedProto(self.sp_model_proto )
@property
def UpperCamelCase_ ( self ):
'''simple docstring'''
return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token
@property
def UpperCamelCase_ ( self ):
'''simple docstring'''
return self._src_lang
@src_lang.setter
def UpperCamelCase_ ( self, A ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[int] = new_src_lang
self.set_src_lang_special_tokens(self._src_lang )
def UpperCamelCase_ ( self, A, A = None, A = False ):
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=A, token_ids_a=A, already_has_special_tokens=A )
SCREAMING_SNAKE_CASE : Union[str, Any] = [1] * len(self.prefix_tokens )
SCREAMING_SNAKE_CASE : int = [1] * len(self.suffix_tokens )
if token_ids_a is None:
return prefix_ones + ([0] * len(A )) + suffix_ones
return prefix_ones + ([0] * len(A )) + ([0] * len(A )) + suffix_ones
def UpperCamelCase_ ( self, A, A = None ):
'''simple docstring'''
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + self.suffix_tokens
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
def UpperCamelCase_ ( self, A, A = None ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Union[str, Any] = [self.sep_token_id]
SCREAMING_SNAKE_CASE : Tuple = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def UpperCamelCase_ ( self, A, A, A, A, **A ):
'''simple docstring'''
if src_lang is None or tgt_lang is None:
raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model' )
SCREAMING_SNAKE_CASE : int = src_lang
SCREAMING_SNAKE_CASE : List[str] = self(A, add_special_tokens=A, return_tensors=A, **A )
SCREAMING_SNAKE_CASE : Any = self.convert_tokens_to_ids(A )
SCREAMING_SNAKE_CASE : int = tgt_lang_id
return inputs
def UpperCamelCase_ ( self ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[Any] = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def UpperCamelCase_ ( self, A ):
'''simple docstring'''
return self.sp_model.encode(A, out_type=A )
def UpperCamelCase_ ( self, A ):
'''simple docstring'''
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.PieceToId(A )
# 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 UpperCamelCase_ ( self, A ):
'''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 UpperCamelCase_ ( self, A ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : str = ''.join(A ).replace(A, ' ' ).strip()
return out_string
def UpperCamelCase_ ( self, A, A = None ):
'''simple docstring'''
if not os.path.isdir(A ):
logger.error(F"Vocabulary path ({save_directory}) should be a directory" )
return
SCREAMING_SNAKE_CASE : Dict = os.path.join(
A, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file, A )
elif not os.path.isfile(self.vocab_file ):
with open(A, 'wb' ) as fi:
SCREAMING_SNAKE_CASE : Tuple = self.sp_model.serialized_model_proto()
fi.write(A )
return (out_vocab_file,)
def UpperCamelCase_ ( self, A, A = "en_XX", A = None, A = "ro_RO", **A, ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[Any] = src_lang
SCREAMING_SNAKE_CASE : Optional[int] = tgt_lang
return super().prepare_seqaseq_batch(A, A, **A )
def UpperCamelCase_ ( self ):
'''simple docstring'''
return self.set_src_lang_special_tokens(self.src_lang )
def UpperCamelCase_ ( self ):
'''simple docstring'''
return self.set_tgt_lang_special_tokens(self.tgt_lang )
def UpperCamelCase_ ( self, A ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Dict = self.lang_code_to_id[src_lang]
SCREAMING_SNAKE_CASE : int = []
SCREAMING_SNAKE_CASE : int = [self.eos_token_id, self.cur_lang_code]
def UpperCamelCase_ ( self, A ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : int = self.lang_code_to_id[lang]
SCREAMING_SNAKE_CASE : Optional[Any] = []
SCREAMING_SNAKE_CASE : Dict = [self.eos_token_id, self.cur_lang_code]
| 28 |
'''simple docstring'''
import os
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
from torch import nn
from ...models.controlnet import ControlNetModel, ControlNetOutput
from ...models.modeling_utils import ModelMixin
from ...utils import logging
UpperCamelCase_ = logging.get_logger(__name__)
class _a ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__( self, A ):
'''simple docstring'''
super().__init__()
SCREAMING_SNAKE_CASE : Dict = nn.ModuleList(A )
def UpperCamelCase_ ( self, A, A, A, A, A, A = None, A = None, A = None, A = None, A = False, A = True, ):
'''simple docstring'''
for i, (image, scale, controlnet) in enumerate(zip(A, A, self.nets ) ):
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = controlnet(
A, A, A, A, A, A, A, A, A, A, A, )
# merge samples
if i == 0:
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = down_samples, mid_sample
else:
SCREAMING_SNAKE_CASE : str = [
samples_prev + samples_curr
for samples_prev, samples_curr in zip(A, A )
]
mid_block_res_sample += mid_sample
return down_block_res_samples, mid_block_res_sample
def UpperCamelCase_ ( self, A, A = True, A = None, A = False, A = None, ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : List[Any] = 0
SCREAMING_SNAKE_CASE : Optional[int] = save_directory
for controlnet in self.nets:
controlnet.save_pretrained(
A, is_main_process=A, save_function=A, safe_serialization=A, variant=A, )
idx += 1
SCREAMING_SNAKE_CASE : List[Any] = model_path_to_save + F"_{idx}"
@classmethod
def UpperCamelCase_ ( cls, A, **A ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Dict = 0
SCREAMING_SNAKE_CASE : List[Any] = []
# load controlnet and append to list until no controlnet directory exists anymore
# first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained`
# second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ...
SCREAMING_SNAKE_CASE : Optional[Any] = pretrained_model_path
while os.path.isdir(A ):
SCREAMING_SNAKE_CASE : Optional[int] = ControlNetModel.from_pretrained(A, **A )
controlnets.append(A )
idx += 1
SCREAMING_SNAKE_CASE : Union[str, Any] = pretrained_model_path + F"_{idx}"
logger.info(F"{len(A )} controlnets loaded from {pretrained_model_path}." )
if len(A ) == 0:
raise ValueError(
F"No ControlNets found under {os.path.dirname(A )}. Expected at least {pretrained_model_path + '_0'}." )
return cls(A )
| 28 | 1 |
'''simple docstring'''
def snake_case__ ( a = 1000 ) -> int:
'''simple docstring'''
return sum(e for e in range(3 , a ) if e % 3 == 0 or e % 5 == 0 )
if __name__ == "__main__":
print(F"{solution() = }") | 707 |
'''simple docstring'''
from typing import List, Optional, Union
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class __magic_name__( __lowerCAmelCase ):
UpperCAmelCase_ : int = ["""image_processor""", """tokenizer"""]
UpperCAmelCase_ : Optional[Any] = """BlipImageProcessor"""
UpperCAmelCase_ : int = """AutoTokenizer"""
def __init__( self : List[str] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : List[Any] ):
'''simple docstring'''
snake_case__ = False
super().__init__(__UpperCamelCase , __UpperCamelCase )
snake_case__ = self.image_processor
def __call__( self : Any , __UpperCamelCase : ImageInput = None , __UpperCamelCase : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __UpperCamelCase : bool = True , __UpperCamelCase : Union[bool, str, PaddingStrategy] = False , __UpperCamelCase : Union[bool, str, TruncationStrategy] = None , __UpperCamelCase : Optional[int] = None , __UpperCamelCase : int = 0 , __UpperCamelCase : Optional[int] = None , __UpperCamelCase : Optional[bool] = None , __UpperCamelCase : bool = False , __UpperCamelCase : bool = False , __UpperCamelCase : bool = False , __UpperCamelCase : bool = False , __UpperCamelCase : bool = False , __UpperCamelCase : bool = True , __UpperCamelCase : Optional[Union[str, TensorType]] = None , **__UpperCamelCase : List[str] , ):
'''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:
snake_case__ = self.tokenizer
snake_case__ = self.tokenizer(
text=__UpperCamelCase , add_special_tokens=__UpperCamelCase , padding=__UpperCamelCase , truncation=__UpperCamelCase , max_length=__UpperCamelCase , stride=__UpperCamelCase , pad_to_multiple_of=__UpperCamelCase , return_attention_mask=__UpperCamelCase , return_overflowing_tokens=__UpperCamelCase , return_special_tokens_mask=__UpperCamelCase , return_offsets_mapping=__UpperCamelCase , return_token_type_ids=__UpperCamelCase , return_length=__UpperCamelCase , verbose=__UpperCamelCase , return_tensors=__UpperCamelCase , **__UpperCamelCase , )
return text_encoding
# add pixel_values
snake_case__ = self.image_processor(__UpperCamelCase , return_tensors=__UpperCamelCase )
if text is not None:
snake_case__ = self.tokenizer(
text=__UpperCamelCase , add_special_tokens=__UpperCamelCase , padding=__UpperCamelCase , truncation=__UpperCamelCase , max_length=__UpperCamelCase , stride=__UpperCamelCase , pad_to_multiple_of=__UpperCamelCase , return_attention_mask=__UpperCamelCase , return_overflowing_tokens=__UpperCamelCase , return_special_tokens_mask=__UpperCamelCase , return_offsets_mapping=__UpperCamelCase , return_token_type_ids=__UpperCamelCase , return_length=__UpperCamelCase , verbose=__UpperCamelCase , return_tensors=__UpperCamelCase , **__UpperCamelCase , )
else:
snake_case__ = None
if text_encoding is not None:
encoding_image_processor.update(__UpperCamelCase )
return encoding_image_processor
def __lowerCAmelCase( self : Any , *__UpperCamelCase : Union[str, Any] , **__UpperCamelCase : Optional[int] ):
'''simple docstring'''
return self.tokenizer.batch_decode(*__UpperCamelCase , **__UpperCamelCase )
def __lowerCAmelCase( self : Optional[int] , *__UpperCamelCase : int , **__UpperCamelCase : str ):
'''simple docstring'''
return self.tokenizer.decode(*__UpperCamelCase , **__UpperCamelCase )
@property
# Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
def __lowerCAmelCase( self : List[str] ):
'''simple docstring'''
snake_case__ = self.tokenizer.model_input_names
snake_case__ = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) | 566 | 0 |
'''simple docstring'''
# HF Trainer benchmarking tool
#
# This tool can be used to run and compare multiple dimensions of the HF Trainers args.
#
# It then prints a report once in github format with all the information that needs to be shared
# with others and second time in a console-friendly format, so it's easier to use for tuning things up.
#
# The main idea is:
#
# ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \
# --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \
# --target-metric-key train_samples_per_second
#
# The variations can be any command line argument that you want to compare and not just dtype as in
# the example.
#
# --variations allows you to compare variations in multiple dimensions.
#
# as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6
# times adding one of:
#
# 1. --tf32 0 --fp16 0
# 2. --tf32 0 --fp16 1
# 3. --tf32 0 --bf16 1
# 4. --tf32 1 --fp16 0
# 5. --tf32 1 --fp16 1
# 6. --tf32 1 --bf16 1
#
# and print the results. This is just a cartesian product - and more than 2 dimensions can be used.
#
# If you want to rely on defaults, this:
# --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1'
# is identical to this:
# --variations '--tf32 0|--tf32 1' '|--fp16|--bf16'
#
# the leading empty variation in the 2nd dimension is a valid variation.
#
# So here we get the following 6 variations:
#
# 1. --tf32 0
# 2. --tf32 0 --fp16
# 3. --tf32 0 --bf16
# 4. --tf32 1
# 5. --tf32 1 --fp16
# 6. --tf32 1 --bf16
#
# In this particular case we don't know what the default tf32 setting is as it's normally
# pytorch-version dependent). That's why it's best to do an explicit setting of each variation:
# `--tf32 0|--tf32 1`
#
# Here is a full example of a train:
#
# CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \
# --base-cmd \
# ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \
# --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \
# --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \
# --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \
# --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \
# --source_prefix "translate English to Romanian: " --warmup_steps 50 \
# --max_train_samples 20000 --dataloader_num_workers 2 ' \
# --target-metric-key train_samples_per_second --repeat-times 1 --variations \
# '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \
# --repeat-times 1 --base-variation '--tf32 0'
#
# and here is a possible output:
#
#
# | Variation | Train | Diff | Train |
# | | samples | % | loss |
# | | per | | |
# | | second | | |
# |:----------------|----------:|-------:|--------:|
# | --tf32 0 | 285.11 | 0 | 2.51 |
# | --tf32 1 | 342.09 | 20 | 2.51 |
# | --fp16 --tf32 0 | 423.49 | 49 | 2.51 |
# | --fp16 --tf32 1 | 423.13 | 48 | 2.51 |
# | --bf16 --tf32 0 | 416.80 | 46 | 2.52 |
# | --bf16 --tf32 1 | 415.87 | 46 | 2.52 |
#
#
# So you can quickly compare the different outcomes.
#
# Typically running each experiment once is enough, but if the environment is unstable you can
# re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results.
#
# By default it'll use the lowest result as the base line to use as 100% and then compare the rest to
# it as can be seen from the table above, but you can also specify which combination is the one to use as
# the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0'
#
# --target-metric-key is there to tell the program which metrics to compare - the different metric keys are
# inside output_dir/all_results.json. e.g., to measure eval performance instead of train use:
# --target-metric-key eval_samples_per_second
# but of course you will need to adjust the --base-cmd value in the example to perform evaluation as
# well (as currently it doesn't)
#
import argparse
import datetime
import io
import itertools
import json
import math
import os
import platform
import re
import shlex
import subprocess
import sys
from pathlib import Path
from statistics import fmean
import pandas as pd
import torch
from tqdm import tqdm
import transformers
_snake_case : str = float('nan')
class A :
def __init__( self : Union[str, Any] , lowerCAmelCase_ : Optional[int] ) -> List[Any]:
"""simple docstring"""
_a = sys.stdout
_a = open(lowerCAmelCase_ , '''a''' )
def __getattr__( self : Dict , lowerCAmelCase_ : Union[str, Any] ) -> List[str]:
"""simple docstring"""
return getattr(self.stdout , lowerCAmelCase_ )
def __lowerCAmelCase ( self : List[Any] , lowerCAmelCase_ : Optional[int] ) -> str:
"""simple docstring"""
self.stdout.write(lowerCAmelCase_ )
# strip tqdm codes
self.file.write(re.sub(R'''^.*\r''' , '''''' , lowerCAmelCase_ , 0 , re.M ) )
def snake_case_ (UpperCamelCase : List[str]=80 , UpperCamelCase : int=False ):
'''simple docstring'''
_a = []
# deal with critical env vars
_a = ['''CUDA_VISIBLE_DEVICES''']
for key in env_keys:
_a = os.environ.get(UpperCamelCase , UpperCamelCase )
if val is not None:
cmd.append(f'{key}={val}' )
# python executable (not always needed if the script is executable)
_a = sys.executable if full_python_path else sys.executable.split('''/''' )[-1]
cmd.append(UpperCamelCase )
# now the normal args
cmd += list(map(shlex.quote , sys.argv ) )
# split up into up to MAX_WIDTH lines with shell multi-line escapes
_a = []
_a = ''''''
while len(UpperCamelCase ) > 0:
current_line += f'{cmd.pop(0 )} '
if len(UpperCamelCase ) == 0 or len(UpperCamelCase ) + len(cmd[0] ) + 1 > max_width - 1:
lines.append(UpperCamelCase )
_a = ''''''
return "\\\n".join(UpperCamelCase )
def snake_case_ (UpperCamelCase : List[Any] , UpperCamelCase : List[Any] ):
'''simple docstring'''
_a = re.sub(R'''[\\\n]+''' , ''' ''' , args.base_cmd )
# remove --output_dir if any and set our own
_a = re.sub('''--output_dir\s+[^\s]+''' , '''''' , args.base_cmd )
args.base_cmd += f' --output_dir {output_dir}'
# ensure we have --overwrite_output_dir
_a = re.sub('''--overwrite_output_dir\s+''' , '''''' , args.base_cmd )
args.base_cmd += " --overwrite_output_dir"
return [sys.executable] + shlex.split(args.base_cmd )
def snake_case_ (UpperCamelCase : Optional[Any] , UpperCamelCase : Any , UpperCamelCase : Union[str, Any] , UpperCamelCase : int , UpperCamelCase : Dict , UpperCamelCase : List[str] , UpperCamelCase : Any ):
'''simple docstring'''
if 0:
import random
from time import sleep
sleep(0 )
return dict(
{k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6666, 222.22222222] )} , )
_a = subprocess.run(UpperCamelCase , capture_output=UpperCamelCase , text=UpperCamelCase )
if verbose:
print('''STDOUT''' , result.stdout )
print('''STDERR''' , result.stderr )
# save the streams
_a = variation.replace(''' ''' , '''-''' )
with open(Path(UpperCamelCase ) / f'log.{prefix}.stdout.txt' , '''w''' ) as f:
f.write(result.stdout )
with open(Path(UpperCamelCase ) / f'log.{prefix}.stderr.txt' , '''w''' ) as f:
f.write(result.stderr )
if result.returncode != 0:
if verbose:
print('''failed''' )
return {target_metric_key: nan}
with io.open(f'{output_dir}/all_results.json' , '''r''' , encoding='''utf-8''' ) as f:
_a = json.load(UpperCamelCase )
# filter out just the keys we want
return {k: v for k, v in metrics.items() if k in metric_keys}
def snake_case_ (UpperCamelCase : List[str] , UpperCamelCase : Tuple , UpperCamelCase : Any , UpperCamelCase : str , UpperCamelCase : Dict , UpperCamelCase : Any , UpperCamelCase : str , UpperCamelCase : str , UpperCamelCase : Any , UpperCamelCase : List[str] , ):
'''simple docstring'''
_a = []
_a = []
_a = f'{id}: {variation:<{longest_variation_len}}'
_a = f'{preamble}: '
_a = set(report_metric_keys + [target_metric_key] )
for i in tqdm(range(UpperCamelCase ) , desc=UpperCamelCase , leave=UpperCamelCase ):
_a = process_run_single(
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase )
_a = single_run_metrics[target_metric_key]
if not math.isnan(UpperCamelCase ):
metrics.append(UpperCamelCase )
results.append(UpperCamelCase )
outcome += "✓"
else:
outcome += "✘"
_a = f'\33[2K\r{outcome}'
if len(UpperCamelCase ) > 0:
_a = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()}
_a = round(mean_metrics[target_metric_key] , 2 )
_a = f'{outcome} {mean_target}'
if len(UpperCamelCase ) > 1:
results_str += f' {tuple(round(UpperCamelCase , 2 ) for x in results )}'
print(UpperCamelCase )
_a = variation
return mean_metrics
else:
print(UpperCamelCase )
return {variation_key: variation, target_metric_key: nan}
def snake_case_ ():
'''simple docstring'''
_a = torch.cuda.get_device_properties(torch.device('''cuda''' ) )
return f'\nDatetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch : {torch.__version__}\ncuda : {torch.version.cuda}\npython : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB\n'
def snake_case_ (UpperCamelCase : Optional[Any] , UpperCamelCase : Optional[int] , UpperCamelCase : Dict , UpperCamelCase : Dict , UpperCamelCase : str ):
'''simple docstring'''
_a = pd.DataFrame(UpperCamelCase )
_a = '''variation'''
_a = '''diff_%'''
_a = nan
if base_variation is not None and len(df[df[variation_key] == base_variation] ):
# this may still return nan
_a = df.loc[df[variation_key] == base_variation][target_metric_key].item()
if math.isnan(UpperCamelCase ):
# as a fallback, use the minimal value as the sentinel
_a = df.loc[df[target_metric_key] != nan][target_metric_key].min()
# create diff column if possible
if not math.isnan(UpperCamelCase ):
_a = df.apply(
lambda UpperCamelCase : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value )
if not math.isnan(r[target_metric_key] )
else 0 , axis='''columns''' , )
# re-order columns
_a = [variation_key, target_metric_key, diff_key, *report_metric_keys]
_a = df.reindex(UpperCamelCase , axis='''columns''' ) # reorder cols
# capitalize
_a = df.rename(str.capitalize , axis='''columns''' )
# make the cols as narrow as possible
_a = df.rename(lambda UpperCamelCase : c.replace('''_''' , '''<br>''' ) , axis='''columns''' )
_a = df.rename(lambda UpperCamelCase : c.replace('''_''' , '''\n''' ) , axis='''columns''' )
_a = ['''''', '''Copy between the cut-here-lines and paste as is to github or a forum''']
report += ["----------8<-----------------8<--------"]
report += ["*** Results:", df_github.to_markdown(index=UpperCamelCase , floatfmt='''.2f''' )]
report += ["```"]
report += ["*** Setup:", get_versions()]
report += ["*** The benchmark command line was:", get_original_command()]
report += ["```"]
report += ["----------8<-----------------8<--------"]
report += ["*** Results (console):", df_console.to_markdown(index=UpperCamelCase , floatfmt='''.2f''' )]
print('''\n\n'''.join(UpperCamelCase ) )
def snake_case_ ():
'''simple docstring'''
_a = argparse.ArgumentParser()
parser.add_argument(
'''--base-cmd''' , default=UpperCamelCase , type=UpperCamelCase , required=UpperCamelCase , help='''Base cmd''' , )
parser.add_argument(
'''--variations''' , default=UpperCamelCase , type=UpperCamelCase , nargs='''+''' , required=UpperCamelCase , help='''Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'''' , )
parser.add_argument(
'''--base-variation''' , default=UpperCamelCase , type=UpperCamelCase , help='''Baseline variation to compare to. if None the minimal target value will be used to compare against''' , )
parser.add_argument(
'''--target-metric-key''' , default=UpperCamelCase , type=UpperCamelCase , required=UpperCamelCase , help='''Target metric key in output_dir/all_results.json, e.g., train_samples_per_second''' , )
parser.add_argument(
'''--report-metric-keys''' , default='''''' , type=UpperCamelCase , help='''Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples''' , )
parser.add_argument(
'''--repeat-times''' , default=1 , type=UpperCamelCase , help='''How many times to re-run each variation - an average will be reported''' , )
parser.add_argument(
'''--output_dir''' , default='''output_benchmark''' , type=UpperCamelCase , help='''The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked''' , )
parser.add_argument(
'''--verbose''' , default=UpperCamelCase , action='''store_true''' , help='''Whether to show the outputs of each run or just the benchmark progress''' , )
_a = parser.parse_args()
_a = args.output_dir
Path(UpperCamelCase ).mkdir(exist_ok=UpperCamelCase )
_a = get_base_command(UpperCamelCase , UpperCamelCase )
# split each dimension into its --foo variations
_a = [list(map(str.strip , re.split(R'''\|''' , UpperCamelCase ) ) ) for x in args.variations]
# build a cartesian product of dimensions and convert those back into cmd-line arg strings,
# while stripping white space for inputs that were empty
_a = list(map(str.strip , map(''' '''.join , itertools.product(*UpperCamelCase ) ) ) )
_a = max(len(UpperCamelCase ) for x in variations )
# split wanted keys
_a = args.report_metric_keys.split()
# capture prints into a log file for convenience
_a = f'benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt'
print(f'\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt' )
print(f'and this script\'s output is also piped into {report_fn}' )
_a = Tee(UpperCamelCase )
print(f'\n*** Running {len(UpperCamelCase )} benchmarks:' )
print(f'Base command: {" ".join(UpperCamelCase )}' )
_a = '''variation'''
_a = []
for id, variation in enumerate(tqdm(UpperCamelCase , desc='''Total completion: ''' , leave=UpperCamelCase ) ):
_a = base_cmd + variation.split()
results.append(
process_run(
id + 1 , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , args.target_metric_key , UpperCamelCase , args.repeat_times , UpperCamelCase , args.verbose , ) )
process_results(UpperCamelCase , args.target_metric_key , UpperCamelCase , args.base_variation , UpperCamelCase )
if __name__ == "__main__":
main()
| 22 |
"""simple docstring"""
A_ : Any = "0.21.0"
from .accelerator import Accelerator
from .big_modeling import (
cpu_offload,
cpu_offload_with_hook,
disk_offload,
dispatch_model,
init_empty_weights,
init_on_device,
load_checkpoint_and_dispatch,
)
from .data_loader import skip_first_batches
from .launchers import debug_launcher, notebook_launcher
from .state import PartialState
from .utils import (
DeepSpeedPlugin,
DistributedDataParallelKwargs,
DistributedType,
FullyShardedDataParallelPlugin,
GradScalerKwargs,
InitProcessGroupKwargs,
find_executable_batch_size,
infer_auto_device_map,
is_rich_available,
load_checkpoint_in_model,
synchronize_rng_states,
)
if is_rich_available():
from .utils import rich
| 196 | 0 |
# 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 torch
from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool
class lowerCAmelCase__( __lowercase ):
'''simple docstring'''
__snake_case = 'facebook/bart-large-mnli'
__snake_case = (
'This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which '
'should be the text to classify, and `labels`, which should be the list of labels to use for classification. '
'It returns the most likely label in the list of provided `labels` for the input text.'
)
__snake_case = 'text_classifier'
__snake_case = AutoTokenizer
__snake_case = AutoModelForSequenceClassification
__snake_case = ['text', ['text']]
__snake_case = ['text']
def UpperCamelCase_ ( self ) -> str:
super().setup()
_SCREAMING_SNAKE_CASE : Union[str, Any] = self.model.config
_SCREAMING_SNAKE_CASE : Optional[Any] = -1
for idx, label in config.idalabel.items():
if label.lower().startswith("entail" ):
_SCREAMING_SNAKE_CASE : Union[str, Any] = int(__lowerCamelCase )
if self.entailment_id == -1:
raise ValueError("Could not determine the entailment ID from the model config, please pass it at init." )
def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> List[str]:
_SCREAMING_SNAKE_CASE : str = labels
return self.pre_processor(
[text] * len(__lowerCamelCase ) , [F"""This example is {label}""" for label in labels] , return_tensors="pt" , padding="max_length" , )
def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any:
_SCREAMING_SNAKE_CASE : List[str] = outputs.logits
_SCREAMING_SNAKE_CASE : List[str] = torch.argmax(logits[:, 2] ).item()
return self._labels[label_id] | 381 |
import copy
import os
from typing import TYPE_CHECKING, List, Union
if TYPE_CHECKING:
pass
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ =logging.get_logger(__name__)
UpperCamelCase__ ={
'kakaobrain/align-base': 'https://huggingface.co/kakaobrain/align-base/resolve/main/config.json',
}
class lowerCAmelCase__( __lowercase ):
'''simple docstring'''
__snake_case = 'align_text_model'
def __init__( self , __lowerCamelCase=3_0_5_2_2 , __lowerCamelCase=7_6_8 , __lowerCamelCase=1_2 , __lowerCamelCase=1_2 , __lowerCamelCase=3_0_7_2 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=5_1_2 , __lowerCamelCase=2 , __lowerCamelCase=0.02 , __lowerCamelCase=1E-12 , __lowerCamelCase=0 , __lowerCamelCase="absolute" , __lowerCamelCase=True , **__lowerCamelCase , ) -> List[Any]:
super().__init__(**__lowerCamelCase )
_SCREAMING_SNAKE_CASE : Tuple = vocab_size
_SCREAMING_SNAKE_CASE : Optional[int] = hidden_size
_SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers
_SCREAMING_SNAKE_CASE : Optional[int] = num_attention_heads
_SCREAMING_SNAKE_CASE : int = hidden_act
_SCREAMING_SNAKE_CASE : Any = intermediate_size
_SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob
_SCREAMING_SNAKE_CASE : Union[str, Any] = attention_probs_dropout_prob
_SCREAMING_SNAKE_CASE : Dict = max_position_embeddings
_SCREAMING_SNAKE_CASE : Optional[Any] = type_vocab_size
_SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range
_SCREAMING_SNAKE_CASE : Dict = layer_norm_eps
_SCREAMING_SNAKE_CASE : str = position_embedding_type
_SCREAMING_SNAKE_CASE : Dict = use_cache
_SCREAMING_SNAKE_CASE : List[str] = pad_token_id
@classmethod
def UpperCamelCase_ ( cls , __lowerCamelCase , **__lowerCamelCase ) -> "PretrainedConfig":
cls._set_token_in_kwargs(__lowerCamelCase )
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = cls.get_config_dict(__lowerCamelCase , **__lowerCamelCase )
# get the text config dict if we are loading from AlignConfig
if config_dict.get("model_type" ) == "align":
_SCREAMING_SNAKE_CASE : Union[str, Any] = config_dict["text_config"]
if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" )
return cls.from_dict(__lowerCamelCase , **__lowerCamelCase )
class lowerCAmelCase__( __lowercase ):
'''simple docstring'''
__snake_case = 'align_vision_model'
def __init__( self , __lowerCamelCase = 3 , __lowerCamelCase = 6_0_0 , __lowerCamelCase = 2.0 , __lowerCamelCase = 3.1 , __lowerCamelCase = 8 , __lowerCamelCase = [3, 3, 5, 3, 5, 5, 3] , __lowerCamelCase = [3_2, 1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2] , __lowerCamelCase = [1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2, 3_2_0] , __lowerCamelCase = [] , __lowerCamelCase = [1, 2, 2, 2, 1, 2, 1] , __lowerCamelCase = [1, 2, 2, 3, 3, 4, 1] , __lowerCamelCase = [1, 6, 6, 6, 6, 6, 6] , __lowerCamelCase = 0.25 , __lowerCamelCase = "swish" , __lowerCamelCase = 2_5_6_0 , __lowerCamelCase = "mean" , __lowerCamelCase = 0.02 , __lowerCamelCase = 0.001 , __lowerCamelCase = 0.99 , __lowerCamelCase = 0.2 , **__lowerCamelCase , ) -> Dict:
super().__init__(**__lowerCamelCase )
_SCREAMING_SNAKE_CASE : int = num_channels
_SCREAMING_SNAKE_CASE : List[Any] = image_size
_SCREAMING_SNAKE_CASE : Dict = width_coefficient
_SCREAMING_SNAKE_CASE : str = depth_coefficient
_SCREAMING_SNAKE_CASE : Union[str, Any] = depth_divisor
_SCREAMING_SNAKE_CASE : List[Any] = kernel_sizes
_SCREAMING_SNAKE_CASE : Tuple = in_channels
_SCREAMING_SNAKE_CASE : Optional[int] = out_channels
_SCREAMING_SNAKE_CASE : List[Any] = depthwise_padding
_SCREAMING_SNAKE_CASE : str = strides
_SCREAMING_SNAKE_CASE : List[str] = num_block_repeats
_SCREAMING_SNAKE_CASE : Tuple = expand_ratios
_SCREAMING_SNAKE_CASE : int = squeeze_expansion_ratio
_SCREAMING_SNAKE_CASE : List[Any] = hidden_act
_SCREAMING_SNAKE_CASE : Optional[int] = hidden_dim
_SCREAMING_SNAKE_CASE : Dict = pooling_type
_SCREAMING_SNAKE_CASE : List[Any] = initializer_range
_SCREAMING_SNAKE_CASE : List[Any] = batch_norm_eps
_SCREAMING_SNAKE_CASE : Union[str, Any] = batch_norm_momentum
_SCREAMING_SNAKE_CASE : int = drop_connect_rate
_SCREAMING_SNAKE_CASE : Tuple = sum(__lowerCamelCase ) * 4
@classmethod
def UpperCamelCase_ ( cls , __lowerCamelCase , **__lowerCamelCase ) -> "PretrainedConfig":
cls._set_token_in_kwargs(__lowerCamelCase )
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = cls.get_config_dict(__lowerCamelCase , **__lowerCamelCase )
# get the vision config dict if we are loading from AlignConfig
if config_dict.get("model_type" ) == "align":
_SCREAMING_SNAKE_CASE : int = config_dict["vision_config"]
if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" )
return cls.from_dict(__lowerCamelCase , **__lowerCamelCase )
class lowerCAmelCase__( __lowercase ):
'''simple docstring'''
__snake_case = 'align'
__snake_case = True
def __init__( self , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=6_4_0 , __lowerCamelCase=1.0 , __lowerCamelCase=0.02 , **__lowerCamelCase , ) -> List[Any]:
super().__init__(**__lowerCamelCase )
if text_config is None:
_SCREAMING_SNAKE_CASE : List[Any] = {}
logger.info("text_config is None. Initializing the AlignTextConfig with default values." )
if vision_config is None:
_SCREAMING_SNAKE_CASE : List[str] = {}
logger.info("vision_config is None. Initializing the AlignVisionConfig with default values." )
_SCREAMING_SNAKE_CASE : Dict = AlignTextConfig(**__lowerCamelCase )
_SCREAMING_SNAKE_CASE : Any = AlignVisionConfig(**__lowerCamelCase )
_SCREAMING_SNAKE_CASE : int = projection_dim
_SCREAMING_SNAKE_CASE : List[str] = temperature_init_value
_SCREAMING_SNAKE_CASE : Any = initializer_range
@classmethod
def UpperCamelCase_ ( cls , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ) -> List[str]:
return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__lowerCamelCase )
def UpperCamelCase_ ( self ) -> Union[str, Any]:
_SCREAMING_SNAKE_CASE : Optional[int] = copy.deepcopy(self.__dict__ )
_SCREAMING_SNAKE_CASE : Any = self.text_config.to_dict()
_SCREAMING_SNAKE_CASE : Optional[int] = self.vision_config.to_dict()
_SCREAMING_SNAKE_CASE : Dict = self.__class__.model_type
return output | 381 | 1 |
"""simple docstring"""
class A__ :
'''simple docstring'''
def __init__( self: Optional[int] , _SCREAMING_SNAKE_CASE: int) -> List[Any]:
"""simple docstring"""
__lowerCAmelCase : Dict = size
__lowerCAmelCase : Optional[int] = [0] * size
__lowerCAmelCase : Tuple = [0] * size
@staticmethod
def _SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE: int) -> int:
"""simple docstring"""
return index | (index + 1)
@staticmethod
def _SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE: int) -> List[str]:
"""simple docstring"""
return (index & (index + 1)) - 1
def _SCREAMING_SNAKE_CASE ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: int) -> Any:
"""simple docstring"""
__lowerCAmelCase : Tuple = value
while index < self.size:
__lowerCAmelCase : Any = self.get_prev(__lowercase) + 1
if current_left_border == index:
__lowerCAmelCase : Union[str, Any] = value
else:
__lowerCAmelCase : List[str] = max(__lowercase , __lowercase , __lowercase)
__lowerCAmelCase : Tuple = self.get_next(__lowercase)
def _SCREAMING_SNAKE_CASE ( self: List[Any] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: int) -> Union[str, Any]:
"""simple docstring"""
right -= 1 # Because of right is exclusive
__lowerCAmelCase : List[Any] = 0
while left <= right:
__lowerCAmelCase : Any = self.get_prev(__lowercase)
if left <= current_left:
__lowerCAmelCase : Dict = max(__lowercase , self.tree[right])
__lowerCAmelCase : Any = current_left
else:
__lowerCAmelCase : int = max(__lowercase , self.arr[right])
right -= 1
return result
if __name__ == "__main__":
import doctest
doctest.testmod() | 293 |
import math
from typing import Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
get_image_size,
is_torch_available,
is_torch_tensor,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_torch_available():
import torch
if is_vision_available():
import PIL
lowercase_ = logging.get_logger(__name__)
def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
def constraint_to_multiple_of(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=None ):
lowercase__ = round(val / multiple ) * multiple
if max_val is not None and x > max_val:
lowercase__ = math.floor(val / multiple ) * multiple
if x < min_val:
lowercase__ = math.ceil(val / multiple ) * multiple
return x
lowercase__ = (output_size, output_size) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else output_size
lowercase__ , lowercase__ = get_image_size(SCREAMING_SNAKE_CASE_ )
lowercase__ , lowercase__ = output_size
# determine new height and width
lowercase__ = output_height / input_height
lowercase__ = output_width / input_width
if keep_aspect_ratio:
# scale as little as possible
if abs(1 - scale_width ) < abs(1 - scale_height ):
# fit width
lowercase__ = scale_width
else:
# fit height
lowercase__ = scale_height
lowercase__ = constraint_to_multiple_of(scale_height * input_height , multiple=SCREAMING_SNAKE_CASE_ )
lowercase__ = constraint_to_multiple_of(scale_width * input_width , multiple=SCREAMING_SNAKE_CASE_ )
return (new_height, new_width)
class _snake_case ( lowercase__):
UpperCamelCase__ : Tuple =["""pixel_values"""]
def __init__( self : Any, __lowercase : bool = True, __lowercase : Dict[str, int] = None, __lowercase : PILImageResampling = PILImageResampling.BILINEAR, __lowercase : bool = False, __lowercase : int = 1, __lowercase : bool = True, __lowercase : Union[int, float] = 1 / 255, __lowercase : bool = True, __lowercase : Optional[Union[float, List[float]]] = None, __lowercase : Optional[Union[float, List[float]]] = None, **__lowercase : List[Any], ):
super().__init__(**__lowercase )
lowercase__ = size if size is not None else {"height": 384, "width": 384}
lowercase__ = get_size_dict(__lowercase )
lowercase__ = do_resize
lowercase__ = size
lowercase__ = keep_aspect_ratio
lowercase__ = ensure_multiple_of
lowercase__ = resample
lowercase__ = do_rescale
lowercase__ = rescale_factor
lowercase__ = do_normalize
lowercase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
lowercase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD
def A__ ( self : List[Any], __lowercase : np.ndarray, __lowercase : Dict[str, int], __lowercase : bool = False, __lowercase : int = 1, __lowercase : PILImageResampling = PILImageResampling.BICUBIC, __lowercase : Optional[Union[str, ChannelDimension]] = None, **__lowercase : Union[str, Any], ):
lowercase__ = get_size_dict(__lowercase )
if "height" not in size or "width" not in size:
raise ValueError(F'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' )
lowercase__ = get_resize_output_image_size(
__lowercase, output_size=(size["height"], size["width"]), keep_aspect_ratio=__lowercase, multiple=__lowercase, )
return resize(__lowercase, size=__lowercase, resample=__lowercase, data_format=__lowercase, **__lowercase )
def A__ ( self : str, __lowercase : np.ndarray, __lowercase : Union[int, float], __lowercase : Optional[Union[str, ChannelDimension]] = None, **__lowercase : List[Any], ):
return rescale(__lowercase, scale=__lowercase, data_format=__lowercase, **__lowercase )
def A__ ( self : Any, __lowercase : np.ndarray, __lowercase : Union[float, List[float]], __lowercase : Union[float, List[float]], __lowercase : Optional[Union[str, ChannelDimension]] = None, **__lowercase : Optional[Any], ):
return normalize(__lowercase, mean=__lowercase, std=__lowercase, data_format=__lowercase, **__lowercase )
def A__ ( self : List[str], __lowercase : ImageInput, __lowercase : bool = None, __lowercase : int = None, __lowercase : bool = None, __lowercase : int = None, __lowercase : PILImageResampling = None, __lowercase : bool = None, __lowercase : float = None, __lowercase : bool = None, __lowercase : Optional[Union[float, List[float]]] = None, __lowercase : Optional[Union[float, List[float]]] = None, __lowercase : Optional[Union[str, TensorType]] = None, __lowercase : ChannelDimension = ChannelDimension.FIRST, **__lowercase : Tuple, ):
lowercase__ = do_resize if do_resize is not None else self.do_resize
lowercase__ = size if size is not None else self.size
lowercase__ = get_size_dict(__lowercase )
lowercase__ = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
lowercase__ = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
lowercase__ = resample if resample is not None else self.resample
lowercase__ = do_rescale if do_rescale is not None else self.do_rescale
lowercase__ = rescale_factor if rescale_factor is not None else self.rescale_factor
lowercase__ = do_normalize if do_normalize is not None else self.do_normalize
lowercase__ = image_mean if image_mean is not None else self.image_mean
lowercase__ = image_std if image_std is not None else self.image_std
lowercase__ = make_list_of_images(__lowercase )
if not valid_images(__lowercase ):
raise ValueError(
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
"torch.Tensor, tf.Tensor or jax.ndarray." )
if do_resize and size is None or resample is None:
raise ValueError("Size and resample must be specified if do_resize is True." )
if do_rescale and rescale_factor is None:
raise ValueError("Rescale factor must be specified if do_rescale is True." )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("Image mean and std must be specified if do_normalize is True." )
# All transformations expect numpy arrays.
lowercase__ = [to_numpy_array(__lowercase ) for image in images]
if do_resize:
lowercase__ = [self.resize(image=__lowercase, size=__lowercase, resample=__lowercase ) for image in images]
if do_rescale:
lowercase__ = [self.rescale(image=__lowercase, scale=__lowercase ) for image in images]
if do_normalize:
lowercase__ = [self.normalize(image=__lowercase, mean=__lowercase, std=__lowercase ) for image in images]
lowercase__ = [to_channel_dimension_format(__lowercase, __lowercase ) for image in images]
lowercase__ = {"pixel_values": images}
return BatchFeature(data=__lowercase, tensor_type=__lowercase )
def A__ ( self : int, __lowercase : Optional[Any], __lowercase : List[Tuple] = None ):
lowercase__ = outputs.logits
# Resize logits and compute semantic segmentation maps
if target_sizes is not None:
if len(__lowercase ) != len(__lowercase ):
raise ValueError(
"Make sure that you pass in as many target sizes as the batch dimension of the logits" )
if is_torch_tensor(__lowercase ):
lowercase__ = target_sizes.numpy()
lowercase__ = []
for idx in range(len(__lowercase ) ):
lowercase__ = torch.nn.functional.interpolate(
logits[idx].unsqueeze(dim=0 ), size=target_sizes[idx], mode="bilinear", align_corners=__lowercase )
lowercase__ = resized_logits[0].argmax(dim=0 )
semantic_segmentation.append(__lowercase )
else:
lowercase__ = logits.argmax(dim=1 )
lowercase__ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )]
return semantic_segmentation
| 413 | 0 |
from collections import defaultdict
def __UpperCamelCase ( _A ):
lowerCAmelCase_ = 1
lowerCAmelCase_ = True
for v in tree[start]:
if v not in visited:
ret += dfs(__lowerCAmelCase )
if ret % 2 == 0:
cuts.append(__lowerCAmelCase )
return ret
def __UpperCamelCase ( ):
dfs(1 )
if __name__ == "__main__":
_A = 10, 9
_A = defaultdict(list)
_A = {}
_A = []
_A = 0
_A = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)]
for u, v in edges:
tree[u].append(v)
tree[v].append(u)
even_tree()
print(len(cuts) - 1)
| 709 |
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
_A = logging.get_logger(__name__)
_A = '''▁'''
_A = {'''vocab_file''': '''spiece.model'''}
_A = {
'''vocab_file''': {
'''google/reformer-crime-and-punishment''': (
'''https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model'''
)
}
}
_A = {
'''google/reformer-crime-and-punishment''': 524_288,
}
class A ( __UpperCAmelCase ):
__snake_case = VOCAB_FILES_NAMES
__snake_case = PRETRAINED_VOCAB_FILES_MAP
__snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__snake_case = ['input_ids', 'attention_mask']
def __init__( self, UpperCamelCase__, UpperCamelCase__="</s>", UpperCamelCase__="<unk>", UpperCamelCase__=[], UpperCamelCase__ = None, **UpperCamelCase__, ):
"""simple docstring"""
lowerCAmelCase_ = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
eos_token=UpperCamelCase__, unk_token=UpperCamelCase__, additional_special_tokens=UpperCamelCase__, sp_model_kwargs=self.sp_model_kwargs, **UpperCamelCase__, )
lowerCAmelCase_ = vocab_file
lowerCAmelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(UpperCamelCase__ )
@property
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
return self.sp_model.get_piece_size()
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ = {self.convert_ids_to_tokens(UpperCamelCase__ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self ):
"""simple docstring"""
lowerCAmelCase_ = self.__dict__.copy()
lowerCAmelCase_ = None
return state
def __setstate__( self, UpperCamelCase__ ):
"""simple docstring"""
lowerCAmelCase_ = d
# for backward compatibility
if not hasattr(self, '''sp_model_kwargs''' ):
lowerCAmelCase_ = {}
lowerCAmelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__ ):
"""simple docstring"""
return self.sp_model.encode(UpperCamelCase__, out_type=UpperCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__ ):
"""simple docstring"""
return self.sp_model.piece_to_id(UpperCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__ ):
"""simple docstring"""
if index < self.sp_model.get_piece_size():
lowerCAmelCase_ = self.sp_model.IdToPiece(UpperCamelCase__ )
return token
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__ ):
"""simple docstring"""
lowerCAmelCase_ = []
lowerCAmelCase_ = ''''''
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
out_string += self.sp_model.decode(UpperCamelCase__ ) + token
lowerCAmelCase_ = []
else:
current_sub_tokens.append(UpperCamelCase__ )
out_string += self.sp_model.decode(UpperCamelCase__ )
return out_string.strip()
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__ = None ):
"""simple docstring"""
if not os.path.isdir(UpperCamelCase__ ):
logger.error(f"Vocabulary path ({save_directory}) should be a directory" )
return
lowerCAmelCase_ = os.path.join(
UpperCamelCase__, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file, UpperCamelCase__ )
elif not os.path.isfile(self.vocab_file ):
with open(UpperCamelCase__, '''wb''' ) as fi:
lowerCAmelCase_ = self.sp_model.serialized_model_proto()
fi.write(UpperCamelCase__ )
return (out_vocab_file,)
| 325 | 0 |
import json
import multiprocessing
import os
import re
from collections import defaultdict
import torch
from accelerate import Accelerator
from accelerate.utils import set_seed
from arguments import HumanEvalArguments
from datasets import load_dataset, load_metric
from torch.utils.data import IterableDataset
from torch.utils.data.dataloader import DataLoader
from tqdm import tqdm
import transformers
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList
snake_case__ : List[Any] = ["\nclass", "\ndef", "\n#", "\n@", "\nprint", "\nif"]
class SCREAMING_SNAKE_CASE_ (_UpperCAmelCase ):
'''simple docstring'''
def __init__( self : str , __a : List[str] , __a : Any , __a : Union[str, Any]=None , __a : int=1 ) ->Optional[int]:
lowerCamelCase_ : List[Any] = tokenizer
lowerCamelCase_ : Any = dataset
lowerCamelCase_ : List[Any] = len(lowerCamelCase_ ) if n_tasks is None else n_tasks
lowerCamelCase_ : Dict = n_copies
def __iter__( self : Dict ) ->str:
lowerCamelCase_ : str = []
for task in range(self.n_tasks ):
# without strip, the model generate commented codes ...
prompts.append(self.tokenizer.eos_token + self.dataset[task]["""prompt"""].strip() )
lowerCamelCase_ : str = self.tokenizer(lowerCamelCase_ , padding=lowerCamelCase_ , return_tensors="""pt""" )
for task in range(self.n_tasks ):
for _ in range(self.n_copies ):
yield {
"ids": outputs.input_ids[task],
"task_id": task,
"input_len": outputs.attention_mask[task].sum(),
}
class SCREAMING_SNAKE_CASE_ (_UpperCAmelCase ):
'''simple docstring'''
def __init__( self : Any , __a : int , __a : Dict , __a : Optional[Any] ) ->Optional[Any]:
lowerCamelCase_ : List[str] = start_length
lowerCamelCase_ : Dict = eof_strings
lowerCamelCase_ : int = tokenizer
def __call__( self : Dict , __a : Optional[Any] , __a : List[str] , **__a : Dict ) ->List[str]:
lowerCamelCase_ : Tuple = self.tokenizer.batch_decode(input_ids[:, self.start_length :] )
lowerCamelCase_ : List[str] = []
for decoded_generation in decoded_generations:
done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) )
return all(lowerCamelCase_ )
def __lowerCamelCase ( A__ : str ) -> Union[str, Any]:
lowerCamelCase_ : Optional[Any] = re.split("""(%s)""" % """|""".join(a_ ) , a_ )
# last string should be ""
return "".join(string_list[:-2] )
def __lowerCamelCase ( A__ : List[str] , A__ : str , A__ : str , A__ : Dict , A__ : Optional[Any] , A__ : str=20 , **A__ : Tuple ) -> List[str]:
lowerCamelCase_ : Union[str, Any] = defaultdict(a_ ) # dict of list of generated tokens
for step, batch in tqdm(enumerate(a_ ) ):
with torch.no_grad():
lowerCamelCase_ : str = batch['''ids'''].shape[-1]
lowerCamelCase_ : List[str] = accelerator.unwrap_model(a_ ).generate(
input_ids=batch["""ids"""][:, : batch["""input_len"""]] , num_return_sequences=a_ , **a_ )
# each task is generated batch_size times
lowerCamelCase_ : Optional[int] = batch['''task_id'''].repeat(a_ )
lowerCamelCase_ : Any = accelerator.pad_across_processes(
a_ , dim=1 , pad_index=tokenizer.pad_token_id )
lowerCamelCase_ : Any = accelerator.gather((generated_tokens, generated_tasks) )
lowerCamelCase_ : Any = generated_tokens.cpu().numpy()
lowerCamelCase_ : Dict = generated_tasks.cpu().numpy()
for task, generated_tokens in zip(a_ , a_ ):
gen_token_dict[task].append(a_ )
lowerCamelCase_ : Dict = [[] for _ in range(a_ )]
for task, generated_tokens in gen_token_dict.items():
for s in generated_tokens:
lowerCamelCase_ : Tuple = tokenizer.decode(a_ , skip_special_tokens=a_ , clean_up_tokenization_spaces=a_ )
code_gens[task].append(remove_last_block(a_ ) )
return code_gens
def __lowerCamelCase ( ) -> Optional[int]:
lowerCamelCase_ : Any = HfArgumentParser(a_ )
lowerCamelCase_ : Any = parser.parse_args()
transformers.logging.set_verbosity_error()
# enables code execution in code_eval metric
lowerCamelCase_ : str = args.HF_ALLOW_CODE_EVAL
# make sure tokenizer plays nice with multiprocessing
lowerCamelCase_ : Optional[int] = '''false'''
if args.num_workers is None:
lowerCamelCase_ : List[Any] = multiprocessing.cpu_count()
# Use dataset load to feed to accelerate
lowerCamelCase_ : List[str] = Accelerator()
set_seed(args.seed , device_specific=a_ )
# Load model and tokenizer
lowerCamelCase_ : Dict = AutoTokenizer.from_pretrained(args.model_ckpt )
lowerCamelCase_ : Optional[int] = tokenizer.eos_token
lowerCamelCase_ : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt )
# Generation settings
lowerCamelCase_ : int = {
'''do_sample''': args.do_sample,
'''temperature''': args.temperature,
'''max_new_tokens''': args.max_new_tokens,
'''top_p''': args.top_p,
'''top_k''': args.top_k,
'''stopping_criteria''': StoppingCriteriaList([EndOfFunctionCriteria(0 , a_ , a_ )] ),
}
# Load evaluation dataset and metric
lowerCamelCase_ : Optional[Any] = load_dataset("""openai_humaneval""" )
lowerCamelCase_ : Dict = load_metric("""code_eval""" )
lowerCamelCase_ : List[Any] = args.num_tasks if args.num_tasks is not None else len(human_eval["""test"""] )
lowerCamelCase_ : Optional[Any] = args.n_samples // args.batch_size
lowerCamelCase_ : List[str] = TokenizedDataset(a_ , human_eval["""test"""] , n_copies=a_ , n_tasks=a_ )
# do not confuse args.batch_size, which is actually the num_return_sequences
lowerCamelCase_ : Dict = DataLoader(a_ , batch_size=1 )
# Run a quick test to see if code evaluation is enabled
try:
lowerCamelCase_ : Optional[int] = code_eval_metric.compute(references=[""""""] , predictions=[[""""""]] )
except ValueError as exception:
print(
"""Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL=\"1\"`"""
""" flag to enable code evaluation.""" )
raise exception
lowerCamelCase_ : Optional[int] = accelerator.prepare(a_ , a_ )
lowerCamelCase_ : int = complete_code(
a_ , a_ , a_ , a_ , n_tasks=a_ , batch_size=args.batch_size , **a_ , )
if accelerator.is_main_process:
lowerCamelCase_ : int = []
for task in tqdm(range(a_ ) ):
lowerCamelCase_ : Tuple = human_eval['''test'''][task]['''test''']
lowerCamelCase_ : List[str] = f'''check({human_eval['test'][task]['entry_point']})'''
references.append("""\n""" + test_func + """\n""" + entry_point )
# Evaluate completions with "code_eval" metric
lowerCamelCase_ : Optional[int] = code_eval_metric.compute(
references=a_ , predictions=a_ , num_workers=args.num_workers )
print(f'''Results: {pass_at_k}''' )
# Save results to json file
with open(args.output_file , """w""" ) as fp:
json.dump(a_ , a_ )
# For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing
# https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script
if __name__ == "__main__":
main()
| 278 |
"""simple docstring"""
from __future__ import annotations
import os
import tempfile
import unittest
from transformers import ConvBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFConvBertForMaskedLM,
TFConvBertForMultipleChoice,
TFConvBertForQuestionAnswering,
TFConvBertForSequenceClassification,
TFConvBertForTokenClassification,
TFConvBertModel,
)
class lowercase__:
'''simple docstring'''
def __init__( self :Tuple , lowerCamelCase_ :Tuple , lowerCamelCase_ :Tuple=13 , lowerCamelCase_ :List[str]=7 , lowerCamelCase_ :Dict=True , lowerCamelCase_ :List[Any]=True , lowerCamelCase_ :List[str]=True , lowerCamelCase_ :Dict=True , lowerCamelCase_ :str=99 , lowerCamelCase_ :Optional[Any]=32 , lowerCamelCase_ :Tuple=2 , lowerCamelCase_ :int=4 , lowerCamelCase_ :Optional[Any]=37 , lowerCamelCase_ :Any="gelu" , lowerCamelCase_ :Any=0.1 , lowerCamelCase_ :Any=0.1 , lowerCamelCase_ :Optional[int]=5_12 , lowerCamelCase_ :str=16 , lowerCamelCase_ :Optional[int]=2 , lowerCamelCase_ :List[str]=0.0_2 , lowerCamelCase_ :int=3 , lowerCamelCase_ :List[Any]=4 , lowerCamelCase_ :Optional[Any]=None , ) -> Any:
'''simple docstring'''
SCREAMING_SNAKE_CASE : int = parent
SCREAMING_SNAKE_CASE : str = 13
SCREAMING_SNAKE_CASE : str = 7
SCREAMING_SNAKE_CASE : List[Any] = True
SCREAMING_SNAKE_CASE : List[str] = True
SCREAMING_SNAKE_CASE : Union[str, Any] = True
SCREAMING_SNAKE_CASE : str = True
SCREAMING_SNAKE_CASE : Any = 99
SCREAMING_SNAKE_CASE : Dict = 3_84
SCREAMING_SNAKE_CASE : List[str] = 2
SCREAMING_SNAKE_CASE : int = 4
SCREAMING_SNAKE_CASE : Any = 37
SCREAMING_SNAKE_CASE : List[str] = '''gelu'''
SCREAMING_SNAKE_CASE : List[str] = 0.1
SCREAMING_SNAKE_CASE : int = 0.1
SCREAMING_SNAKE_CASE : Union[str, Any] = 5_12
SCREAMING_SNAKE_CASE : int = 16
SCREAMING_SNAKE_CASE : List[str] = 2
SCREAMING_SNAKE_CASE : Tuple = 0.0_2
SCREAMING_SNAKE_CASE : List[str] = 3
SCREAMING_SNAKE_CASE : Union[str, Any] = 4
SCREAMING_SNAKE_CASE : str = 1_28
SCREAMING_SNAKE_CASE : List[str] = 2
SCREAMING_SNAKE_CASE : Union[str, Any] = 9
SCREAMING_SNAKE_CASE : Dict = 1
SCREAMING_SNAKE_CASE : List[str] = None
def __lowerCAmelCase ( self :Optional[Any] ) -> Any:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
SCREAMING_SNAKE_CASE : int = None
if self.use_input_mask:
SCREAMING_SNAKE_CASE : Tuple = random_attention_mask([self.batch_size, self.seq_length] )
SCREAMING_SNAKE_CASE : List[Any] = None
if self.use_token_type_ids:
SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
SCREAMING_SNAKE_CASE : List[str] = None
SCREAMING_SNAKE_CASE : str = None
SCREAMING_SNAKE_CASE : str = None
if self.use_labels:
SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size )
SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([self.batch_size] , self.num_choices )
SCREAMING_SNAKE_CASE : List[str] = ConvBertConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=lowerCamelCase_ , )
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def __lowerCAmelCase ( self :str , lowerCamelCase_ :Optional[int] , lowerCamelCase_ :int , lowerCamelCase_ :List[str] , lowerCamelCase_ :Union[str, Any] , lowerCamelCase_ :int , lowerCamelCase_ :List[Any] , lowerCamelCase_ :Tuple ) -> Dict:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[Any] = TFConvBertModel(config=lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Optional[int] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
SCREAMING_SNAKE_CASE : Dict = [input_ids, input_mask]
SCREAMING_SNAKE_CASE : List[Any] = model(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : int = model(lowerCamelCase_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __lowerCAmelCase ( self :str , lowerCamelCase_ :List[Any] , lowerCamelCase_ :List[str] , lowerCamelCase_ :int , lowerCamelCase_ :Optional[int] , lowerCamelCase_ :str , lowerCamelCase_ :str , lowerCamelCase_ :Dict ) -> str:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Any = TFConvBertForMaskedLM(config=lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Tuple = {
'''input_ids''': input_ids,
'''attention_mask''': input_mask,
'''token_type_ids''': token_type_ids,
}
SCREAMING_SNAKE_CASE : Tuple = model(lowerCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def __lowerCAmelCase ( self :Dict , lowerCamelCase_ :str , lowerCamelCase_ :Any , lowerCamelCase_ :str , lowerCamelCase_ :Dict , lowerCamelCase_ :int , lowerCamelCase_ :Optional[int] , lowerCamelCase_ :List[Any] ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[int] = self.num_labels
SCREAMING_SNAKE_CASE : Dict = TFConvBertForSequenceClassification(config=lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Any = {
'''input_ids''': input_ids,
'''attention_mask''': input_mask,
'''token_type_ids''': token_type_ids,
}
SCREAMING_SNAKE_CASE : List[Any] = model(lowerCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __lowerCAmelCase ( self :int , lowerCamelCase_ :Dict , lowerCamelCase_ :Optional[int] , lowerCamelCase_ :Dict , lowerCamelCase_ :Any , lowerCamelCase_ :Dict , lowerCamelCase_ :List[Any] , lowerCamelCase_ :List[Any] ) -> List[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE : List[Any] = self.num_choices
SCREAMING_SNAKE_CASE : Optional[Any] = TFConvBertForMultipleChoice(config=lowerCamelCase_ )
SCREAMING_SNAKE_CASE : List[Any] = tf.tile(tf.expand_dims(lowerCamelCase_ , 1 ) , (1, self.num_choices, 1) )
SCREAMING_SNAKE_CASE : Dict = tf.tile(tf.expand_dims(lowerCamelCase_ , 1 ) , (1, self.num_choices, 1) )
SCREAMING_SNAKE_CASE : List[Any] = tf.tile(tf.expand_dims(lowerCamelCase_ , 1 ) , (1, self.num_choices, 1) )
SCREAMING_SNAKE_CASE : Any = {
'''input_ids''': multiple_choice_inputs_ids,
'''attention_mask''': multiple_choice_input_mask,
'''token_type_ids''': multiple_choice_token_type_ids,
}
SCREAMING_SNAKE_CASE : Optional[int] = model(lowerCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def __lowerCAmelCase ( self :Optional[int] , lowerCamelCase_ :Tuple , lowerCamelCase_ :Any , lowerCamelCase_ :List[Any] , lowerCamelCase_ :Tuple , lowerCamelCase_ :Optional[int] , lowerCamelCase_ :Tuple , lowerCamelCase_ :List[str] ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[int] = self.num_labels
SCREAMING_SNAKE_CASE : List[Any] = TFConvBertForTokenClassification(config=lowerCamelCase_ )
SCREAMING_SNAKE_CASE : int = {
'''input_ids''': input_ids,
'''attention_mask''': input_mask,
'''token_type_ids''': token_type_ids,
}
SCREAMING_SNAKE_CASE : int = model(lowerCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def __lowerCAmelCase ( self :List[str] , lowerCamelCase_ :Union[str, Any] , lowerCamelCase_ :Optional[int] , lowerCamelCase_ :Tuple , lowerCamelCase_ :Optional[Any] , lowerCamelCase_ :List[str] , lowerCamelCase_ :Union[str, Any] , lowerCamelCase_ :Optional[Any] ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE : int = TFConvBertForQuestionAnswering(config=lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Dict = {
'''input_ids''': input_ids,
'''attention_mask''': input_mask,
'''token_type_ids''': token_type_ids,
}
SCREAMING_SNAKE_CASE : Dict = model(lowerCamelCase_ )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def __lowerCAmelCase ( self :List[Any] ) -> Optional[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Tuple = self.prepare_config_and_inputs()
(
(
SCREAMING_SNAKE_CASE
), (
SCREAMING_SNAKE_CASE
), (
SCREAMING_SNAKE_CASE
), (
SCREAMING_SNAKE_CASE
), (
SCREAMING_SNAKE_CASE
), (
SCREAMING_SNAKE_CASE
), (
SCREAMING_SNAKE_CASE
),
) : Optional[Any] = config_and_inputs
SCREAMING_SNAKE_CASE : Dict = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_tf
class lowercase__( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ):
'''simple docstring'''
UpperCamelCase = (
(
TFConvBertModel,
TFConvBertForMaskedLM,
TFConvBertForQuestionAnswering,
TFConvBertForSequenceClassification,
TFConvBertForTokenClassification,
TFConvBertForMultipleChoice,
)
if is_tf_available()
else ()
)
UpperCamelCase = (
{
"""feature-extraction""": TFConvBertModel,
"""fill-mask""": TFConvBertForMaskedLM,
"""question-answering""": TFConvBertForQuestionAnswering,
"""text-classification""": TFConvBertForSequenceClassification,
"""token-classification""": TFConvBertForTokenClassification,
"""zero-shot""": TFConvBertForSequenceClassification,
}
if is_tf_available()
else {}
)
UpperCamelCase = False
UpperCamelCase = False
UpperCamelCase = False
def __lowerCAmelCase ( self :Optional[int] ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Any = TFConvBertModelTester(self )
SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=lowerCamelCase_ , hidden_size=37 )
def __lowerCAmelCase ( self :List[str] ) -> Union[str, Any]:
'''simple docstring'''
self.config_tester.run_common_tests()
def __lowerCAmelCase ( self :Dict ) -> Dict:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase_ )
def __lowerCAmelCase ( self :Optional[int] ) -> int:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase_ )
def __lowerCAmelCase ( self :List[Any] ) -> int:
'''simple docstring'''
SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase_ )
def __lowerCAmelCase ( self :int ) -> Any:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*lowerCamelCase_ )
def __lowerCAmelCase ( self :Optional[Any] ) -> Tuple:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase_ )
def __lowerCAmelCase ( self :Any ) -> str:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*lowerCamelCase_ )
@slow
def __lowerCAmelCase ( self :int ) -> Optional[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
SCREAMING_SNAKE_CASE : List[Any] = True
SCREAMING_SNAKE_CASE : Tuple = True
if hasattr(lowerCamelCase_ , '''use_cache''' ):
SCREAMING_SNAKE_CASE : Any = True
SCREAMING_SNAKE_CASE : str = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length )
SCREAMING_SNAKE_CASE : Optional[int] = getattr(self.model_tester , '''key_length''' , lowerCamelCase_ )
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE : str = self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Optional[Any] = model_class(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : List[str] = len(model(lowerCamelCase_ ) )
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(lowerCamelCase_ , saved_model=lowerCamelCase_ )
SCREAMING_SNAKE_CASE : int = os.path.join(lowerCamelCase_ , '''saved_model''' , '''1''' )
SCREAMING_SNAKE_CASE : Tuple = tf.keras.models.load_model(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : int = model(lowerCamelCase_ )
if self.is_encoder_decoder:
SCREAMING_SNAKE_CASE : Optional[int] = outputs['''encoder_hidden_states''']
SCREAMING_SNAKE_CASE : str = outputs['''encoder_attentions''']
else:
SCREAMING_SNAKE_CASE : List[str] = outputs['''hidden_states''']
SCREAMING_SNAKE_CASE : List[Any] = outputs['''attentions''']
self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Dict = getattr(
self.model_tester , '''expected_num_hidden_layers''' , self.model_tester.num_hidden_layers + 1 )
self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ )
self.assertListEqual(
list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , )
self.assertEqual(len(lowerCamelCase_ ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , )
@slow
def __lowerCAmelCase ( self :Any ) -> Dict:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Union[str, Any] = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' )
self.assertIsNotNone(lowerCamelCase_ )
def __lowerCAmelCase ( self :Tuple ) -> Tuple:
'''simple docstring'''
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common()
SCREAMING_SNAKE_CASE : str = True
SCREAMING_SNAKE_CASE : List[str] = getattr(self.model_tester , '''decoder_seq_length''' , self.model_tester.seq_length )
SCREAMING_SNAKE_CASE : List[str] = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length )
SCREAMING_SNAKE_CASE : List[str] = getattr(self.model_tester , '''key_length''' , lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Any = getattr(self.model_tester , '''key_length''' , lowerCamelCase_ )
def check_decoder_attentions_output(lowerCamelCase_ :Optional[Any] ):
SCREAMING_SNAKE_CASE : Any = len(lowerCamelCase_ )
self.assertEqual(out_len % 2 , 0 )
SCREAMING_SNAKE_CASE : int = outputs.decoder_attentions
self.assertEqual(len(lowerCamelCase_ ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , )
def check_encoder_attentions_output(lowerCamelCase_ :Optional[int] ):
SCREAMING_SNAKE_CASE : List[Any] = [
t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions)
]
self.assertEqual(len(lowerCamelCase_ ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , )
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE : Optional[int] = True
SCREAMING_SNAKE_CASE : List[str] = False
SCREAMING_SNAKE_CASE : str = model_class(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : List[Any] = model(self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) )
SCREAMING_SNAKE_CASE : Any = len(lowerCamelCase_ )
self.assertEqual(config.output_hidden_states , lowerCamelCase_ )
check_encoder_attentions_output(lowerCamelCase_ )
if self.is_encoder_decoder:
SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Optional[Any] = model(self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) )
self.assertEqual(config.output_hidden_states , lowerCamelCase_ )
check_decoder_attentions_output(lowerCamelCase_ )
# Check that output attentions can also be changed via the config
del inputs_dict["output_attentions"]
SCREAMING_SNAKE_CASE : List[Any] = True
SCREAMING_SNAKE_CASE : List[str] = model_class(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : str = model(self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) )
self.assertEqual(config.output_hidden_states , lowerCamelCase_ )
check_encoder_attentions_output(lowerCamelCase_ )
# Check attention is always last and order is fine
SCREAMING_SNAKE_CASE : Optional[int] = True
SCREAMING_SNAKE_CASE : str = True
SCREAMING_SNAKE_CASE : Optional[Any] = model_class(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Dict = model(self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) )
self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(lowerCamelCase_ ) )
self.assertEqual(model.config.output_hidden_states , lowerCamelCase_ )
check_encoder_attentions_output(lowerCamelCase_ )
@require_tf
class lowercase__( unittest.TestCase ):
'''simple docstring'''
@slow
def __lowerCAmelCase ( self :int ) -> List[str]:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[Any] = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' )
SCREAMING_SNAKE_CASE : Any = tf.constant([[0, 1, 2, 3, 4, 5]] )
SCREAMING_SNAKE_CASE : List[Any] = model(lowerCamelCase_ )[0]
SCREAMING_SNAKE_CASE : Optional[Any] = [1, 6, 7_68]
self.assertEqual(output.shape , lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Optional[int] = tf.constant(
[
[
[-0.0_3_4_7_5_4_9_3, -0.4_6_8_6_0_3_4, -0.3_0_6_3_8_8_3_2],
[0.2_2_6_3_7_2_4_8, -0.2_6_9_8_8_6_4_6, -0.7_4_2_3_4_2_4],
[0.1_0_3_2_4_8_6_8, -0.4_5_0_1_3_5_0_8, -0.5_8_2_8_0_7_8_4],
]
] )
tf.debugging.assert_near(output[:, :3, :3] , lowerCamelCase_ , atol=1E-4 )
| 698 | 0 |
'''simple docstring'''
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError
import requests
def UpperCamelCase__ ( a__ = "isbn/0140328726" ):
'''simple docstring'''
_lowerCAmelCase =olid.strip().strip('/' ) # Remove leading/trailing whitespace & slashes
if new_olid.count('/' ) != 1:
_lowerCAmelCase =F'''{olid} is not a valid Open Library olid'''
raise ValueError(a__ )
return requests.get(F'''https://openlibrary.org/{new_olid}.json''' ).json()
def UpperCamelCase__ ( a__ ):
'''simple docstring'''
_lowerCAmelCase ={
'title': 'Title',
'publish_date': 'Publish date',
'authors': 'Authors',
'number_of_pages': 'Number of pages:',
'first_sentence': 'First sentence',
'isbn_10': 'ISBN (10)',
'isbn_13': 'ISBN (13)',
}
_lowerCAmelCase ={better_key: ol_book_data[key] for key, better_key in desired_keys.items()}
_lowerCAmelCase =[
get_openlibrary_data(author['key'] )['name'] for author in data['Authors']
]
_lowerCAmelCase =data['First sentence']['value']
for key, value in data.items():
if isinstance(a__ , a__ ):
_lowerCAmelCase =', '.join(a__ )
return data
if __name__ == "__main__":
import doctest
doctest.testmod()
while True:
lowercase_ = input('''\nEnter the ISBN code to search (or \'quit\' to stop): ''').strip()
if isbn.lower() in ("", "q", "quit", "exit", "stop"):
break
if len(isbn) not in (10, 13) or not isbn.isdigit():
print(F'Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.')
continue
print(F'\nSearching Open Library for ISBN: {isbn}...\n')
try:
lowercase_ = summarize_book(get_openlibrary_data(F'isbn/{isbn}'))
print('''\n'''.join(F'{key}: {value}' for key, value in book_summary.items()))
except JSONDecodeError: # Workaround for requests.exceptions.RequestException:
print(F'Sorry, there are no results for ISBN: {isbn}.')
| 58 | '''simple docstring'''
import argparse
import glob
import logging
import os
import time
from argparse import Namespace
import numpy as np
import torch
from lightning_base import BaseTransformer, add_generic_args, generic_train
from torch.utils.data import DataLoader, TensorDataset
from transformers import glue_compute_metrics as compute_metrics
from transformers import glue_convert_examples_to_features as convert_examples_to_features
from transformers import glue_output_modes, glue_tasks_num_labels
from transformers import glue_processors as processors
lowercase_ = logging.getLogger(__name__)
class SCREAMING_SNAKE_CASE ( __lowercase):
"""simple docstring"""
lowercase : int = 'sequence-classification'
def __init__( self , __A ) -> List[Any]:
if type(__A ) == dict:
_lowerCAmelCase =Namespace(**__A )
_lowerCAmelCase =glue_output_modes[hparams.task]
_lowerCAmelCase =glue_tasks_num_labels[hparams.task]
super().__init__(__A , __A , self.mode )
def UpperCamelCase__ ( self , **__A ) -> Any:
return self.model(**__A )
def UpperCamelCase__ ( self , __A , __A ) -> Union[str, Any]:
_lowerCAmelCase ={'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_lowerCAmelCase =batch[2] if self.config.model_type in ['bert', 'xlnet', 'albert'] else None
_lowerCAmelCase =self(**__A )
_lowerCAmelCase =outputs[0]
_lowerCAmelCase =self.trainer.lr_schedulers[0]['scheduler']
_lowerCAmelCase ={'loss': loss, 'rate': lr_scheduler.get_last_lr()[-1]}
return {"loss": loss, "log": tensorboard_logs}
def UpperCamelCase__ ( self ) -> Any:
_lowerCAmelCase =self.hparams
_lowerCAmelCase =processors[args.task]()
_lowerCAmelCase =processor.get_labels()
for mode in ["train", "dev"]:
_lowerCAmelCase =self._feature_file(__A )
if os.path.exists(__A ) and not args.overwrite_cache:
logger.info('Loading features from cached file %s' , __A )
else:
logger.info('Creating features from dataset file at %s' , args.data_dir )
_lowerCAmelCase =(
processor.get_dev_examples(args.data_dir )
if mode == 'dev'
else processor.get_train_examples(args.data_dir )
)
_lowerCAmelCase =convert_examples_to_features(
__A , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , )
logger.info('Saving features into cached file %s' , __A )
torch.save(__A , __A )
def UpperCamelCase__ ( self , __A , __A , __A = False ) -> DataLoader:
_lowerCAmelCase ='dev' if mode == 'test' else mode
_lowerCAmelCase =self._feature_file(__A )
logger.info('Loading features from cached file %s' , __A )
_lowerCAmelCase =torch.load(__A )
_lowerCAmelCase =torch.tensor([f.input_ids for f in features] , dtype=torch.long )
_lowerCAmelCase =torch.tensor([f.attention_mask for f in features] , dtype=torch.long )
_lowerCAmelCase =torch.tensor([f.token_type_ids for f in features] , dtype=torch.long )
if self.hparams.glue_output_mode == "classification":
_lowerCAmelCase =torch.tensor([f.label for f in features] , dtype=torch.long )
elif self.hparams.glue_output_mode == "regression":
_lowerCAmelCase =torch.tensor([f.label for f in features] , dtype=torch.float )
return DataLoader(
TensorDataset(__A , __A , __A , __A ) , batch_size=__A , shuffle=__A , )
def UpperCamelCase__ ( self , __A , __A ) -> List[str]:
_lowerCAmelCase ={'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_lowerCAmelCase =batch[2] if self.config.model_type in ['bert', 'xlnet', 'albert'] else None
_lowerCAmelCase =self(**__A )
_lowerCAmelCase , _lowerCAmelCase =outputs[:2]
_lowerCAmelCase =logits.detach().cpu().numpy()
_lowerCAmelCase =inputs['labels'].detach().cpu().numpy()
return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}
def UpperCamelCase__ ( self , __A ) -> tuple:
_lowerCAmelCase =torch.stack([x['val_loss'] for x in outputs] ).mean().detach().cpu().item()
_lowerCAmelCase =np.concatenate([x['pred'] for x in outputs] , axis=0 )
if self.hparams.glue_output_mode == "classification":
_lowerCAmelCase =np.argmax(__A , axis=1 )
elif self.hparams.glue_output_mode == "regression":
_lowerCAmelCase =np.squeeze(__A )
_lowerCAmelCase =np.concatenate([x['target'] for x in outputs] , axis=0 )
_lowerCAmelCase =[[] for _ in range(out_label_ids.shape[0] )]
_lowerCAmelCase =[[] for _ in range(out_label_ids.shape[0] )]
_lowerCAmelCase ={**{'val_loss': val_loss_mean}, **compute_metrics(self.hparams.task , __A , __A )}
_lowerCAmelCase =dict(results.items() )
_lowerCAmelCase =results
return ret, preds_list, out_label_list
def UpperCamelCase__ ( self , __A ) -> dict:
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase =self._eval_end(__A )
_lowerCAmelCase =ret['log']
return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
def UpperCamelCase__ ( self , __A ) -> dict:
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase =self._eval_end(__A )
_lowerCAmelCase =ret['log']
# `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss`
return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
@staticmethod
def UpperCamelCase__ ( __A , __A ) -> Any:
BaseTransformer.add_model_specific_args(__A , __A )
parser.add_argument(
'--max_seq_length' , default=128 , type=__A , help=(
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
) , )
parser.add_argument(
'--task' , default='' , type=__A , required=__A , help='The GLUE task to run' , )
parser.add_argument(
'--gpus' , default=0 , type=__A , help='The number of GPUs allocated for this, it is by default 0 meaning none' , )
parser.add_argument(
'--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' )
return parser
def UpperCamelCase__ ( ):
'''simple docstring'''
_lowerCAmelCase =argparse.ArgumentParser()
add_generic_args(a__ , os.getcwd() )
_lowerCAmelCase =GLUETransformer.add_model_specific_args(a__ , os.getcwd() )
_lowerCAmelCase =parser.parse_args()
# If output_dir not provided, a folder will be generated in pwd
if args.output_dir is None:
_lowerCAmelCase =os.path.join(
'./results' , F'''{args.task}_{time.strftime('%Y%m%d_%H%M%S' )}''' , )
os.makedirs(args.output_dir )
_lowerCAmelCase =GLUETransformer(a__ )
_lowerCAmelCase =generic_train(a__ , a__ )
# Optionally, predict on dev set and write to output_dir
if args.do_predict:
_lowerCAmelCase =sorted(glob.glob(os.path.join(args.output_dir , 'checkpoint-epoch=*.ckpt' ) , recursive=a__ ) )
_lowerCAmelCase =model.load_from_checkpoint(checkpoints[-1] )
return trainer.test(a__ )
if __name__ == "__main__":
main()
| 58 | 1 |
'''simple docstring'''
import json
import os
from typing import Dict, List, Optional, Tuple
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
_UpperCAmelCase : Any = logging.get_logger(__name__)
_UpperCAmelCase : int = {
"""vocab_file""": """vocab.json""",
"""tokenizer_config_file""": """tokenizer_config.json""",
"""merges_file""": """merges.txt""",
}
_UpperCAmelCase : Union[str, Any] = {
"""vocab_file""": {
"""facebook/s2t-wav2vec2-large-en-de""": (
"""https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json"""
),
},
"""tokenizer_config_file""": {
"""facebook/s2t-wav2vec2-large-en-de""": (
"""https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json"""
),
},
"""merges_file""": {
"""facebook/s2t-wav2vec2-large-en-de""": (
"""https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt"""
),
},
}
_UpperCAmelCase : Dict = """</w>"""
_UpperCAmelCase : Optional[Any] = """@@ """
def snake_case__ ( UpperCamelCase ) -> Any:
_UpperCamelCase : List[str] = set()
_UpperCamelCase : int = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
_UpperCamelCase : Dict = char
return pairs
# Speech2Text2 has no max input length
_UpperCAmelCase : Optional[Any] = {"""facebook/s2t-wav2vec2-large-en-de""": 1024}
class UpperCAmelCase ( a_ ):
"""simple docstring"""
A__ : List[Any] = VOCAB_FILES_NAMES
A__ : List[Any] = PRETRAINED_VOCAB_FILES_MAP
A__ : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
A__ : int = ['input_ids', 'attention_mask']
def __init__( self , _snake_case , _snake_case="<s>" , _snake_case="<pad>" , _snake_case="</s>" , _snake_case="<unk>" , _snake_case=False , _snake_case=None , **_snake_case , ) -> List[str]:
super().__init__(
unk_token=_snake_case , bos_token=_snake_case , eos_token=_snake_case , pad_token=_snake_case , do_lower_case=_snake_case , **_snake_case , )
_UpperCamelCase : List[Any] = do_lower_case
with open(_snake_case , encoding='''utf-8''' ) as vocab_handle:
_UpperCamelCase : Optional[int] = json.load(_snake_case )
_UpperCamelCase : List[str] = {v: k for k, v in self.encoder.items()}
if merges_file is None:
logger.info(F'''No merges files provided. {self.__class__.__name__} can only be used for decoding.''' )
_UpperCamelCase : int = None
_UpperCamelCase : Optional[int] = None
else:
with open(_snake_case , encoding='''utf-8''' ) as merges_handle:
_UpperCamelCase : List[str] = merges_handle.read().split('''\n''' )[:-1]
_UpperCamelCase : int = [tuple(merge.split()[:2] ) for merge in merges]
_UpperCamelCase : List[Any] = dict(zip(_snake_case , range(len(_snake_case ) ) ) )
_UpperCamelCase : Optional[int] = {}
@property
def _lowercase ( self ) -> int:
return len(self.decoder )
def _lowercase ( self ) -> Dict:
return dict(self.encoder , **self.added_tokens_encoder )
def _lowercase ( self , _snake_case ) -> List[str]:
_UpperCamelCase : Optional[int] = tuple(token[:-1] ) + (token[-1] + BPE_TOKEN_MERGES,)
if token in self.cache:
return self.cache[token]
_UpperCamelCase : Any = get_pairs(_snake_case )
if not pairs:
return token
while True:
_UpperCamelCase : Dict = min(_snake_case , key=lambda _snake_case : self.bpe_ranks.get(_snake_case , float('''inf''' ) ) )
if bigram not in self.bpe_ranks:
break
_UpperCamelCase, _UpperCamelCase : Optional[Any] = bigram
_UpperCamelCase : str = []
_UpperCamelCase : List[str] = 0
while i < len(_snake_case ):
try:
_UpperCamelCase : List[str] = word.index(_snake_case , _snake_case )
except ValueError:
new_word.extend(word[i:] )
break
else:
new_word.extend(word[i:j] )
_UpperCamelCase : Optional[Any] = j
if word[i] == first and i < len(_snake_case ) - 1 and word[i + 1] == second:
new_word.append(first + second )
i += 2
else:
new_word.append(word[i] )
i += 1
_UpperCamelCase : Optional[int] = tuple(_snake_case )
_UpperCamelCase : str = new_word
if len(_snake_case ) == 1:
break
else:
_UpperCamelCase : List[str] = get_pairs(_snake_case )
_UpperCamelCase : List[Any] = ''' '''.join(_snake_case )
if word == "\n " + BPE_TOKEN_MERGES:
_UpperCamelCase : List[Any] = '''\n''' + BPE_TOKEN_MERGES
if word.endswith(_snake_case ):
_UpperCamelCase : Dict = word.replace(_snake_case , '''''' )
_UpperCamelCase : int = word.replace(''' ''' , _snake_case )
_UpperCamelCase : Any = word
return word
def _lowercase ( self , _snake_case ) -> Dict:
if self.bpe_ranks is None:
raise ValueError(
'''This tokenizer was instantiated without a `merges.txt` file, so'''
''' that it can only be used for decoding, not for encoding.'''
'''Make sure to provide `merges.txt` file at instantiation to enable '''
'''encoding.''' )
if self.do_lower_case:
_UpperCamelCase : Tuple = text.lower()
_UpperCamelCase : Any = text.split()
_UpperCamelCase : Union[str, Any] = []
for token in text:
if token:
split_tokens.extend(list(self.bpe(_snake_case ).split(''' ''' ) ) )
return split_tokens
def _lowercase ( self , _snake_case ) -> int:
return self.encoder.get(_snake_case , self.encoder.get(self.unk_token ) )
def _lowercase ( self , _snake_case ) -> str:
_UpperCamelCase : str = self.decoder.get(_snake_case , self.unk_token )
return result
def _lowercase ( self , _snake_case ) -> str:
_UpperCamelCase : Optional[int] = ''' '''.join(_snake_case )
# make sure @@ tokens are concatenated
_UpperCamelCase : List[Any] = ''''''.join(string.split(_snake_case ) )
return string
def _lowercase ( self , _snake_case , _snake_case = None ) -> Tuple[str]:
if not os.path.isdir(_snake_case ):
logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' )
return
_UpperCamelCase : int = os.path.join(
_snake_case , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
_UpperCamelCase : Any = os.path.join(
_snake_case , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] )
with open(_snake_case , '''w''' , encoding='''utf-8''' ) as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=_snake_case , ensure_ascii=_snake_case ) + '''\n''' )
_UpperCamelCase : Tuple = 0
if self.bpe_ranks is None:
return (vocab_file,)
with open(_snake_case , '''w''' , encoding='''utf-8''' ) as writer:
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _snake_case : kv[1] ):
if index != token_index:
logger.warning(
F'''Saving vocabulary to {merges_file}: BPE merge indices are not consecutive.'''
''' Please check that the tokenizer is not corrupted!''' )
_UpperCamelCase : str = token_index
writer.write(''' '''.join(_snake_case ) + '''\n''' )
index += 1
return (vocab_file, merges_file)
| 683 |
'''simple docstring'''
import os
import pytest
from datasets import (
get_dataset_config_info,
get_dataset_config_names,
get_dataset_infos,
get_dataset_split_names,
inspect_dataset,
inspect_metric,
)
_UpperCAmelCase : Optional[int] = pytest.mark.integration
@pytest.mark.parametrize('''path''' ,['''paws''', '''csv'''] )
def snake_case__ ( UpperCamelCase ,UpperCamelCase ) -> Dict:
inspect_dataset(UpperCamelCase ,UpperCamelCase )
_UpperCamelCase : Optional[Any] = path + '''.py'''
assert script_name in os.listdir(UpperCamelCase )
assert "__pycache__" not in os.listdir(UpperCamelCase )
@pytest.mark.filterwarnings('''ignore:inspect_metric is deprecated:FutureWarning''' )
@pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' )
@pytest.mark.parametrize('''path''' ,['''accuracy'''] )
def snake_case__ ( UpperCamelCase ,UpperCamelCase ) -> int:
inspect_metric(UpperCamelCase ,UpperCamelCase )
_UpperCamelCase : List[str] = path + '''.py'''
assert script_name in os.listdir(UpperCamelCase )
assert "__pycache__" not in os.listdir(UpperCamelCase )
@pytest.mark.parametrize(
'''path, config_name, expected_splits''' ,[
('''squad''', '''plain_text''', ['''train''', '''validation''']),
('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']),
('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']),
] ,)
def snake_case__ ( UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) -> int:
_UpperCamelCase : List[str] = get_dataset_config_info(UpperCamelCase ,config_name=UpperCamelCase )
assert info.config_name == config_name
assert list(info.splits.keys() ) == expected_splits
@pytest.mark.parametrize(
'''path, config_name, expected_exception''' ,[
('''paws''', None, ValueError),
] ,)
def snake_case__ ( UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) -> List[str]:
with pytest.raises(UpperCamelCase ):
get_dataset_config_info(UpperCamelCase ,config_name=UpperCamelCase )
@pytest.mark.parametrize(
'''path, expected''' ,[
('''squad''', '''plain_text'''),
('''acronym_identification''', '''default'''),
('''lhoestq/squad''', '''plain_text'''),
('''lhoestq/test''', '''default'''),
('''lhoestq/demo1''', '''lhoestq--demo1'''),
('''dalle-mini/wit''', '''dalle-mini--wit'''),
] ,)
def snake_case__ ( UpperCamelCase ,UpperCamelCase ) -> Union[str, Any]:
_UpperCamelCase : int = get_dataset_config_names(UpperCamelCase )
assert expected in config_names
@pytest.mark.parametrize(
'''path, expected_configs, expected_splits_in_first_config''' ,[
('''squad''', ['''plain_text'''], ['''train''', '''validation''']),
('''dalle-mini/wit''', ['''dalle-mini--wit'''], ['''train''']),
('''paws''', ['''labeled_final''', '''labeled_swap''', '''unlabeled_final'''], ['''train''', '''test''', '''validation''']),
] ,)
def snake_case__ ( UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) -> Dict:
_UpperCamelCase : Dict = get_dataset_infos(UpperCamelCase )
assert list(infos.keys() ) == expected_configs
_UpperCamelCase : Dict = expected_configs[0]
assert expected_config in infos
_UpperCamelCase : Any = infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys() ) == expected_splits_in_first_config
@pytest.mark.parametrize(
'''path, expected_config, expected_splits''' ,[
('''squad''', '''plain_text''', ['''train''', '''validation''']),
('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']),
('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']),
] ,)
def snake_case__ ( UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) -> Union[str, Any]:
_UpperCamelCase : List[Any] = get_dataset_infos(UpperCamelCase )
assert expected_config in infos
_UpperCamelCase : Union[str, Any] = infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys() ) == expected_splits
@pytest.mark.parametrize(
'''path, config_name, expected_exception''' ,[
('''paws''', None, ValueError),
] ,)
def snake_case__ ( UpperCamelCase ,UpperCamelCase ,UpperCamelCase ) -> List[Any]:
with pytest.raises(UpperCamelCase ):
get_dataset_split_names(UpperCamelCase ,config_name=UpperCamelCase )
| 683 | 1 |
"""simple docstring"""
from __future__ import annotations
from typing import Dict
from ...configuration_utils import PretrainedConfig
_UpperCamelCase = {
"""susnato/ernie-m-base_pytorch""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json""",
"""susnato/ernie-m-large_pytorch""": """https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json""",
}
class lowerCamelCase__ ( snake_case ):
SCREAMING_SNAKE_CASE = '''ernie_m'''
SCREAMING_SNAKE_CASE = {'''dropout''': '''classifier_dropout''', '''num_classes''': '''num_labels'''}
def __init__( self ,A = 250_002 ,A = 768 ,A = 12 ,A = 12 ,A = 3_072 ,A = "gelu" ,A = 0.1 ,A = 0.1 ,A = 514 ,A = 0.02 ,A = 1 ,A = 1e-0_5 ,A=None ,A=False ,A=0.0 ,**A ,):
super().__init__(pad_token_id=A ,**A )
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 = initializer_range
UpperCAmelCase = layer_norm_eps
UpperCAmelCase = classifier_dropout
UpperCAmelCase = is_decoder
UpperCAmelCase = act_dropout
| 714 |
"""simple docstring"""
def _a ( _snake_case ): # noqa: E741
"""simple docstring"""
UpperCAmelCase = len(_snake_case )
UpperCAmelCase = 0
UpperCAmelCase = [0] * n
UpperCAmelCase = [False] * n
UpperCAmelCase = [False] * n
def dfs(_snake_case , _snake_case , _snake_case , _snake_case ):
if parent == root:
out_edge_count += 1
UpperCAmelCase = True
UpperCAmelCase = at
for to in l[at]:
if to == parent:
pass
elif not visited[to]:
UpperCAmelCase = dfs(_snake_case , _snake_case , _snake_case , _snake_case )
UpperCAmelCase = min(low[at] , low[to] )
# AP found via bridge
if at < low[to]:
UpperCAmelCase = True
# AP found via cycle
if at == low[to]:
UpperCAmelCase = True
else:
UpperCAmelCase = min(low[at] , _snake_case )
return out_edge_count
for i in range(_snake_case ):
if not visited[i]:
UpperCAmelCase = 0
UpperCAmelCase = dfs(_snake_case , _snake_case , -1 , _snake_case )
UpperCAmelCase = out_edge_count > 1
for x in range(len(_snake_case ) ):
if is_art[x] is True:
print(_snake_case )
# Adjacency list of graph
_UpperCamelCase = {
0: [1, 2],
1: [0, 2],
2: [0, 1, 3, 5],
3: [2, 4],
4: [3],
5: [2, 6, 8],
6: [5, 7],
7: [6, 8],
8: [5, 7],
}
compute_ap(data)
| 74 | 0 |
import math
from typing import Any, Callable, List, Optional, Tuple, Union
import numpy as np
import torch
from ...models import TaFilmDecoder
from ...schedulers import DDPMScheduler
from ...utils import is_onnx_available, logging, randn_tensor
if is_onnx_available():
from ..onnx_utils import OnnxRuntimeModel
from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline
from .continous_encoder import SpectrogramContEncoder
from .notes_encoder import SpectrogramNotesEncoder
_lowercase = logging.get_logger(__name__) # pylint: disable=invalid-name
_lowercase = 256
class lowerCamelCase__ ( A__ ):
__lowerCamelCase = ["""melgan"""]
def __init__( self : Optional[Any] , __a : SpectrogramNotesEncoder , __a : SpectrogramContEncoder , __a : TaFilmDecoder , __a : DDPMScheduler , __a : OnnxRuntimeModel if is_onnx_available() else Any , ):
'''simple docstring'''
super().__init__()
# From MELGAN
lowerCamelCase__: Tuple = math.log(1e-5 ) # Matches MelGAN training.
lowerCamelCase__: Optional[int] = 4.0 # Largest value for most examples
lowerCamelCase__: List[str] = 128
self.register_modules(
notes_encoder=__a , continuous_encoder=__a , decoder=__a , scheduler=__a , melgan=__a , )
def lowerCamelCase_ ( self : Optional[Any] , __a : Tuple , __a : int=(-1.0, 1.0) , __a : List[str]=False ):
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: Tuple = output_range
if clip:
lowerCamelCase__: Dict = torch.clip(__a , self.min_value , self.max_value )
# Scale to [0, 1].
lowerCamelCase__: Optional[int] = (features - self.min_value) / (self.max_value - self.min_value)
# Scale to [min_out, max_out].
return zero_one * (max_out - min_out) + min_out
def lowerCamelCase_ ( self : Optional[Any] , __a : int , __a : Optional[Any]=(-1.0, 1.0) , __a : int=False ):
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: Optional[Any] = input_range
lowerCamelCase__: Optional[Any] = torch.clip(__a , __a , __a ) if clip else outputs
# Scale to [0, 1].
lowerCamelCase__: Union[str, Any] = (outputs - min_out) / (max_out - min_out)
# Scale to [self.min_value, self.max_value].
return zero_one * (self.max_value - self.min_value) + self.min_value
def lowerCamelCase_ ( self : str , __a : List[str] , __a : str , __a : Optional[Any] ):
'''simple docstring'''
lowerCamelCase__: Optional[int] = input_tokens > 0
lowerCamelCase__ , lowerCamelCase__: int = self.notes_encoder(
encoder_input_tokens=__a , encoder_inputs_mask=__a )
lowerCamelCase__ , lowerCamelCase__: Tuple = self.continuous_encoder(
encoder_inputs=__a , encoder_inputs_mask=__a )
return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)]
def lowerCamelCase_ ( self : str , __a : Tuple , __a : Dict , __a : List[str] ):
'''simple docstring'''
lowerCamelCase__: str = noise_time
if not torch.is_tensor(__a ):
lowerCamelCase__: List[Any] = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device )
elif torch.is_tensor(__a ) and len(timesteps.shape ) == 0:
lowerCamelCase__: Optional[Any] = timesteps[None].to(input_tokens.device )
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
lowerCamelCase__: int = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device )
lowerCamelCase__: str = self.decoder(
encodings_and_masks=__a , decoder_input_tokens=__a , decoder_noise_time=__a )
return logits
@torch.no_grad()
def __call__( self : Optional[int] , __a : List[List[int]] , __a : Optional[torch.Generator] = None , __a : int = 100 , __a : bool = True , __a : str = "numpy" , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , ):
'''simple docstring'''
if (callback_steps is None) or (
callback_steps is not None and (not isinstance(__a , __a ) or callback_steps <= 0)
):
raise ValueError(
f"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
f""" {type(__a )}.""" )
lowerCamelCase__: Union[str, Any] = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa )
lowerCamelCase__: str = np.zeros([1, 0, self.n_dims] , np.floataa )
lowerCamelCase__: str = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=__a , device=self.device )
for i, encoder_input_tokens in enumerate(__a ):
if i == 0:
lowerCamelCase__: Any = torch.from_numpy(pred_mel[:1].copy() ).to(
device=self.device , dtype=self.decoder.dtype )
# The first chunk has no previous context.
lowerCamelCase__: Dict = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=__a , device=self.device )
else:
# The full song pipeline does not feed in a context feature, so the mask
# will be all 0s after the feature converter. Because we know we're
# feeding in a full context chunk from the previous prediction, set it
# to all 1s.
lowerCamelCase__: List[Any] = ones
lowerCamelCase__: List[Any] = self.scale_features(
__a , output_range=[-1.0, 1.0] , clip=__a )
lowerCamelCase__: List[str] = self.encode(
input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=__a , continuous_mask=__a , )
# Sample encoder_continuous_inputs shaped gaussian noise to begin loop
lowerCamelCase__: Any = randn_tensor(
shape=encoder_continuous_inputs.shape , generator=__a , device=self.device , dtype=self.decoder.dtype , )
# set step values
self.scheduler.set_timesteps(__a )
# Denoising diffusion loop
for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ):
lowerCamelCase__: List[str] = self.decode(
encodings_and_masks=__a , input_tokens=__a , noise_time=t / self.scheduler.config.num_train_timesteps , )
# Compute previous output: x_t -> x_t-1
lowerCamelCase__: Any = self.scheduler.step(__a , __a , __a , generator=__a ).prev_sample
lowerCamelCase__: List[str] = self.scale_to_features(__a , input_range=[-1.0, 1.0] )
lowerCamelCase__: Optional[Any] = mel[:1]
lowerCamelCase__: Any = mel.cpu().float().numpy()
lowerCamelCase__: Tuple = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 )
# call the callback, if provided
if callback is not None and i % callback_steps == 0:
callback(__a , __a )
logger.info("""Generated segment""" , __a )
if output_type == "numpy" and not is_onnx_available():
raise ValueError(
"""Cannot return output in 'np' format if ONNX is not available. Make sure to have ONNX installed or set 'output_type' to 'mel'.""" )
elif output_type == "numpy" and self.melgan is None:
raise ValueError(
"""Cannot return output in 'np' format if melgan component is not defined. Make sure to define `self.melgan` or set 'output_type' to 'mel'.""" )
if output_type == "numpy":
lowerCamelCase__: Optional[int] = self.melgan(input_features=full_pred_mel.astype(np.floataa ) )
else:
lowerCamelCase__: str = full_pred_mel
if not return_dict:
return (output,)
return AudioPipelineOutput(audios=__a )
| 306 |
from __future__ import annotations
import unittest
import numpy as np
from transformers import OPTConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel
def __lowerCAmelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=None , _UpperCamelCase=None ) -> Any:
'''simple docstring'''
if attention_mask is None:
lowerCamelCase__: List[str] = tf.cast(tf.math.not_equal(_UpperCamelCase , config.pad_token_id ) , tf.inta )
return {"input_ids": input_ids, "attention_mask": attention_mask}
@require_tf
class lowerCamelCase__ :
__lowerCamelCase = OPTConfig
__lowerCamelCase = {}
__lowerCamelCase = """gelu"""
def __init__( self : Union[str, Any] , __a : List[Any] , __a : Dict=13 , __a : Dict=7 , __a : Optional[Any]=True , __a : Any=False , __a : Tuple=99 , __a : Optional[int]=16 , __a : Any=2 , __a : Optional[Any]=4 , __a : Union[str, Any]=4 , __a : Tuple="gelu" , __a : Optional[int]=0.1 , __a : int=0.1 , __a : List[Any]=20 , __a : Tuple=2 , __a : str=1 , __a : str=0 , __a : List[Any]=16 , __a : Optional[Any]=16 , ):
'''simple docstring'''
lowerCamelCase__: List[str] = parent
lowerCamelCase__: List[str] = batch_size
lowerCamelCase__: Dict = seq_length
lowerCamelCase__: List[str] = is_training
lowerCamelCase__: Dict = use_labels
lowerCamelCase__: Union[str, Any] = vocab_size
lowerCamelCase__: Union[str, Any] = hidden_size
lowerCamelCase__: Any = num_hidden_layers
lowerCamelCase__: Union[str, Any] = num_attention_heads
lowerCamelCase__: Tuple = intermediate_size
lowerCamelCase__: Optional[int] = hidden_act
lowerCamelCase__: Union[str, Any] = hidden_dropout_prob
lowerCamelCase__: str = attention_probs_dropout_prob
lowerCamelCase__: List[str] = max_position_embeddings
lowerCamelCase__: Tuple = eos_token_id
lowerCamelCase__: Any = pad_token_id
lowerCamelCase__: str = bos_token_id
lowerCamelCase__: Optional[int] = embed_dim
lowerCamelCase__: Union[str, Any] = word_embed_proj_dim
lowerCamelCase__: List[Any] = False
def lowerCamelCase_ ( self : List[str] ):
'''simple docstring'''
lowerCamelCase__: List[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size )
lowerCamelCase__: Tuple = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 )
lowerCamelCase__: Optional[int] = tf.concat([input_ids, eos_tensor] , axis=1 )
lowerCamelCase__: Union[str, Any] = self.config_cls(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=__a , **self.config_updates , )
lowerCamelCase__: Optional[Any] = prepare_opt_inputs_dict(__a , __a )
return config, inputs_dict
def lowerCamelCase_ ( self : str , __a : Optional[Any] , __a : Optional[int] ):
'''simple docstring'''
lowerCamelCase__: Optional[Any] = TFOPTModel(config=__a )
lowerCamelCase__: Optional[Any] = inputs_dict["""input_ids"""]
lowerCamelCase__: Dict = input_ids[:1, :]
lowerCamelCase__: Any = inputs_dict["""attention_mask"""][:1, :]
lowerCamelCase__: Any = 1
# first forward pass
lowerCamelCase__: str = model(__a , attention_mask=__a , use_cache=__a )
lowerCamelCase__ , lowerCamelCase__: Dict = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
lowerCamelCase__: Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size )
lowerCamelCase__: Dict = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta )
# append to next input_ids and
lowerCamelCase__: str = tf.concat([input_ids, next_tokens] , axis=-1 )
lowerCamelCase__: int = tf.concat([attention_mask, next_attn_mask] , axis=-1 )
lowerCamelCase__: Any = model(__a , attention_mask=__a )[0]
lowerCamelCase__: Any = model(__a , attention_mask=__a , past_key_values=__a )[0]
self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] )
# select random slice
lowerCamelCase__: str = int(ids_tensor((1,) , output_from_past.shape[-1] ) )
lowerCamelCase__: Optional[int] = output_from_no_past[:, -3:, random_slice_idx]
lowerCamelCase__: List[str] = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(__a , __a , rtol=1e-3 )
@require_tf
class lowerCamelCase__ ( A__ , A__ , unittest.TestCase ):
__lowerCamelCase = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else ()
__lowerCamelCase = (TFOPTForCausalLM,) if is_tf_available() else ()
__lowerCamelCase = (
{"""feature-extraction""": TFOPTModel, """text-generation""": TFOPTForCausalLM} if is_tf_available() else {}
)
__lowerCamelCase = False
__lowerCamelCase = False
__lowerCamelCase = False
__lowerCamelCase = 10
def lowerCamelCase_ ( self : Tuple ):
'''simple docstring'''
lowerCamelCase__: int = TFOPTModelTester(self )
lowerCamelCase__: Tuple = ConfigTester(self , config_class=__a )
def lowerCamelCase_ ( self : str ):
'''simple docstring'''
self.config_tester.run_common_tests()
def lowerCamelCase_ ( self : Dict ):
'''simple docstring'''
lowerCamelCase__: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*__a )
def lowerCamelCase_ ( self : Dict ):
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: str = self.model_tester.prepare_config_and_inputs_for_common()
def _get_word_embedding_weight(__a : Optional[int] , __a : Dict ):
if hasattr(__a , """weight""" ):
return embedding_layer.weight
else:
# Here we build the word embeddings weights if not exists.
# And then we retry to get the attribute once built.
model.build()
if hasattr(__a , """weight""" ):
return embedding_layer.weight
else:
return None
for model_class in self.all_model_classes:
for size in [config.vocab_size - 10, config.vocab_size + 10]:
# build the embeddings
lowerCamelCase__: int = model_class(config=__a )
lowerCamelCase__: Tuple = _get_word_embedding_weight(__a , model.get_input_embeddings() )
lowerCamelCase__: Optional[int] = _get_word_embedding_weight(__a , model.get_output_embeddings() )
# reshape the embeddings
model.resize_token_embeddings(__a )
lowerCamelCase__: str = _get_word_embedding_weight(__a , model.get_input_embeddings() )
lowerCamelCase__: List[str] = _get_word_embedding_weight(__a , model.get_output_embeddings() )
# check that the resized embeddings size matches the desired size.
lowerCamelCase__: Any = size if size is not None else config.vocab_size
self.assertEqual(new_input_embeddings.shape[0] , __a )
# check that weights remain the same after resizing
lowerCamelCase__: Optional[Any] = True
for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ):
if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0:
lowerCamelCase__: Any = False
self.assertTrue(__a )
if old_output_embeddings is not None and new_output_embeddings is not None:
self.assertEqual(new_output_embeddings.shape[0] , __a )
lowerCamelCase__: List[Any] = True
for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ):
if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0:
lowerCamelCase__: List[Any] = False
self.assertTrue(__a )
def __lowerCAmelCase ( _UpperCamelCase ) -> Optional[Any]:
'''simple docstring'''
return tf.constant(_UpperCamelCase , dtype=tf.intaa )
@require_tf
class lowerCamelCase__ ( unittest.TestCase ):
__lowerCamelCase = 99
def lowerCamelCase_ ( self : Dict ):
'''simple docstring'''
lowerCamelCase__: int = tf.ones((4, 1) , dtype=tf.intaa ) * 2
lowerCamelCase__: Optional[int] = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 )
lowerCamelCase__: Any = input_ids.shape[0]
lowerCamelCase__: List[str] = OPTConfig(
vocab_size=self.vocab_size , hidden_size=24 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , )
return config, input_ids, batch_size
@require_sentencepiece
@require_tf
class lowerCamelCase__ ( unittest.TestCase ):
@slow
def lowerCamelCase_ ( self : List[str] ):
'''simple docstring'''
lowerCamelCase__: int = TFOPTModel.from_pretrained("""facebook/opt-350m""" )
lowerCamelCase__: List[Any] = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] )
lowerCamelCase__: Optional[Any] = tf.not_equal(__a , model.config.pad_token_id )
with tf.GradientTape():
lowerCamelCase__: str = model(input_ids=__a , attention_mask=__a ).last_hidden_state
lowerCamelCase__: str = (1, 11, 512)
self.assertEqual(output.shape , __a )
lowerCamelCase__: str = tf.constant(
[[-0.2_873, -1.9_218, -0.3_033], [-1.2_710, -0.1_338, -0.1_902], [0.4_095, 0.1_214, -1.3_121]] )
self.assertTrue(np.allclose(output[:, :3, :3] , __a , atol=4e-3 ) )
lowerCamelCase__: Optional[int] = tf.function(__a , jit_compile=__a )
lowerCamelCase__: List[Any] = xla_generate(__a , __a )[0]
self.assertTrue(np.allclose(output[:, :3, :3] , __a , atol=4e-2 ) )
@require_tf
@slow
class lowerCamelCase__ ( unittest.TestCase ):
def lowerCamelCase_ ( self : Tuple ):
'''simple docstring'''
super().setUp()
lowerCamelCase__: List[Any] = """facebook/opt-350m"""
def lowerCamelCase_ ( self : Tuple ):
'''simple docstring'''
lowerCamelCase__: Dict = TFOPTForCausalLM.from_pretrained(self.path_model )
lowerCamelCase__: Dict = GPTaTokenizer.from_pretrained(self.path_model )
lowerCamelCase__: Union[str, Any] = [
"""Today is a beautiful day and I want to""",
"""In the city of""",
"""Paris is the capital of France and""",
"""Computers and mobile phones have taken""",
]
# verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
lowerCamelCase__: Union[str, Any] = tokenizer(__a , return_tensors="""tf""" , padding=__a , add_special_tokens=__a )
lowerCamelCase__: Union[str, Any] = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 )
lowerCamelCase__: Dict = tf.constant(
[
[1.3_851, -13.8_923, -10.5_229, -10.7_533, -0.2_309, -10.2_384, -0.5_365, -9.0_947, -5.1_670],
[-4.7_073, -10.6_276, -3.9_415, -21.5_242, -0.2_822, -0.2_822, -0.2_822, -0.2_822, -0.2_822],
[0.6_247, -3.4_229, -8.9_179, -1.4_297, -14.1_650, 1.4_146, -9.0_218, -0.2_703, -0.2_703],
[6.4_783, -1.9_913, -10.7_926, -2.3_336, 1.5_092, -0.9_974, -6.8_213, 1.3_477, 1.3_477],
] )
self.assertTrue(np.allclose(__a , __a , atol=1e-4 ) )
lowerCamelCase__: Any = tf.function(__a , jit_compile=__a )
lowerCamelCase__: List[Any] = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 )
self.assertTrue(np.allclose(__a , __a , atol=1e-4 ) )
@require_tf
@slow
class lowerCamelCase__ ( unittest.TestCase ):
@property
def lowerCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
return [
"Today is a beautiful day and I want",
"In the city of",
"Paris is the capital of France and",
"Computers and mobile phones have taken",
]
def lowerCamelCase_ ( self : int ):
'''simple docstring'''
lowerCamelCase__: Union[str, Any] = """facebook/opt-125m"""
lowerCamelCase__: Dict = [
"""Today is a beautiful day and I want to""",
"""In the city of New York, the city""",
"""Paris is the capital of France and the capital""",
"""Computers and mobile phones have taken over the""",
]
lowerCamelCase__: Any = []
lowerCamelCase__: Optional[Any] = GPTaTokenizer.from_pretrained(__a )
lowerCamelCase__: str = TFOPTForCausalLM.from_pretrained(__a )
for prompt in self.prompts:
lowerCamelCase__: Dict = tokenizer(__a , return_tensors="""tf""" ).input_ids
lowerCamelCase__: Any = model.generate(__a , max_length=10 )
lowerCamelCase__: Optional[int] = tokenizer.batch_decode(__a , skip_special_tokens=__a )
predicted_outputs += generated_string
self.assertListEqual(__a , __a )
def lowerCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
lowerCamelCase__: List[Any] = """facebook/opt-350m"""
lowerCamelCase__: Tuple = GPTaTokenizer.from_pretrained(__a )
lowerCamelCase__: Any = TFOPTForCausalLM.from_pretrained(__a )
lowerCamelCase__: Tuple = """left"""
# use different length sentences to test batching
lowerCamelCase__: Tuple = [
"""Hello, my dog is a little""",
"""Today, I""",
]
lowerCamelCase__: List[Any] = tokenizer(__a , return_tensors="""tf""" , padding=__a )
lowerCamelCase__: Any = inputs["""input_ids"""]
lowerCamelCase__: int = model.generate(input_ids=__a , attention_mask=inputs["""attention_mask"""] )
lowerCamelCase__: Optional[int] = tokenizer(sentences[0] , return_tensors="""tf""" ).input_ids
lowerCamelCase__: Optional[Any] = model.generate(input_ids=__a )
lowerCamelCase__: int = inputs_non_padded.shape[-1] - tf.math.reduce_sum(
tf.cast(inputs["""attention_mask"""][-1] , tf.intaa ) )
lowerCamelCase__: Dict = tokenizer(sentences[1] , return_tensors="""tf""" ).input_ids
lowerCamelCase__: str = model.generate(input_ids=__a , max_length=model.config.max_length - num_paddings )
lowerCamelCase__: List[str] = tokenizer.batch_decode(__a , skip_special_tokens=__a )
lowerCamelCase__: Optional[int] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=__a )
lowerCamelCase__: Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=__a )
lowerCamelCase__: Tuple = [
"""Hello, my dog is a little bit of a dork.\nI'm a little bit""",
"""Today, I was in the middle of a conversation with a friend about the""",
]
self.assertListEqual(__a , __a )
self.assertListEqual(__a , [non_padded_sentence, padded_sentence] )
def lowerCamelCase_ ( self : List[str] ):
'''simple docstring'''
lowerCamelCase__: Dict = """facebook/opt-350m"""
lowerCamelCase__: Tuple = [
"""Today is a beautiful day and I want to""",
"""In the city of San Francisco, the city""",
"""Paris is the capital of France and the capital""",
"""Computers and mobile phones have taken over the""",
]
lowerCamelCase__: Dict = []
lowerCamelCase__: int = GPTaTokenizer.from_pretrained(__a )
lowerCamelCase__: List[Any] = TFOPTForCausalLM.from_pretrained(__a )
for prompt in self.prompts:
lowerCamelCase__: str = tokenizer(__a , return_tensors="""tf""" ).input_ids
lowerCamelCase__: Optional[int] = model.generate(__a , max_length=10 )
lowerCamelCase__: Any = tokenizer.batch_decode(__a , skip_special_tokens=__a )
predicted_outputs += generated_string
self.assertListEqual(__a , __a )
| 306 | 1 |
import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to properly calculate the metrics on the
# validation dataset when in a distributed system, and builds off the
# `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
# - single CPU or single GPU
# - multi GPUS (using PyTorch distributed mode)
# - (multi) TPUs
# - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################
UpperCamelCase = 16
UpperCamelCase = 32
def A ( lowercase__ : Tuple , lowercase__ : Tuple = 16 ) -> Any:
UpperCamelCase__ :Union[str, Any] = AutoTokenizer.from_pretrained("""bert-base-cased""" )
UpperCamelCase__ :Union[str, Any] = load_dataset("""glue""" , """mrpc""" )
def tokenize_function(lowercase__ : int ):
# max_length=None => use the model max length (it's actually the default)
UpperCamelCase__ :Union[str, Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowercase_ , max_length=lowercase_ )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
UpperCamelCase__ :Union[str, Any] = datasets.map(
lowercase_ , batched=lowercase_ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
UpperCamelCase__ :str = tokenized_datasets.rename_column("""label""" , """labels""" )
def collate_fn(lowercase__ : Optional[int] ):
# On TPU it's best to pad everything to the same length or training will be very slow.
UpperCamelCase__ :Tuple = 128 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
UpperCamelCase__ :Any = 16
elif accelerator.mixed_precision != "no":
UpperCamelCase__ :List[Any] = 8
else:
UpperCamelCase__ :Optional[Any] = None
return tokenizer.pad(
lowercase_ , padding="""longest""" , max_length=lowercase_ , pad_to_multiple_of=lowercase_ , return_tensors="""pt""" , )
# Instantiate dataloaders.
UpperCamelCase__ :str = DataLoader(
tokenized_datasets["""train"""] , shuffle=lowercase_ , collate_fn=lowercase_ , batch_size=lowercase_ )
UpperCamelCase__ :Optional[Any] = DataLoader(
tokenized_datasets["""validation"""] , shuffle=lowercase_ , collate_fn=lowercase_ , batch_size=lowercase_ )
return train_dataloader, eval_dataloader
# For testing only
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
UpperCamelCase = mocked_dataloaders # noqa: F811
def A ( lowercase__ : List[str] , lowercase__ : Union[str, Any] ) -> int:
if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , lowercase_ ) == "1":
UpperCamelCase__ :Optional[Any] = 2
# Initialize accelerator
UpperCamelCase__ :Dict = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
UpperCamelCase__ :Tuple = config["lr"]
UpperCamelCase__ :Any = int(config["""num_epochs"""] )
UpperCamelCase__ :Optional[Any] = int(config["""seed"""] )
UpperCamelCase__ :Optional[Any] = int(config["""batch_size"""] )
UpperCamelCase__ :Tuple = evaluate.load("""glue""" , """mrpc""" )
# If the batch size is too big we use gradient accumulation
UpperCamelCase__ :Union[str, Any] = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
UpperCamelCase__ :List[str] = batch_size // MAX_GPU_BATCH_SIZE
UpperCamelCase__ :Dict = MAX_GPU_BATCH_SIZE
set_seed(lowercase_ )
UpperCamelCase__ :List[str] = get_dataloaders(lowercase_ , lowercase_ )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
UpperCamelCase__ :List[Any] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=lowercase_ )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
UpperCamelCase__ :List[str] = model.to(accelerator.device )
# Instantiate optimizer
UpperCamelCase__ :Any = AdamW(params=model.parameters() , lr=lowercase_ )
# Instantiate scheduler
UpperCamelCase__ :Any = get_linear_schedule_with_warmup(
optimizer=lowercase_ , num_warmup_steps=100 , num_training_steps=(len(lowercase_ ) * num_epochs) // gradient_accumulation_steps , )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
UpperCamelCase__ :List[str] = accelerator.prepare(
lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ )
# Now we train the model
for epoch in range(lowercase_ ):
model.train()
for step, batch in enumerate(lowercase_ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
UpperCamelCase__ :List[str] = model(**lowercase_ )
UpperCamelCase__ :str = outputs.loss
UpperCamelCase__ :Tuple = loss / gradient_accumulation_steps
accelerator.backward(lowercase_ )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
UpperCamelCase__ :Dict = 0
for step, batch in enumerate(lowercase_ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
UpperCamelCase__ :List[str] = model(**lowercase_ )
UpperCamelCase__ :List[Any] = outputs.logits.argmax(dim=-1 )
UpperCamelCase__ :Any = accelerator.gather((predictions, batch["""labels"""]) )
# New Code #
# First we check if it's a distributed system
if accelerator.use_distributed:
# Then see if we're on the last batch of our eval dataloader
if step == len(lowercase_ ) - 1:
# Last batch needs to be truncated on distributed systems as it contains additional samples
UpperCamelCase__ :Dict = predictions[: len(eval_dataloader.dataset ) - samples_seen]
UpperCamelCase__ :List[str] = references[: len(eval_dataloader.dataset ) - samples_seen]
else:
# Otherwise we add the number of samples seen
samples_seen += references.shape[0]
# All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`:
# accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=lowercase_ , references=lowercase_ , )
UpperCamelCase__ :Tuple = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"""epoch {epoch}:""" , lowercase_ )
def A ( ) -> int:
UpperCamelCase__ :List[str] = argparse.ArgumentParser(description="""Simple example of training script.""" )
parser.add_argument(
"""--mixed_precision""" , type=lowercase_ , default=lowercase_ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose"""
"""between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."""
"""and an Nvidia Ampere GPU.""" , )
parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" )
UpperCamelCase__ :Optional[Any] = parser.parse_args()
UpperCamelCase__ :Any = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
training_function(lowercase_ , lowercase_ )
if __name__ == "__main__":
main() | 707 |
def A ( lowercase__ : int ) -> bool:
if p < 2:
raise ValueError("""p should not be less than 2!""" )
elif p == 2:
return True
UpperCamelCase__ :Optional[int] = 4
UpperCamelCase__ :int = (1 << p) - 1
for _ in range(p - 2 ):
UpperCamelCase__ :str = ((s * s) - 2) % m
return s == 0
if __name__ == "__main__":
print(lucas_lehmer_test(7))
print(lucas_lehmer_test(11)) | 383 | 0 |
'''simple docstring'''
from typing import Optional, Tuple, Union
import flax
import flax.linen as nn
import jax
import jax.numpy as jnp
from flax.core.frozen_dict import FrozenDict
from ..configuration_utils import ConfigMixin, flax_register_to_config
from ..utils import BaseOutput
from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps
from .modeling_flax_utils import FlaxModelMixin
from .unet_ad_blocks_flax import (
FlaxCrossAttnDownBlockaD,
FlaxDownBlockaD,
FlaxUNetMidBlockaDCrossAttn,
)
@flax.struct.dataclass
class lowercase_ (lowerCamelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : jnp.ndarray
SCREAMING_SNAKE_CASE : jnp.ndarray
class lowercase_ (nn.Module ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : int
SCREAMING_SNAKE_CASE : Tuple[int] = (1_6, 3_2, 9_6, 2_5_6)
SCREAMING_SNAKE_CASE : jnp.dtype = jnp.floataa
def SCREAMING_SNAKE_CASE ( self : Dict ):
__lowercase = nn.Conv(
self.block_out_channels[0] ,kernel_size=(3, 3) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,)
__lowercase = []
for i in range(len(self.block_out_channels ) - 1 ):
__lowercase = self.block_out_channels[i]
__lowercase = self.block_out_channels[i + 1]
__lowercase = nn.Conv(
lowercase__ ,kernel_size=(3, 3) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,)
blocks.append(lowercase__ )
__lowercase = nn.Conv(
lowercase__ ,kernel_size=(3, 3) ,strides=(2, 2) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,)
blocks.append(lowercase__ )
__lowercase = blocks
__lowercase = nn.Conv(
self.conditioning_embedding_channels ,kernel_size=(3, 3) ,padding=((1, 1), (1, 1)) ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,)
def __call__( self : List[str] ,lowercase__ : Optional[int] ):
__lowercase = self.conv_in(lowercase__ )
__lowercase = nn.silu(lowercase__ )
for block in self.blocks:
__lowercase = block(lowercase__ )
__lowercase = nn.silu(lowercase__ )
__lowercase = self.conv_out(lowercase__ )
return embedding
@flax_register_to_config
class lowercase_ (nn.Module , lowerCamelCase__ , lowerCamelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : int = 3_2
SCREAMING_SNAKE_CASE : int = 4
SCREAMING_SNAKE_CASE : Tuple[str] = (
"CrossAttnDownBlock2D",
"CrossAttnDownBlock2D",
"CrossAttnDownBlock2D",
"DownBlock2D",
)
SCREAMING_SNAKE_CASE : Union[bool, Tuple[bool]] = False
SCREAMING_SNAKE_CASE : Tuple[int] = (3_2_0, 6_4_0, 1_2_8_0, 1_2_8_0)
SCREAMING_SNAKE_CASE : int = 2
SCREAMING_SNAKE_CASE : Union[int, Tuple[int]] = 8
SCREAMING_SNAKE_CASE : Optional[Union[int, Tuple[int]]] = None
SCREAMING_SNAKE_CASE : int = 1_2_8_0
SCREAMING_SNAKE_CASE : float = 0.0
SCREAMING_SNAKE_CASE : bool = False
SCREAMING_SNAKE_CASE : jnp.dtype = jnp.floataa
SCREAMING_SNAKE_CASE : bool = True
SCREAMING_SNAKE_CASE : int = 0
SCREAMING_SNAKE_CASE : str = "rgb"
SCREAMING_SNAKE_CASE : Tuple[int] = (1_6, 3_2, 9_6, 2_5_6)
def SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : jax.random.KeyArray ):
# init input tensors
__lowercase = (1, self.in_channels, self.sample_size, self.sample_size)
__lowercase = jnp.zeros(lowercase__ ,dtype=jnp.floataa )
__lowercase = jnp.ones((1,) ,dtype=jnp.intaa )
__lowercase = jnp.zeros((1, 1, self.cross_attention_dim) ,dtype=jnp.floataa )
__lowercase = (1, 3, self.sample_size * 8, self.sample_size * 8)
__lowercase = jnp.zeros(lowercase__ ,dtype=jnp.floataa )
__lowercase , __lowercase = jax.random.split(lowercase__ )
__lowercase = {'''params''': params_rng, '''dropout''': dropout_rng}
return self.init(lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ )["params"]
def SCREAMING_SNAKE_CASE ( self : Any ):
__lowercase = self.block_out_channels
__lowercase = block_out_channels[0] * 4
# If `num_attention_heads` is not defined (which is the case for most models)
# it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
# The reason for this behavior is to correct for incorrectly named variables that were introduced
# when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
# Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
# which is why we correct for the naming here.
__lowercase = self.num_attention_heads or self.attention_head_dim
# input
__lowercase = nn.Conv(
block_out_channels[0] ,kernel_size=(3, 3) ,strides=(1, 1) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,)
# time
__lowercase = FlaxTimesteps(
block_out_channels[0] ,flip_sin_to_cos=self.flip_sin_to_cos ,freq_shift=self.config.freq_shift )
__lowercase = FlaxTimestepEmbedding(lowercase__ ,dtype=self.dtype )
__lowercase = FlaxControlNetConditioningEmbedding(
conditioning_embedding_channels=block_out_channels[0] ,block_out_channels=self.conditioning_embedding_out_channels ,)
__lowercase = self.only_cross_attention
if isinstance(lowercase__ ,lowercase__ ):
__lowercase = (only_cross_attention,) * len(self.down_block_types )
if isinstance(lowercase__ ,lowercase__ ):
__lowercase = (num_attention_heads,) * len(self.down_block_types )
# down
__lowercase = []
__lowercase = []
__lowercase = block_out_channels[0]
__lowercase = nn.Conv(
lowercase__ ,kernel_size=(1, 1) ,padding='''VALID''' ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,)
controlnet_down_blocks.append(lowercase__ )
for i, down_block_type in enumerate(self.down_block_types ):
__lowercase = output_channel
__lowercase = block_out_channels[i]
__lowercase = i == len(lowercase__ ) - 1
if down_block_type == "CrossAttnDownBlock2D":
__lowercase = FlaxCrossAttnDownBlockaD(
in_channels=lowercase__ ,out_channels=lowercase__ ,dropout=self.dropout ,num_layers=self.layers_per_block ,num_attention_heads=num_attention_heads[i] ,add_downsample=not is_final_block ,use_linear_projection=self.use_linear_projection ,only_cross_attention=only_cross_attention[i] ,dtype=self.dtype ,)
else:
__lowercase = FlaxDownBlockaD(
in_channels=lowercase__ ,out_channels=lowercase__ ,dropout=self.dropout ,num_layers=self.layers_per_block ,add_downsample=not is_final_block ,dtype=self.dtype ,)
down_blocks.append(lowercase__ )
for _ in range(self.layers_per_block ):
__lowercase = nn.Conv(
lowercase__ ,kernel_size=(1, 1) ,padding='''VALID''' ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,)
controlnet_down_blocks.append(lowercase__ )
if not is_final_block:
__lowercase = nn.Conv(
lowercase__ ,kernel_size=(1, 1) ,padding='''VALID''' ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,)
controlnet_down_blocks.append(lowercase__ )
__lowercase = down_blocks
__lowercase = controlnet_down_blocks
# mid
__lowercase = block_out_channels[-1]
__lowercase = FlaxUNetMidBlockaDCrossAttn(
in_channels=lowercase__ ,dropout=self.dropout ,num_attention_heads=num_attention_heads[-1] ,use_linear_projection=self.use_linear_projection ,dtype=self.dtype ,)
__lowercase = nn.Conv(
lowercase__ ,kernel_size=(1, 1) ,padding='''VALID''' ,kernel_init=nn.initializers.zeros_init() ,bias_init=nn.initializers.zeros_init() ,dtype=self.dtype ,)
def __call__( self : Optional[Any] ,lowercase__ : List[str] ,lowercase__ : Any ,lowercase__ : List[Any] ,lowercase__ : str ,lowercase__ : float = 1.0 ,lowercase__ : bool = True ,lowercase__ : bool = False ,):
__lowercase = self.controlnet_conditioning_channel_order
if channel_order == "bgr":
__lowercase = jnp.flip(lowercase__ ,axis=1 )
# 1. time
if not isinstance(lowercase__ ,jnp.ndarray ):
__lowercase = jnp.array([timesteps] ,dtype=jnp.intaa )
elif isinstance(lowercase__ ,jnp.ndarray ) and len(timesteps.shape ) == 0:
__lowercase = timesteps.astype(dtype=jnp.floataa )
__lowercase = jnp.expand_dims(lowercase__ ,0 )
__lowercase = self.time_proj(lowercase__ )
__lowercase = self.time_embedding(lowercase__ )
# 2. pre-process
__lowercase = jnp.transpose(lowercase__ ,(0, 2, 3, 1) )
__lowercase = self.conv_in(lowercase__ )
__lowercase = jnp.transpose(lowercase__ ,(0, 2, 3, 1) )
__lowercase = self.controlnet_cond_embedding(lowercase__ )
sample += controlnet_cond
# 3. down
__lowercase = (sample,)
for down_block in self.down_blocks:
if isinstance(lowercase__ ,lowercase__ ):
__lowercase , __lowercase = down_block(lowercase__ ,lowercase__ ,lowercase__ ,deterministic=not train )
else:
__lowercase , __lowercase = down_block(lowercase__ ,lowercase__ ,deterministic=not train )
down_block_res_samples += res_samples
# 4. mid
__lowercase = self.mid_block(lowercase__ ,lowercase__ ,lowercase__ ,deterministic=not train )
# 5. contronet blocks
__lowercase = ()
for down_block_res_sample, controlnet_block in zip(lowercase__ ,self.controlnet_down_blocks ):
__lowercase = controlnet_block(lowercase__ )
controlnet_down_block_res_samples += (down_block_res_sample,)
__lowercase = controlnet_down_block_res_samples
__lowercase = self.controlnet_mid_block(lowercase__ )
# 6. scaling
__lowercase = [sample * conditioning_scale for sample in down_block_res_samples]
mid_block_res_sample *= conditioning_scale
if not return_dict:
return (down_block_res_samples, mid_block_res_sample)
return FlaxControlNetOutput(
down_block_res_samples=lowercase__ ,mid_block_res_sample=lowercase__ )
| 41 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCAmelCase = logging.get_logger(__name__)
class A_ ( A__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = """timm_backbone"""
def __init__( self :Any , lowerCamelCase_ :int=None , lowerCamelCase_ :Optional[int]=3 , lowerCamelCase_ :int=True , lowerCamelCase_ :Dict=True , lowerCamelCase_ :Union[str, Any]=None , **lowerCamelCase_ :Optional[int] , ):
"""simple docstring"""
super().__init__(**lowerCamelCase_ )
lowerCamelCase__ : Optional[int] =backbone
lowerCamelCase__ : List[Any] =num_channels
lowerCamelCase__ : Tuple =features_only
lowerCamelCase__ : Dict =use_pretrained_backbone
lowerCamelCase__ : Optional[int] =True
lowerCamelCase__ : Optional[int] =out_indices if out_indices is not None else (-1,) | 174 | 0 |
import inspect
import os
import sys
import unittest
import accelerate
from accelerate.test_utils import execute_subprocess_async, require_tpu
class UpperCamelCase__ ( unittest.TestCase ):
'''simple docstring'''
def snake_case__ ( self ) -> Dict:
"""simple docstring"""
lowercase_ : Optional[int] = inspect.getfile(accelerate.test_utils )
lowercase_ : Tuple = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] )
lowercase_ : int = os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] )
@require_tpu
def snake_case__ ( self ) -> Optional[int]:
"""simple docstring"""
lowercase_ : Dict = f"""
{self.test_dir}/xla_spawn.py
--num_cores 8
{self.test_file_path}
""".split()
lowercase_ : Optional[Any] = [sys.executable] + distributed_args
execute_subprocess_async(snake_case__, env=os.environ.copy() ) | 436 |
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_albert import AlbertTokenizer
else:
UpperCAmelCase_ = None
UpperCAmelCase_ = logging.get_logger(__name__)
UpperCAmelCase_ = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""}
UpperCAmelCase_ = {
"""vocab_file""": {
"""albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""",
"""albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""",
"""albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""",
"""albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""",
"""albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""",
"""albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""",
"""albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""",
"""albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""",
},
"""tokenizer_file""": {
"""albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json""",
"""albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json""",
"""albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json""",
"""albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json""",
"""albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json""",
"""albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json""",
"""albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json""",
"""albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json""",
},
}
UpperCAmelCase_ = {
"""albert-base-v1""": 512,
"""albert-large-v1""": 512,
"""albert-xlarge-v1""": 512,
"""albert-xxlarge-v1""": 512,
"""albert-base-v2""": 512,
"""albert-large-v2""": 512,
"""albert-xlarge-v2""": 512,
"""albert-xxlarge-v2""": 512,
}
UpperCAmelCase_ = """▁"""
class UpperCamelCase__ ( lowerCamelCase__ ):
'''simple docstring'''
__a : List[str] = VOCAB_FILES_NAMES
__a : str = PRETRAINED_VOCAB_FILES_MAP
__a : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__a : Tuple = AlbertTokenizer
def __init__( self, snake_case__=None, snake_case__=None, snake_case__=True, snake_case__=True, snake_case__=False, snake_case__="[CLS]", snake_case__="[SEP]", snake_case__="<unk>", snake_case__="[SEP]", snake_case__="<pad>", snake_case__="[CLS]", snake_case__="[MASK]", **snake_case__, ) -> Tuple:
"""simple docstring"""
# Mask token behave like a normal word, i.e. include the space before it and
# is included in the raw text, there should be a match in a non-normalized sentence.
lowercase_ : Optional[Any] = (
AddedToken(snake_case__, lstrip=snake_case__, rstrip=snake_case__, normalized=snake_case__ )
if isinstance(snake_case__, snake_case__ )
else mask_token
)
super().__init__(
snake_case__, tokenizer_file=snake_case__, do_lower_case=snake_case__, remove_space=snake_case__, keep_accents=snake_case__, bos_token=snake_case__, eos_token=snake_case__, unk_token=snake_case__, sep_token=snake_case__, pad_token=snake_case__, cls_token=snake_case__, mask_token=snake_case__, **snake_case__, )
lowercase_ : Optional[Any] = do_lower_case
lowercase_ : List[Any] = remove_space
lowercase_ : Dict = keep_accents
lowercase_ : Optional[int] = vocab_file
lowercase_ : Any = False if not self.vocab_file else True
def snake_case__ ( self, snake_case__, snake_case__ = None ) -> List[int]:
"""simple docstring"""
lowercase_ : int = [self.sep_token_id]
lowercase_ : Tuple = [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 snake_case__ ( self, snake_case__, snake_case__ = None ) -> List[int]:
"""simple docstring"""
lowercase_ : List[Any] = [self.sep_token_id]
lowercase_ : int = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def snake_case__ ( self, snake_case__, snake_case__ = None ) -> Tuple[str]:
"""simple docstring"""
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(snake_case__ ):
logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" )
return
lowercase_ : List[Any] = os.path.join(
snake_case__, (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case__ ):
copyfile(self.vocab_file, snake_case__ )
return (out_vocab_file,) | 436 | 1 |
'''simple docstring'''
import argparse
from collections import defaultdict
def lowercase__( __UpperCamelCase: Union[str, Any] ,__UpperCamelCase: List[str] ,__UpperCamelCase: Tuple ,__UpperCamelCase: str ,__UpperCamelCase: Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Any = f"{file}_{class_name}_{test_name}"
done_test[_id] += 1
with open(__UpperCamelCase ,'r' ) as f:
SCREAMING_SNAKE_CASE : Union[str, Any] = f.readlines()
SCREAMING_SNAKE_CASE : Optional[int] = f"class {class_name}("
SCREAMING_SNAKE_CASE : Union[str, Any] = f"{4 * ' '}def {test_name}("
SCREAMING_SNAKE_CASE : int = f"{8 * ' '}{correct_line.split()[0]}"
SCREAMING_SNAKE_CASE : Optional[Any] = f"{16 * ' '}{correct_line.split()[0]}"
SCREAMING_SNAKE_CASE : Any = False
SCREAMING_SNAKE_CASE : Dict = False
SCREAMING_SNAKE_CASE : int = False
SCREAMING_SNAKE_CASE : List[Any] = False
SCREAMING_SNAKE_CASE : Union[str, Any] = 0
SCREAMING_SNAKE_CASE : Tuple = 0
SCREAMING_SNAKE_CASE : List[Any] = []
for line in lines:
if line.startswith(__UpperCamelCase ):
SCREAMING_SNAKE_CASE : Tuple = True
elif in_class and line.startswith(__UpperCamelCase ):
SCREAMING_SNAKE_CASE : str = True
elif in_class and in_func and (line.startswith(__UpperCamelCase ) or line.startswith(__UpperCamelCase )):
SCREAMING_SNAKE_CASE : Any = len(line.split(correct_line.split()[0] )[0] )
count += 1
if count == done_test[_id]:
SCREAMING_SNAKE_CASE : Union[str, Any] = True
if in_class and in_func and in_line:
if ")" not in line:
continue
else:
SCREAMING_SNAKE_CASE : str = True
if in_class and in_func and in_line and insert_line:
new_lines.append(f"{spaces * ' '}{correct_line}" )
SCREAMING_SNAKE_CASE : Optional[Any] = False
else:
new_lines.append(__UpperCamelCase )
with open(__UpperCamelCase ,'w' ) as f:
for line in new_lines:
f.write(__UpperCamelCase )
def lowercase__( __UpperCamelCase: List[str] ,__UpperCamelCase: List[Any]=None ):
"""simple docstring"""
if fail is not None:
with open(__UpperCamelCase ,'r' ) as f:
SCREAMING_SNAKE_CASE : Union[str, Any] = {l.strip() for l in f.readlines()}
else:
SCREAMING_SNAKE_CASE : Union[str, Any] = None
with open(__UpperCamelCase ,'r' ) as f:
SCREAMING_SNAKE_CASE : List[Any] = f.readlines()
SCREAMING_SNAKE_CASE : Union[str, Any] = defaultdict(__UpperCamelCase )
for line in correct_lines:
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = line.split(';' )
if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures:
overwrite_file(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase )
if __name__ == "__main__":
UpperCamelCase_ = argparse.ArgumentParser()
parser.add_argument("--correct_filename", help="filename of tests with expected result")
parser.add_argument("--fail_filename", help="filename of test failures", type=str, default=None)
UpperCamelCase_ = parser.parse_args()
main(args.correct_filename, args.fail_filename)
| 28 | '''simple docstring'''
from collections.abc import Sequence
def lowerCAmelCase ( UpperCamelCase__ : Sequence[float] , UpperCamelCase__ : bool = False ):
"""simple docstring"""
if not arr:
return 0
__UpperCAmelCase = 0 if allow_empty_subarrays else float('''-inf''' )
__UpperCAmelCase = 0.0
for num in arr:
__UpperCAmelCase = max(0 if allow_empty_subarrays else num , curr_sum + num )
__UpperCAmelCase = max(UpperCamelCase__ , UpperCamelCase__ )
return max_sum
if __name__ == "__main__":
from doctest import testmod
testmod()
__lowerCAmelCase : int = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(F"""{max_subarray_sum(nums) = }""")
| 262 | 0 |
import importlib
import os
import sys
# This is required to make the module import works (when the python process is running from the root of the repo)
sys.path.append('''.''')
def UpperCamelCase__ ( A__ ) -> Any:
snake_case__ : Union[str, Any] = test_file.split(os.path.sep )
if components[0:2] != ["tests", "models"]:
raise ValueError(
'`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got '
F"""{test_file} instead.""" )
snake_case__ : int = components[-1]
if not test_fn.endswith('py' ):
raise ValueError(F"""`test_file` should be a python file. Got {test_fn} instead.""" )
if not test_fn.startswith('test_modeling_' ):
raise ValueError(
F"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" )
snake_case__ : List[Any] = components[:-1] + [test_fn.replace('.py' , '' )]
snake_case__ : Union[str, Any] = '.'.join(_SCREAMING_SNAKE_CASE )
return test_module_path
def UpperCamelCase__ ( A__ ) -> Any:
snake_case__ : Any = get_module_path(_SCREAMING_SNAKE_CASE )
snake_case__ : str = importlib.import_module(_SCREAMING_SNAKE_CASE )
return test_module
def UpperCamelCase__ ( A__ ) -> List[str]:
snake_case__ : List[Any] = []
snake_case__ : Optional[int] = get_test_module(_SCREAMING_SNAKE_CASE )
for attr in dir(_SCREAMING_SNAKE_CASE ):
if attr.endswith('ModelTester' ):
tester_classes.append(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
# sort with class names
return sorted(_SCREAMING_SNAKE_CASE , key=lambda A__ : x.__name__ )
def UpperCamelCase__ ( A__ ) -> Optional[Any]:
snake_case__ : Any = []
snake_case__ : Optional[int] = get_test_module(_SCREAMING_SNAKE_CASE )
for attr in dir(_SCREAMING_SNAKE_CASE ):
snake_case__ : Optional[Any] = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking
# `all_model_classes` is not empty (which also excludes other special classes).
snake_case__ : Union[str, Any] = getattr(_SCREAMING_SNAKE_CASE , 'all_model_classes' , [] )
if len(_SCREAMING_SNAKE_CASE ) > 0:
test_classes.append(_SCREAMING_SNAKE_CASE )
# sort with class names
return sorted(_SCREAMING_SNAKE_CASE , key=lambda A__ : x.__name__ )
def UpperCamelCase__ ( A__ ) -> Any:
snake_case__ : Optional[Any] = get_test_classes(_SCREAMING_SNAKE_CASE )
snake_case__ : Optional[int] = set()
for test_class in test_classes:
model_classes.update(test_class.all_model_classes )
# sort with class names
return sorted(_SCREAMING_SNAKE_CASE , key=lambda A__ : x.__name__ )
def UpperCamelCase__ ( A__ ) -> Any:
snake_case__ : Union[str, Any] = test_class()
if hasattr(_SCREAMING_SNAKE_CASE , 'setUp' ):
test.setUp()
snake_case__ : List[str] = None
if hasattr(_SCREAMING_SNAKE_CASE , 'model_tester' ):
# `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case.
if test.model_tester is not None:
snake_case__ : Any = test.model_tester.__class__
return model_tester
def UpperCamelCase__ ( A__ , A__ ) -> Tuple:
snake_case__ : Tuple = get_test_classes(_SCREAMING_SNAKE_CASE )
snake_case__ : Optional[int] = []
for test_class in test_classes:
if model_class in test_class.all_model_classes:
target_test_classes.append(_SCREAMING_SNAKE_CASE )
# sort with class names
return sorted(_SCREAMING_SNAKE_CASE , key=lambda A__ : x.__name__ )
def UpperCamelCase__ ( A__ , A__ ) -> int:
snake_case__ : Tuple = get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
snake_case__ : Union[str, Any] = []
for test_class in test_classes:
snake_case__ : Union[str, Any] = get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE )
if tester_class is not None:
tester_classes.append(_SCREAMING_SNAKE_CASE )
# sort with class names
return sorted(_SCREAMING_SNAKE_CASE , key=lambda A__ : x.__name__ )
def UpperCamelCase__ ( A__ ) -> Dict:
snake_case__ : Optional[int] = get_test_classes(_SCREAMING_SNAKE_CASE )
snake_case__ : Union[str, Any] = {test_class: get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) for test_class in test_classes}
return test_tester_mapping
def UpperCamelCase__ ( A__ ) -> List[Any]:
snake_case__ : List[str] = get_model_classes(_SCREAMING_SNAKE_CASE )
snake_case__ : List[Any] = {
model_class: get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes
}
return model_test_mapping
def UpperCamelCase__ ( A__ ) -> Union[str, Any]:
snake_case__ : Any = get_model_classes(_SCREAMING_SNAKE_CASE )
snake_case__ : int = {
model_class: get_tester_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes
}
return model_to_tester_mapping
def UpperCamelCase__ ( A__ ) -> Any:
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
return o
elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
return o.__name__
elif isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ):
return [to_json(_SCREAMING_SNAKE_CASE ) for x in o]
elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
return {to_json(_SCREAMING_SNAKE_CASE ): to_json(_SCREAMING_SNAKE_CASE ) for k, v in o.items()}
else:
return o
| 702 | import numpy as np
import qiskit
def UpperCamelCase__ ( A__ = 8 , A__ = None ) -> str:
snake_case__ : Optional[int] = np.random.default_rng(seed=A__ )
# Roughly 25% of the qubits will contribute to the key.
# So we take more than we need.
snake_case__ : Tuple = 6 * key_len
# Measurement basis for Alice's qubits.
snake_case__ : Tuple = rng.integers(2 , size=A__ )
# The set of states Alice will prepare.
snake_case__ : List[str] = rng.integers(2 , size=A__ )
# Measurement basis for Bob's qubits.
snake_case__ : List[Any] = rng.integers(2 , size=A__ )
# Quantum Circuit to simulate BB84
snake_case__ : Any = qiskit.QuantumCircuit(A__ , name='BB84' )
# Alice prepares her qubits according to rules above.
for index, _ in enumerate(A__ ):
if alice_state[index] == 1:
bbaa_circ.x(A__ )
if alice_basis[index] == 1:
bbaa_circ.h(A__ )
bbaa_circ.barrier()
# Bob measures the received qubits according to rules above.
for index, _ in enumerate(A__ ):
if bob_basis[index] == 1:
bbaa_circ.h(A__ )
bbaa_circ.barrier()
bbaa_circ.measure_all()
# Simulate the quantum circuit.
snake_case__ : List[str] = qiskit.Aer.get_backend('aer_simulator' )
# We only need to run one shot because the key is unique.
# Multiple shots will produce the same key.
snake_case__ : Optional[Any] = qiskit.execute(A__ , A__ , shots=1 , seed_simulator=A__ )
# Returns the result of measurement.
snake_case__ : Union[str, Any] = job.result().get_counts(A__ ).most_frequent()
# Extracting the generated key from the simulation results.
# Only keep measurement results where Alice and Bob chose the same basis.
snake_case__ : Optional[Any] = ''.join(
[
result_bit
for alice_basis_bit, bob_basis_bit, result_bit in zip(
A__ , A__ , A__ )
if alice_basis_bit == bob_basis_bit
] )
# Get final key. Pad with 0 if too short, otherwise truncate.
snake_case__ : Tuple = gen_key[:key_len] if len(A__ ) >= key_len else gen_key.ljust(A__ , '0' )
return key
if __name__ == "__main__":
print(F'''The generated key is : {bbaa(8, seed=0)}''')
from doctest import testmod
testmod()
| 699 | 0 |
import unittest
from huggingface_hub import hf_hub_download
from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor
from transformers.pipelines import VideoClassificationPipeline, pipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_decord,
require_tf,
require_torch,
require_torch_or_tf,
require_vision,
)
from .test_pipelines_common import ANY
@is_pipeline_test
@require_torch_or_tf
@require_vision
@require_decord
class lowerCAmelCase_ ( unittest.TestCase ):
UpperCAmelCase = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING
def UpperCamelCase_ ( self : Tuple , _A : str , _A : List[Any] , _A : List[Any] ):
_UpperCamelCase = hf_hub_download(
repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' )
_UpperCamelCase = VideoClassificationPipeline(model=_A , image_processor=_A , top_k=2 )
_UpperCamelCase = [
example_video_filepath,
'''https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4''',
]
return video_classifier, examples
def UpperCamelCase_ ( self : Tuple , _A : List[Any] , _A : Union[str, Any] ):
for example in examples:
_UpperCamelCase = video_classifier(_A )
self.assertEqual(
_A , [
{'''score''': ANY(_A ), '''label''': ANY(_A )},
{'''score''': ANY(_A ), '''label''': ANY(_A )},
] , )
@require_torch
def UpperCamelCase_ ( self : Optional[Any] ):
_UpperCamelCase = '''hf-internal-testing/tiny-random-VideoMAEForVideoClassification'''
_UpperCamelCase = VideoMAEFeatureExtractor(
size={'''shortest_edge''': 10} , crop_size={'''height''': 10, '''width''': 10} )
_UpperCamelCase = pipeline(
'''video-classification''' , model=_A , feature_extractor=_A , frame_sampling_rate=4 )
_UpperCamelCase = hf_hub_download(repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' )
_UpperCamelCase = video_classifier(_A , top_k=2 )
self.assertEqual(
nested_simplify(_A , decimals=4 ) , [{'''score''': 0.5199, '''label''': '''LABEL_0'''}, {'''score''': 0.4801, '''label''': '''LABEL_1'''}] , )
_UpperCamelCase = video_classifier(
[
video_file_path,
video_file_path,
] , top_k=2 , )
self.assertEqual(
nested_simplify(_A , decimals=4 ) , [
[{'''score''': 0.5199, '''label''': '''LABEL_0'''}, {'''score''': 0.4801, '''label''': '''LABEL_1'''}],
[{'''score''': 0.5199, '''label''': '''LABEL_0'''}, {'''score''': 0.4801, '''label''': '''LABEL_1'''}],
] , )
@require_tf
def UpperCamelCase_ ( self : Optional[int] ):
pass
| 10 | import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional
import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors
import transformers
from transformers import (
AutoConfig,
AutoModelForMultipleChoice,
AutoTokenizer,
DataCollatorWithPadding,
EvalPrediction,
HfArgumentParser,
Trainer,
TrainingArguments,
set_seed,
)
from transformers.trainer_utils import is_main_process
_lowerCAmelCase = logging.getLogger(__name__)
def _snake_case ( __snake_case , __snake_case ):
return (preds == labels).mean()
@dataclass
class lowerCAmelCase_ :
UpperCAmelCase = field(
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} )
UpperCAmelCase = field(
default=__lowercase, metadata={"help": "Pretrained config name or path if not the same as model_name"} )
UpperCAmelCase = field(
default=__lowercase, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} )
UpperCAmelCase = field(
default=__lowercase, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, )
@dataclass
class lowerCAmelCase_ :
UpperCAmelCase = field(metadata={"help": "The name of the task to train on: " + ", ".join(processors.keys() )} )
UpperCAmelCase = field(metadata={"help": "Should contain the data files for the task."} )
UpperCAmelCase = 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."
)
}, )
UpperCAmelCase = field(
default=__lowercase, metadata={"help": "Overwrite the cached training and evaluation sets"} )
def _snake_case ( ):
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
_UpperCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_args_into_dataclasses()
if (
os.path.exists(training_args.output_dir )
and os.listdir(training_args.output_dir )
and training_args.do_train
and not training_args.overwrite_output_dir
):
raise ValueError(
f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use"""
''' --overwrite_output_dir to overcome.''' )
# Setup logging
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , )
logger.warning(
'''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , 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()
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
logger.info('''Training/evaluation parameters %s''' , __snake_case )
# Set seed
set_seed(training_args.seed )
try:
_UpperCamelCase = processors[data_args.task_name]()
_UpperCamelCase = processor.get_labels()
_UpperCamelCase = len(__snake_case )
except KeyError:
raise ValueError('''Task not found: %s''' % (data_args.task_name) )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
_UpperCamelCase = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__snake_case , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , )
_UpperCamelCase = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , )
_UpperCamelCase = AutoModelForMultipleChoice.from_pretrained(
model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , )
# Get datasets
_UpperCamelCase = (
MultipleChoiceDataset(
data_dir=data_args.data_dir , tokenizer=__snake_case , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , )
if training_args.do_train
else None
)
_UpperCamelCase = (
MultipleChoiceDataset(
data_dir=data_args.data_dir , tokenizer=__snake_case , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , )
if training_args.do_eval
else None
)
def compute_metrics(__snake_case ) -> Dict:
_UpperCamelCase = np.argmax(p.predictions , axis=1 )
return {"acc": simple_accuracy(__snake_case , p.label_ids )}
# Data collator
_UpperCamelCase = DataCollatorWithPadding(__snake_case , pad_to_multiple_of=8 ) if training_args.fpaa else None
# Initialize our Trainer
_UpperCamelCase = Trainer(
model=__snake_case , args=__snake_case , train_dataset=__snake_case , eval_dataset=__snake_case , compute_metrics=__snake_case , data_collator=__snake_case , )
# Training
if training_args.do_train:
trainer.train(
model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None )
trainer.save_model()
# For convenience, we also re-save the tokenizer to the same directory,
# so that you can share your model easily on huggingface.co/models =)
if trainer.is_world_master():
tokenizer.save_pretrained(training_args.output_dir )
# Evaluation
_UpperCamelCase = {}
if training_args.do_eval:
logger.info('''*** Evaluate ***''' )
_UpperCamelCase = trainer.evaluate()
_UpperCamelCase = os.path.join(training_args.output_dir , '''eval_results.txt''' )
if trainer.is_world_master():
with open(__snake_case , '''w''' ) as writer:
logger.info('''***** Eval results *****''' )
for key, value in result.items():
logger.info(''' %s = %s''' , __snake_case , __snake_case )
writer.write('''%s = %s\n''' % (key, value) )
results.update(__snake_case )
return results
def _snake_case ( __snake_case ):
# For xla_spawn (TPUs)
main()
if __name__ == "__main__":
main()
| 10 | 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 : List[str] = {
'configuration_electra': ['ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ElectraConfig', 'ElectraOnnxConfig'],
'tokenization_electra': ['ElectraTokenizer'],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case : Union[str, Any] = ['ElectraTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case : Any = [
'ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST',
'ElectraForCausalLM',
'ElectraForMaskedLM',
'ElectraForMultipleChoice',
'ElectraForPreTraining',
'ElectraForQuestionAnswering',
'ElectraForSequenceClassification',
'ElectraForTokenClassification',
'ElectraModel',
'ElectraPreTrainedModel',
'load_tf_weights_in_electra',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case : List[Any] = [
'TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFElectraForMaskedLM',
'TFElectraForMultipleChoice',
'TFElectraForPreTraining',
'TFElectraForQuestionAnswering',
'TFElectraForSequenceClassification',
'TFElectraForTokenClassification',
'TFElectraModel',
'TFElectraPreTrainedModel',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case : Dict = [
'FlaxElectraForCausalLM',
'FlaxElectraForMaskedLM',
'FlaxElectraForMultipleChoice',
'FlaxElectraForPreTraining',
'FlaxElectraForQuestionAnswering',
'FlaxElectraForSequenceClassification',
'FlaxElectraForTokenClassification',
'FlaxElectraModel',
'FlaxElectraPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig
from .tokenization_electra import ElectraTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_electra_fast import ElectraTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_electra import (
ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST,
ElectraForCausalLM,
ElectraForMaskedLM,
ElectraForMultipleChoice,
ElectraForPreTraining,
ElectraForQuestionAnswering,
ElectraForSequenceClassification,
ElectraForTokenClassification,
ElectraModel,
ElectraPreTrainedModel,
load_tf_weights_in_electra,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_electra import (
TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST,
TFElectraForMaskedLM,
TFElectraForMultipleChoice,
TFElectraForPreTraining,
TFElectraForQuestionAnswering,
TFElectraForSequenceClassification,
TFElectraForTokenClassification,
TFElectraModel,
TFElectraPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_electra import (
FlaxElectraForCausalLM,
FlaxElectraForMaskedLM,
FlaxElectraForMultipleChoice,
FlaxElectraForPreTraining,
FlaxElectraForQuestionAnswering,
FlaxElectraForSequenceClassification,
FlaxElectraForTokenClassification,
FlaxElectraModel,
FlaxElectraPreTrainedModel,
)
else:
import sys
snake_case : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 339 |
'''simple docstring'''
from __future__ import annotations
def lowercase__ ( __UpperCamelCase : int | str ):
'''simple docstring'''
__lowercase = str(__UpperCamelCase )
return n == n[::-1]
def lowercase__ ( __UpperCamelCase : int = 1000000 ):
'''simple docstring'''
__lowercase = 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()))))
| 339 | 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 CLIPSegProcessor, ViTImageProcessor
@require_vision
class A__ ( unittest.TestCase ):
"""simple docstring"""
def __lowercase ( self) -> Dict:
'''simple docstring'''
a__ : Union[str, Any] = tempfile.mkdtemp()
# fmt: off
a__ : Any = ['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
a__ : Optional[Any] = dict(zip(lowercase , range(len(lowercase))))
a__ : Union[str, Any] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', '']
a__ : List[str] = {'unk_token': '<unk>'}
a__ : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'])
a__ : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'])
with open(self.vocab_file , 'w' , encoding='utf-8') as fp:
fp.write(json.dumps(lowercase) + '\n')
with open(self.merges_file , 'w' , encoding='utf-8') as fp:
fp.write('\n'.join(lowercase))
a__ : Any = {
'do_resize': True,
'size': 20,
'do_center_crop': True,
'crop_size': 18,
'do_normalize': True,
'image_mean': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73],
'image_std': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11],
}
a__ : int = os.path.join(self.tmpdirname , lowercase)
with open(self.image_processor_file , 'w' , encoding='utf-8') as fp:
json.dump(lowercase , lowercase)
def __lowercase ( self , **lowercase) -> List[str]:
'''simple docstring'''
return CLIPTokenizer.from_pretrained(self.tmpdirname , **lowercase)
def __lowercase ( self , **lowercase) -> Any:
'''simple docstring'''
return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **lowercase)
def __lowercase ( self , **lowercase) -> int:
'''simple docstring'''
return ViTImageProcessor.from_pretrained(self.tmpdirname , **lowercase)
def __lowercase ( self) -> Any:
'''simple docstring'''
shutil.rmtree(self.tmpdirname)
def __lowercase ( self) -> Optional[Any]:
'''simple docstring'''
a__ : Dict = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta)]
a__ : Optional[Any] = [Image.fromarray(np.moveaxis(lowercase , 0 , -1)) for x in image_inputs]
return image_inputs
def __lowercase ( self) -> Dict:
'''simple docstring'''
a__ : Optional[int] = self.get_tokenizer()
a__ : str = self.get_rust_tokenizer()
a__ : Dict = self.get_image_processor()
a__ : Any = CLIPSegProcessor(tokenizer=lowercase , image_processor=lowercase)
processor_slow.save_pretrained(self.tmpdirname)
a__ : Any = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=lowercase)
a__ : Any = CLIPSegProcessor(tokenizer=lowercase , image_processor=lowercase)
processor_fast.save_pretrained(self.tmpdirname)
a__ : str = CLIPSegProcessor.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 , lowercase)
self.assertIsInstance(processor_fast.tokenizer , lowercase)
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 , lowercase)
self.assertIsInstance(processor_fast.image_processor , lowercase)
def __lowercase ( self) -> Union[str, Any]:
'''simple docstring'''
a__ : Optional[Any] = CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor())
processor.save_pretrained(self.tmpdirname)
a__ : str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)')
a__ : Optional[Any] = self.get_image_processor(do_normalize=lowercase , padding_value=1.0)
a__ : Union[str, Any] = CLIPSegProcessor.from_pretrained(
self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=lowercase , padding_value=1.0)
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab())
self.assertIsInstance(processor.tokenizer , lowercase)
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string())
self.assertIsInstance(processor.image_processor , lowercase)
def __lowercase ( self) -> Dict:
'''simple docstring'''
a__ : List[Any] = self.get_image_processor()
a__ : Tuple = self.get_tokenizer()
a__ : Dict = CLIPSegProcessor(tokenizer=lowercase , image_processor=lowercase)
a__ : Optional[Any] = self.prepare_image_inputs()
a__ : Union[str, Any] = image_processor(lowercase , return_tensors='np')
a__ : Union[str, Any] = processor(images=lowercase , return_tensors='np')
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2)
def __lowercase ( self) -> Optional[int]:
'''simple docstring'''
a__ : int = self.get_image_processor()
a__ : Any = self.get_tokenizer()
a__ : int = CLIPSegProcessor(tokenizer=lowercase , image_processor=lowercase)
a__ : Dict = 'lower newer'
a__ : Optional[Any] = processor(text=lowercase)
a__ : Tuple = tokenizer(lowercase)
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key])
def __lowercase ( self) -> int:
'''simple docstring'''
a__ : List[Any] = self.get_image_processor()
a__ : Any = self.get_tokenizer()
a__ : Any = CLIPSegProcessor(tokenizer=lowercase , image_processor=lowercase)
a__ : Optional[Any] = 'lower newer'
a__ : Any = self.prepare_image_inputs()
a__ : str = processor(text=lowercase , images=lowercase)
self.assertListEqual(list(inputs.keys()) , ['input_ids', 'attention_mask', 'pixel_values'])
# test if it raises when no input is passed
with pytest.raises(lowercase):
processor()
def __lowercase ( self) -> List[str]:
'''simple docstring'''
a__ : int = self.get_image_processor()
a__ : List[str] = self.get_tokenizer()
a__ : Any = CLIPSegProcessor(tokenizer=lowercase , image_processor=lowercase)
a__ : List[str] = self.prepare_image_inputs()
a__ : str = self.prepare_image_inputs()
a__ : List[str] = processor(images=lowercase , visual_prompt=lowercase)
self.assertListEqual(list(inputs.keys()) , ['pixel_values', 'conditional_pixel_values'])
# test if it raises when no input is passed
with pytest.raises(lowercase):
processor()
def __lowercase ( self) -> str:
'''simple docstring'''
a__ : Any = self.get_image_processor()
a__ : str = self.get_tokenizer()
a__ : str = CLIPSegProcessor(tokenizer=lowercase , image_processor=lowercase)
a__ : Optional[int] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
a__ : str = processor.batch_decode(lowercase)
a__ : Dict = tokenizer.batch_decode(lowercase)
self.assertListEqual(lowercase , lowercase)
| 302 |
import json
from typing import Iterator, List, Union
from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers
from tokenizers.implementations.base_tokenizer import BaseTokenizer
from tokenizers.models import Unigram
from tokenizers.processors import TemplateProcessing
class A__ ( __UpperCAmelCase ):
"""simple docstring"""
def __init__( self , lowercase = "▁" , lowercase = True , lowercase = "<unk>" , lowercase = "</s>" , lowercase = "<pad>" , ) -> str:
'''simple docstring'''
a__ : Optional[Any] = {
'pad': {'id': 0, 'token': pad_token},
'eos': {'id': 1, 'token': eos_token},
'unk': {'id': 2, 'token': unk_token},
}
a__ : List[str] = [None] * len(self.special_tokens)
for token_dict in self.special_tokens.values():
a__ : Union[str, Any] = token_dict['token']
a__ : Any = Tokenizer(Unigram())
a__ : Any = normalizers.Sequence(
[
normalizers.Nmt(),
normalizers.NFKC(),
normalizers.Replace(Regex(' {2,}') , ' '),
normalizers.Lowercase(),
])
a__ : Optional[int] = pre_tokenizers.Sequence(
[
pre_tokenizers.Metaspace(replacement=lowercase , add_prefix_space=lowercase),
pre_tokenizers.Digits(individual_digits=lowercase),
pre_tokenizers.Punctuation(),
])
a__ : Dict = decoders.Metaspace(replacement=lowercase , add_prefix_space=lowercase)
a__ : int = TemplateProcessing(
single=F'$A {self.special_tokens["eos"]["token"]}' , special_tokens=[(self.special_tokens['eos']['token'], self.special_tokens['eos']['id'])] , )
a__ : str = {
'model': 'SentencePieceUnigram',
'replacement': replacement,
'add_prefix_space': add_prefix_space,
}
super().__init__(lowercase , lowercase)
def __lowercase ( self , lowercase , lowercase = 8000 , lowercase = True , ) -> Any:
'''simple docstring'''
a__ : int = trainers.UnigramTrainer(
vocab_size=lowercase , special_tokens=self.special_tokens_list , show_progress=lowercase , )
if isinstance(lowercase , lowercase):
a__ : List[Any] = [files]
self._tokenizer.train(lowercase , trainer=lowercase)
self.add_unk_id()
def __lowercase ( self , lowercase , lowercase = 8000 , lowercase = True , ) -> Dict:
'''simple docstring'''
a__ : str = trainers.UnigramTrainer(
vocab_size=lowercase , special_tokens=self.special_tokens_list , show_progress=lowercase , )
self._tokenizer.train_from_iterator(lowercase , trainer=lowercase)
self.add_unk_id()
def __lowercase ( self) -> Tuple:
'''simple docstring'''
a__ : List[str] = json.loads(self._tokenizer.to_str())
a__ : List[Any] = self.special_tokens['unk']['id']
a__ : str = Tokenizer.from_str(json.dumps(lowercase))
| 302 | 1 |
from typing import List, Optional, Union
import numpy as np
from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging
lowerCamelCase__ = logging.get_logger(__name__)
class A__ ( __magic_name__ ):
lowercase = ['input_features', 'attention_mask']
def __init__( self : Optional[Any] , a : Union[str, Any]=80 , a : List[Any]=16_000 , a : Union[str, Any]=0.0 , a : int=10 , a : Any=25 , a : str="hamming_window" , a : str=32_768.0 , a : Any=0.9_7 , a : Union[str, Any]=1.0 , a : Optional[int]=True , a : Optional[int]=True , a : int=False , **a : Dict , ):
'''simple docstring'''
super().__init__(feature_size=a , sampling_rate=a , padding_value=a , **a )
lowerCAmelCase__ : Optional[Any] = feature_size
lowerCAmelCase__ : Any = sampling_rate
lowerCAmelCase__ : int = padding_value
lowerCAmelCase__ : Optional[Any] = hop_length
lowerCAmelCase__ : Any = win_length
lowerCAmelCase__ : List[str] = frame_signal_scale
lowerCAmelCase__ : Union[str, Any] = preemphasis_coeff
lowerCAmelCase__ : Tuple = mel_floor
lowerCAmelCase__ : List[str] = normalize_means
lowerCAmelCase__ : int = normalize_vars
lowerCAmelCase__ : List[Any] = win_function
lowerCAmelCase__ : int = return_attention_mask
lowerCAmelCase__ : int = win_length * sampling_rate // 1_000
lowerCAmelCase__ : Tuple = hop_length * sampling_rate // 1_000
lowerCAmelCase__ : Tuple = optimal_fft_length(self.sample_size )
lowerCAmelCase__ : Any = (self.n_fft // 2) + 1
def _lowerCamelCase ( self : Optional[Any] , a : np.array ):
'''simple docstring'''
if self.win_function == "hamming_window":
lowerCAmelCase__ : Optional[int] = window_function(window_length=self.sample_size , name=self.win_function , periodic=a )
else:
lowerCAmelCase__ : Tuple = window_function(window_length=self.sample_size , name=self.win_function )
lowerCAmelCase__ : Tuple = mel_filter_bank(
num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , )
lowerCAmelCase__ : Any = spectrogram(
one_waveform * self.frame_signal_scale , window=a , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=a , preemphasis=self.preemphasis_coeff , mel_filters=a , mel_floor=self.mel_floor , log_mel='log' , )
return msfc_features.T
def _lowerCamelCase ( self : Optional[Any] , a : int , a : Union[str, Any] , a : List[str] ):
'''simple docstring'''
if self.normalize_means:
lowerCAmelCase__ : Dict = x[:input_length].mean(axis=0 )
lowerCAmelCase__ : List[Any] = np.subtract(a , a )
if self.normalize_vars:
lowerCAmelCase__ : Union[str, Any] = x[:input_length].std(axis=0 )
lowerCAmelCase__ : Any = np.divide(a , a )
if input_length < x.shape[0]:
lowerCAmelCase__ : List[str] = padding_value
# make sure array is in float32
lowerCAmelCase__ : Optional[int] = x.astype(np.floataa )
return x
def _lowerCamelCase ( self : Union[str, Any] , a : List[np.ndarray] , a : Optional[np.ndarray] = None ):
'''simple docstring'''
lowerCAmelCase__ : Optional[int] = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features]
return [self._normalize_one(a , a , self.padding_value ) for x, n in zip(a , a )]
def __call__( self : Union[str, Any] , a : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , a : Union[bool, str, PaddingStrategy] = False , a : Optional[int] = None , a : bool = False , a : Optional[int] = None , a : Optional[bool] = None , a : Optional[Union[str, TensorType]] = None , a : Optional[int] = None , **a : str , ):
'''simple docstring'''
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
f''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'''
f''' {self.sampling_rate} and not {sampling_rate}.''' )
else:
logger.warning(
'It is strongly recommended to pass the ``sampling_rate`` argument to this function. '
'Failing to do so can result in silent errors that might be hard to debug.' )
lowerCAmelCase__ : int = isinstance(a , np.ndarray ) and len(raw_speech.shape ) > 1
if is_batched_numpy and len(raw_speech.shape ) > 2:
raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' )
lowerCAmelCase__ : int = is_batched_numpy or (
isinstance(a , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
lowerCAmelCase__ : str = [np.asarray(a , dtype=np.floataa ) for speech in raw_speech]
elif not is_batched and not isinstance(a , np.ndarray ):
lowerCAmelCase__ : Dict = np.asarray(a , dtype=np.floataa )
elif isinstance(a , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
lowerCAmelCase__ : Optional[Any] = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
lowerCAmelCase__ : str = [raw_speech]
# extract fbank features
lowerCAmelCase__ : Dict = [self._extract_mfsc_features(a ) for one_waveform in raw_speech]
# convert into correct format for padding
lowerCAmelCase__ : List[str] = BatchFeature({'input_features': features} )
lowerCAmelCase__ : Optional[Any] = self.pad(
a , padding=a , max_length=a , truncation=a , pad_to_multiple_of=a , return_attention_mask=a , **a , )
# make sure list is in array format
lowerCAmelCase__ : List[str] = padded_inputs.get('input_features' )
if isinstance(input_features[0] , a ):
lowerCAmelCase__ : Optional[Any] = [np.asarray(a , dtype=np.floataa ) for feature in input_features]
lowerCAmelCase__ : Optional[Any] = padded_inputs.get('attention_mask' )
if attention_mask is not None:
lowerCAmelCase__ : List[Any] = [np.asarray(a , dtype=np.intaa ) for array in attention_mask]
if self.normalize_means or self.normalize_vars:
lowerCAmelCase__ : str = (
np.array(a , dtype=np.intaa )
if self._get_padding_strategies(a , max_length=a ) is not PaddingStrategy.DO_NOT_PAD
and padding
else None
)
lowerCAmelCase__ : Tuple = self.normalize(
padded_inputs['input_features'] , attention_mask=a )
if return_tensors is not None:
lowerCAmelCase__ : List[str] = padded_inputs.convert_to_tensors(a )
return padded_inputs | 721 |
import torch
from diffusers import DDPMParallelScheduler
from .test_schedulers import SchedulerCommonTest
class A__ ( __magic_name__ ):
lowercase = (DDPMParallelScheduler,)
def _lowerCamelCase ( self : str , **a : Optional[int] ):
'''simple docstring'''
lowerCAmelCase__ : str = {
'num_train_timesteps': 1_000,
'beta_start': 0.0_0_0_1,
'beta_end': 0.0_2,
'beta_schedule': 'linear',
'variance_type': 'fixed_small',
'clip_sample': True,
}
config.update(**a )
return config
def _lowerCamelCase ( self : Tuple ):
'''simple docstring'''
for timesteps in [1, 5, 100, 1_000]:
self.check_over_configs(num_train_timesteps=a )
def _lowerCamelCase ( self : int ):
'''simple docstring'''
for beta_start, beta_end in zip([0.0_0_0_1, 0.0_0_1, 0.0_1, 0.1] , [0.0_0_2, 0.0_2, 0.2, 2] ):
self.check_over_configs(beta_start=a , beta_end=a )
def _lowerCamelCase ( self : Optional[Any] ):
'''simple docstring'''
for schedule in ["linear", "squaredcos_cap_v2"]:
self.check_over_configs(beta_schedule=a )
def _lowerCamelCase ( self : List[str] ):
'''simple docstring'''
for variance in ["fixed_small", "fixed_large", "other"]:
self.check_over_configs(variance_type=a )
def _lowerCamelCase ( self : List[Any] ):
'''simple docstring'''
for clip_sample in [True, False]:
self.check_over_configs(clip_sample=a )
def _lowerCamelCase ( self : Dict ):
'''simple docstring'''
self.check_over_configs(thresholding=a )
for threshold in [0.5, 1.0, 2.0]:
for prediction_type in ["epsilon", "sample", "v_prediction"]:
self.check_over_configs(
thresholding=a , prediction_type=a , sample_max_value=a , )
def _lowerCamelCase ( self : List[Any] ):
'''simple docstring'''
for prediction_type in ["epsilon", "sample", "v_prediction"]:
self.check_over_configs(prediction_type=a )
def _lowerCamelCase ( self : Any ):
'''simple docstring'''
for t in [0, 500, 999]:
self.check_over_forward(time_step=a )
def _lowerCamelCase ( self : int ):
'''simple docstring'''
lowerCAmelCase__ : List[Any] = self.scheduler_classes[0]
lowerCAmelCase__ : Any = self.get_scheduler_config()
lowerCAmelCase__ : List[str] = scheduler_class(**a )
assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5
assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_0_9_7_9 ) ) < 1E-5
assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.0_2 ) ) < 1E-5
def _lowerCamelCase ( self : Optional[int] ):
'''simple docstring'''
lowerCAmelCase__ : Any = self.scheduler_classes[0]
lowerCAmelCase__ : Any = self.get_scheduler_config()
lowerCAmelCase__ : int = scheduler_class(**a )
lowerCAmelCase__ : str = len(a )
lowerCAmelCase__ : Tuple = self.dummy_model()
lowerCAmelCase__ : Optional[Any] = self.dummy_sample_deter
lowerCAmelCase__ : int = self.dummy_sample_deter + 0.1
lowerCAmelCase__ : Union[str, Any] = self.dummy_sample_deter - 0.1
lowerCAmelCase__ : Tuple = samplea.shape[0]
lowerCAmelCase__ : List[Any] = torch.stack([samplea, samplea, samplea] , dim=0 )
lowerCAmelCase__ : Optional[Any] = torch.arange(a )[0:3, None].repeat(1 , a )
lowerCAmelCase__ : List[str] = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) )
lowerCAmelCase__ : Tuple = scheduler.batch_step_no_noise(a , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) )
lowerCAmelCase__ : str = torch.sum(torch.abs(a ) )
lowerCAmelCase__ : Any = torch.mean(torch.abs(a ) )
assert abs(result_sum.item() - 1_1_5_3.1_8_3_3 ) < 1E-2
assert abs(result_mean.item() - 0.5_0_0_5 ) < 1E-3
def _lowerCamelCase ( self : Any ):
'''simple docstring'''
lowerCAmelCase__ : str = self.scheduler_classes[0]
lowerCAmelCase__ : List[Any] = self.get_scheduler_config()
lowerCAmelCase__ : Dict = scheduler_class(**a )
lowerCAmelCase__ : str = len(a )
lowerCAmelCase__ : Any = self.dummy_model()
lowerCAmelCase__ : int = self.dummy_sample_deter
lowerCAmelCase__ : Tuple = torch.manual_seed(0 )
for t in reversed(range(a ) ):
# 1. predict noise residual
lowerCAmelCase__ : Optional[Any] = model(a , a )
# 2. predict previous mean of sample x_t-1
lowerCAmelCase__ : int = scheduler.step(a , a , a , generator=a ).prev_sample
lowerCAmelCase__ : List[str] = pred_prev_sample
lowerCAmelCase__ : Optional[int] = torch.sum(torch.abs(a ) )
lowerCAmelCase__ : Optional[Any] = torch.mean(torch.abs(a ) )
assert abs(result_sum.item() - 2_5_8.9_6_0_6 ) < 1E-2
assert abs(result_mean.item() - 0.3_3_7_2 ) < 1E-3
def _lowerCamelCase ( self : Union[str, Any] ):
'''simple docstring'''
lowerCAmelCase__ : str = self.scheduler_classes[0]
lowerCAmelCase__ : Dict = self.get_scheduler_config(prediction_type='v_prediction' )
lowerCAmelCase__ : int = scheduler_class(**a )
lowerCAmelCase__ : str = len(a )
lowerCAmelCase__ : Optional[int] = self.dummy_model()
lowerCAmelCase__ : List[str] = self.dummy_sample_deter
lowerCAmelCase__ : Optional[Any] = torch.manual_seed(0 )
for t in reversed(range(a ) ):
# 1. predict noise residual
lowerCAmelCase__ : List[Any] = model(a , a )
# 2. predict previous mean of sample x_t-1
lowerCAmelCase__ : Optional[int] = scheduler.step(a , a , a , generator=a ).prev_sample
lowerCAmelCase__ : str = pred_prev_sample
lowerCAmelCase__ : Optional[int] = torch.sum(torch.abs(a ) )
lowerCAmelCase__ : Any = torch.mean(torch.abs(a ) )
assert abs(result_sum.item() - 2_0_2.0_2_9_6 ) < 1E-2
assert abs(result_mean.item() - 0.2_6_3_1 ) < 1E-3
def _lowerCamelCase ( self : Dict ):
'''simple docstring'''
lowerCAmelCase__ : Optional[Any] = self.scheduler_classes[0]
lowerCAmelCase__ : Any = self.get_scheduler_config()
lowerCAmelCase__ : Optional[int] = scheduler_class(**a )
lowerCAmelCase__ : Optional[Any] = [100, 87, 50, 1, 0]
scheduler.set_timesteps(timesteps=a )
lowerCAmelCase__ : List[Any] = scheduler.timesteps
for i, timestep in enumerate(a ):
if i == len(a ) - 1:
lowerCAmelCase__ : Tuple = -1
else:
lowerCAmelCase__ : Dict = timesteps[i + 1]
lowerCAmelCase__ : str = scheduler.previous_timestep(a )
lowerCAmelCase__ : int = prev_t.item()
self.assertEqual(a , a )
def _lowerCamelCase ( self : Union[str, Any] ):
'''simple docstring'''
lowerCAmelCase__ : Union[str, Any] = self.scheduler_classes[0]
lowerCAmelCase__ : Optional[int] = self.get_scheduler_config()
lowerCAmelCase__ : Optional[Any] = scheduler_class(**a )
lowerCAmelCase__ : str = [100, 87, 50, 51, 0]
with self.assertRaises(a , msg='`custom_timesteps` must be in descending order.' ):
scheduler.set_timesteps(timesteps=a )
def _lowerCamelCase ( self : List[Any] ):
'''simple docstring'''
lowerCAmelCase__ : Union[str, Any] = self.scheduler_classes[0]
lowerCAmelCase__ : str = self.get_scheduler_config()
lowerCAmelCase__ : Optional[int] = scheduler_class(**a )
lowerCAmelCase__ : str = [100, 87, 50, 1, 0]
lowerCAmelCase__ : int = len(a )
with self.assertRaises(a , msg='Can only pass one of `num_inference_steps` or `custom_timesteps`.' ):
scheduler.set_timesteps(num_inference_steps=a , timesteps=a )
def _lowerCamelCase ( self : List[str] ):
'''simple docstring'''
lowerCAmelCase__ : Dict = self.scheduler_classes[0]
lowerCAmelCase__ : Dict = self.get_scheduler_config()
lowerCAmelCase__ : Optional[int] = scheduler_class(**a )
lowerCAmelCase__ : str = [scheduler.config.num_train_timesteps]
with self.assertRaises(
a , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ):
scheduler.set_timesteps(timesteps=a ) | 69 | 0 |
import mpmath # for roots of unity
import numpy as np
class _UpperCamelCase :
'''simple docstring'''
def __init__( self : Any , a : Any=None , a : List[Any]=None ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[int] = list(poly_a or [0] )[:]
SCREAMING_SNAKE_CASE : str = list(poly_b or [0] )[:]
# Remove leading zero coefficients
while self.polyA[-1] == 0:
self.polyA.pop()
SCREAMING_SNAKE_CASE : Union[str, Any] = len(self.polyA )
while self.polyB[-1] == 0:
self.polyB.pop()
SCREAMING_SNAKE_CASE : Dict = len(self.polyB )
# Add 0 to make lengths equal a power of 2
SCREAMING_SNAKE_CASE : str = int(
2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) )
while len(self.polyA ) < self.c_max_length:
self.polyA.append(0 )
while len(self.polyB ) < self.c_max_length:
self.polyB.append(0 )
# A complex root used for the fourier transform
SCREAMING_SNAKE_CASE : Any = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) )
# The product
SCREAMING_SNAKE_CASE : Any = self.__multiply()
def __UpperCamelCase ( self : int , a : List[Any] ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE : List[Any] = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB]
# Corner case
if len(a ) <= 1:
return dft[0]
#
SCREAMING_SNAKE_CASE : int = self.c_max_length // 2
while next_ncol > 0:
SCREAMING_SNAKE_CASE : Union[str, Any] = [[] for i in range(a )]
SCREAMING_SNAKE_CASE : Optional[Any] = self.root**next_ncol
# First half of next step
SCREAMING_SNAKE_CASE : List[str] = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a ):
new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] )
current_root *= root
# Second half of next step
SCREAMING_SNAKE_CASE : List[Any] = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a ):
new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] )
current_root *= root
# Update
SCREAMING_SNAKE_CASE : Any = new_dft
SCREAMING_SNAKE_CASE : Union[str, Any] = next_ncol // 2
return dft[0]
def __UpperCamelCase ( self : int ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = self.__dft("A" )
SCREAMING_SNAKE_CASE : int = self.__dft("B" )
SCREAMING_SNAKE_CASE : Optional[Any] = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]]
del dft_a
del dft_b
# Corner Case
if len(inverce_c[0] ) <= 1:
return inverce_c[0]
# Inverse DFT
SCREAMING_SNAKE_CASE : List[str] = 2
while next_ncol <= self.c_max_length:
SCREAMING_SNAKE_CASE : Any = [[] for i in range(a )]
SCREAMING_SNAKE_CASE : Union[str, Any] = self.root ** (next_ncol // 2)
SCREAMING_SNAKE_CASE : Union[str, Any] = 1
# First half of next step
for j in range(self.c_max_length // next_ncol ):
for i in range(next_ncol // 2 ):
# Even positions
new_inverse_c[i].append(
(
inverce_c[i][j]
+ inverce_c[i][j + self.c_max_length // next_ncol]
)
/ 2 )
# Odd positions
new_inverse_c[i + next_ncol // 2].append(
(
inverce_c[i][j]
- inverce_c[i][j + self.c_max_length // next_ncol]
)
/ (2 * current_root) )
current_root *= root
# Update
SCREAMING_SNAKE_CASE : List[str] = new_inverse_c
next_ncol *= 2
# Unpack
SCREAMING_SNAKE_CASE : List[str] = [round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1J for x in inverce_c]
# Remove leading 0's
while inverce_c[-1] == 0:
inverce_c.pop()
return inverce_c
def __str__( self : int ) -> Dict:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Union[str, Any] = "A = " + " + ".join(
F"{coef}*x^{i}" for coef, i in enumerate(self.polyA[: self.len_A] ) )
SCREAMING_SNAKE_CASE : Tuple = "B = " + " + ".join(
F"{coef}*x^{i}" for coef, i in enumerate(self.polyB[: self.len_B] ) )
SCREAMING_SNAKE_CASE : List[Any] = "A*B = " + " + ".join(
F"{coef}*x^{i}" for coef, i in enumerate(self.product ) )
return F"{a}\n{b}\n{c}"
# Unit tests
if __name__ == "__main__":
import doctest
doctest.testmod() | 25 |
'''simple docstring'''
import string
def snake_case_ ( SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
_snake_case = ""
for i in sequence:
_snake_case = ord(SCREAMING_SNAKE_CASE__ )
if 65 <= extract <= 90:
output += chr(1_55 - extract )
elif 97 <= extract <= 1_22:
output += chr(2_19 - extract )
else:
output += i
return output
def snake_case_ ( SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
_snake_case = string.ascii_letters
_snake_case = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1]
return "".join(
letters_reversed[letters.index(SCREAMING_SNAKE_CASE__ )] if c in letters else c for c in sequence )
def snake_case_ ( ):
'''simple docstring'''
from timeit import timeit
print("Running performance benchmarks..." )
_snake_case = "from string import printable ; from __main__ import atbash, atbash_slow"
print(f'''> atbash_slow(): {timeit("atbash_slow(printable)" , setup=SCREAMING_SNAKE_CASE__ )} seconds''' )
print(f'''> atbash(): {timeit("atbash(printable)" , setup=SCREAMING_SNAKE_CASE__ )} seconds''' )
if __name__ == "__main__":
for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
print(F'{example} encrypted in atbash: {atbash(example)}')
benchmark()
| 672 | 0 |
import argparse
import json
import logging
import os
import sys
from unittest.mock import patch
from transformers.testing_utils import TestCasePlus, get_gpu_count, slow
__lowerCAmelCase : List[Any] = [
os.path.join(os.path.dirname(__file__), dirname)
for dirname in [
'text-classification',
'language-modeling',
'summarization',
'token-classification',
'question-answering',
]
]
sys.path.extend(SRC_DIRS)
if SRC_DIRS is not None:
import run_clm_flax
import run_flax_glue
import run_flax_ner
import run_mlm_flax
import run_qa
import run_summarization_flax
import run_ta_mlm_flax
logging.basicConfig(level=logging.DEBUG)
__lowerCAmelCase : int = logging.getLogger()
def __magic_name__ ( ):
'''simple docstring'''
a = argparse.ArgumentParser()
parser.add_argument("-f" )
a = parser.parse_args()
return args.f
def __magic_name__ ( A : Union[str, Any], A : Union[str, Any]="eval" ):
'''simple docstring'''
a = os.path.join(A, F"""{split}_results.json""" )
if os.path.exists(A ):
with open(A, "r" ) as f:
return json.load(A )
raise ValueError(F"""can't find {path}""" )
__lowerCAmelCase : str = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
class snake_case__ (_UpperCamelCase ):
"""simple docstring"""
def __UpperCAmelCase ( self : Optional[Any] ) -> str:
a = self.get_auto_remove_tmp_dir()
a = f"""
run_glue.py
--model_name_or_path distilbert-base-uncased
--output_dir {tmp_dir}
--train_file ./tests/fixtures/tests_samples/MRPC/train.csv
--validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--learning_rate=1e-4
--eval_steps=2
--warmup_steps=2
--seed=42
--max_seq_length=128
""".split()
with patch.object(__lowerCamelCase , "argv" , __lowerCamelCase ):
run_flax_glue.main()
a = get_results(__lowerCamelCase )
self.assertGreaterEqual(result["eval_accuracy"] , 0.75 )
@slow
def __UpperCAmelCase ( self : List[Any] ) -> Dict:
a = self.get_auto_remove_tmp_dir()
a = f"""
run_clm_flax.py
--model_name_or_path distilgpt2
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--do_train
--do_eval
--block_size 128
--per_device_train_batch_size 4
--per_device_eval_batch_size 4
--num_train_epochs 2
--logging_steps 2 --eval_steps 2
--output_dir {tmp_dir}
--overwrite_output_dir
""".split()
with patch.object(__lowerCamelCase , "argv" , __lowerCamelCase ):
run_clm_flax.main()
a = get_results(__lowerCamelCase )
self.assertLess(result["eval_perplexity"] , 1_00 )
@slow
def __UpperCAmelCase ( self : Optional[int] ) -> Dict:
a = self.get_auto_remove_tmp_dir()
a = f"""
run_summarization.py
--model_name_or_path t5-small
--train_file tests/fixtures/tests_samples/xsum/sample.json
--validation_file tests/fixtures/tests_samples/xsum/sample.json
--test_file tests/fixtures/tests_samples/xsum/sample.json
--output_dir {tmp_dir}
--overwrite_output_dir
--num_train_epochs=3
--warmup_steps=8
--do_train
--do_eval
--do_predict
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--predict_with_generate
""".split()
with patch.object(__lowerCamelCase , "argv" , __lowerCamelCase ):
run_summarization_flax.main()
a = get_results(__lowerCamelCase , split="test" )
self.assertGreaterEqual(result["test_rouge1"] , 10 )
self.assertGreaterEqual(result["test_rouge2"] , 2 )
self.assertGreaterEqual(result["test_rougeL"] , 7 )
self.assertGreaterEqual(result["test_rougeLsum"] , 7 )
@slow
def __UpperCAmelCase ( self : Any ) -> Tuple:
a = self.get_auto_remove_tmp_dir()
a = f"""
run_mlm.py
--model_name_or_path distilroberta-base
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--output_dir {tmp_dir}
--overwrite_output_dir
--max_seq_length 128
--per_device_train_batch_size 4
--per_device_eval_batch_size 4
--logging_steps 2 --eval_steps 2
--do_train
--do_eval
--num_train_epochs=1
""".split()
with patch.object(__lowerCamelCase , "argv" , __lowerCamelCase ):
run_mlm_flax.main()
a = get_results(__lowerCamelCase )
self.assertLess(result["eval_perplexity"] , 42 )
@slow
def __UpperCAmelCase ( self : Dict ) -> Optional[Any]:
a = self.get_auto_remove_tmp_dir()
a = f"""
run_t5_mlm_flax.py
--model_name_or_path t5-small
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--do_train
--do_eval
--max_seq_length 128
--per_device_train_batch_size 4
--per_device_eval_batch_size 4
--num_train_epochs 2
--logging_steps 2 --eval_steps 2
--output_dir {tmp_dir}
--overwrite_output_dir
""".split()
with patch.object(__lowerCamelCase , "argv" , __lowerCamelCase ):
run_ta_mlm_flax.main()
a = get_results(__lowerCamelCase )
self.assertGreaterEqual(result["eval_accuracy"] , 0.42 )
@slow
def __UpperCAmelCase ( self : str ) -> List[Any]:
# with so little data distributed training needs more epochs to get the score on par with 0/1 gpu
a = 7 if get_gpu_count() > 1 else 2
a = self.get_auto_remove_tmp_dir()
a = f"""
run_flax_ner.py
--model_name_or_path bert-base-uncased
--train_file tests/fixtures/tests_samples/conll/sample.json
--validation_file tests/fixtures/tests_samples/conll/sample.json
--output_dir {tmp_dir}
--overwrite_output_dir
--do_train
--do_eval
--warmup_steps=2
--learning_rate=2e-4
--logging_steps 2 --eval_steps 2
--per_device_train_batch_size=2
--per_device_eval_batch_size=2
--num_train_epochs={epochs}
--seed 7
""".split()
with patch.object(__lowerCamelCase , "argv" , __lowerCamelCase ):
run_flax_ner.main()
a = get_results(__lowerCamelCase )
self.assertGreaterEqual(result["eval_accuracy"] , 0.75 )
self.assertGreaterEqual(result["eval_f1"] , 0.3 )
@slow
def __UpperCAmelCase ( self : Union[str, Any] ) -> str:
a = self.get_auto_remove_tmp_dir()
a = f"""
run_qa.py
--model_name_or_path bert-base-uncased
--version_2_with_negative
--train_file tests/fixtures/tests_samples/SQUAD/sample.json
--validation_file tests/fixtures/tests_samples/SQUAD/sample.json
--output_dir {tmp_dir}
--overwrite_output_dir
--num_train_epochs=3
--warmup_steps=2
--do_train
--do_eval
--logging_steps 2 --eval_steps 2
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
""".split()
with patch.object(__lowerCamelCase , "argv" , __lowerCamelCase ):
run_qa.main()
a = get_results(__lowerCamelCase )
self.assertGreaterEqual(result["eval_f1"] , 30 )
self.assertGreaterEqual(result["eval_exact"] , 30 )
| 662 |
import multiprocessing
import time
from arguments import PretokenizationArguments
from datasets import load_dataset
from transformers import AutoTokenizer, HfArgumentParser
def __magic_name__ ( A : List[str] ):
'''simple docstring'''
a = {}
a = tokenizer(example["content"], truncation=A )["input_ids"]
a = len(example["content"] ) / len(output["input_ids"] )
return output
__lowerCAmelCase : Dict = HfArgumentParser(PretokenizationArguments)
__lowerCAmelCase : str = parser.parse_args()
if args.num_workers is None:
__lowerCAmelCase : List[Any] = multiprocessing.cpu_count()
__lowerCAmelCase : str = AutoTokenizer.from_pretrained(args.tokenizer_dir)
__lowerCAmelCase : List[Any] = time.time()
__lowerCAmelCase : str = load_dataset(args.dataset_name, split='train')
print(F'''Dataset loaded in {time.time()-t_start:.2f}s''')
__lowerCAmelCase : int = time.time()
__lowerCAmelCase : Optional[int] = ds.map(
tokenize,
num_proc=args.num_workers,
remove_columns=[
'repo_name',
'path',
'copies',
'size',
'content',
'license',
'hash',
'line_mean',
'line_max',
'alpha_frac',
'autogenerated',
],
)
print(F'''Dataset tokenized in {time.time()-t_start:.2f}s''')
__lowerCAmelCase : Tuple = time.time()
ds.push_to_hub(args.tokenized_data_repo)
print(F'''Data pushed to the hub in {time.time()-t_start:.2f}s''')
| 662 | 1 |
"""simple docstring"""
import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union
import sentencepiece
from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer
from ...utils import logging
__UpperCAmelCase = logging.get_logger(__name__)
__UpperCAmelCase = '▁'
__UpperCAmelCase = {
'vocab_file': 'vocab.json',
'spm_file': 'sentencepiece.bpe.model',
'tokenizer_config_file': 'tokenizer_config.json',
}
__UpperCAmelCase = {
'vocab_file': {
'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json',
'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json',
},
'spm_file': {
'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model',
'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model',
},
'tokenizer_config_file': {
'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json',
'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json',
},
}
__UpperCAmelCase = {
'facebook/m2m100_418M': 1024,
}
# fmt: off
__UpperCAmelCase = {
'm2m100': ['af', 'am', 'ar', 'ast', 'az', 'ba', 'be', 'bg', 'bn', 'br', 'bs', 'ca', 'ceb', 'cs', 'cy', 'da', 'de', 'el', 'en', 'es', 'et', 'fa', 'ff', 'fi', 'fr', 'fy', 'ga', 'gd', 'gl', 'gu', 'ha', 'he', 'hi', 'hr', 'ht', 'hu', 'hy', 'id', 'ig', 'ilo', 'is', 'it', 'ja', 'jv', 'ka', 'kk', 'km', 'kn', 'ko', 'lb', 'lg', 'ln', 'lo', 'lt', 'lv', 'mg', 'mk', 'ml', 'mn', 'mr', 'ms', 'my', 'ne', 'nl', 'no', 'ns', 'oc', 'or', 'pa', 'pl', 'ps', 'pt', 'ro', 'ru', 'sd', 'si', 'sk', 'sl', 'so', 'sq', 'sr', 'ss', 'su', 'sv', 'sw', 'ta', 'th', 'tl', 'tn', 'tr', 'uk', 'ur', 'uz', 'vi', 'wo', 'xh', 'yi', 'yo', 'zh', 'zu'],
'wmt21': ['en', 'ha', 'is', 'ja', 'cs', 'ru', 'zh', 'de']
}
class __lowercase ( __lowerCamelCase ):
snake_case_ = VOCAB_FILES_NAMES
snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case_ = PRETRAINED_VOCAB_FILES_MAP
snake_case_ = ["""input_ids""", """attention_mask"""]
snake_case_ = []
snake_case_ = []
def __init__( self : int ,A : List[Any] ,A : str ,A : List[Any]=None ,A : Dict=None ,A : str="<s>" ,A : int="</s>" ,A : List[Any]="</s>" ,A : Optional[Any]="<pad>" ,A : List[str]="<unk>" ,A : Optional[Any]="m2m100" ,A : Optional[Dict[str, Any]] = None ,A : List[str]=8 ,**A : Optional[Any] ,):
'''simple docstring'''
UpperCAmelCase__ : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs
UpperCAmelCase__ : List[str] = language_codes
UpperCAmelCase__ : Dict = FAIRSEQ_LANGUAGE_CODES[language_codes]
UpperCAmelCase__ : Optional[int] = {lang_code: f"__{lang_code}__" for lang_code in fairseq_language_code}
UpperCAmelCase__ : Tuple = kwargs.get("""additional_special_tokens""" ,[] )
kwargs["additional_special_tokens"] += [
self.get_lang_token(A )
for lang_code in fairseq_language_code
if self.get_lang_token(A ) not in kwargs["additional_special_tokens"]
]
super().__init__(
src_lang=A ,tgt_lang=A ,bos_token=A ,eos_token=A ,sep_token=A ,unk_token=A ,pad_token=A ,language_codes=A ,sp_model_kwargs=self.sp_model_kwargs ,num_madeup_words=A ,**A ,)
UpperCAmelCase__ : str = vocab_file
UpperCAmelCase__ : Dict = load_json(A )
UpperCAmelCase__ : Optional[int] = {v: k for k, v in self.encoder.items()}
UpperCAmelCase__ : Dict = spm_file
UpperCAmelCase__ : List[Any] = load_spm(A ,self.sp_model_kwargs )
UpperCAmelCase__ : Dict = len(self.encoder )
UpperCAmelCase__ : Dict = {
self.get_lang_token(A ): self.encoder_size + i for i, lang_code in enumerate(A )
}
UpperCAmelCase__ : Union[str, Any] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(A )}
UpperCAmelCase__ : Union[str, Any] = {v: k for k, v in self.lang_token_to_id.items()}
UpperCAmelCase__ : List[str] = src_lang if src_lang is not None else """en"""
UpperCAmelCase__ : int = tgt_lang
UpperCAmelCase__ : int = self.get_lang_id(self._src_lang )
self.set_src_lang_special_tokens(self._src_lang )
UpperCAmelCase__ : List[str] = num_madeup_words
@property
def __lowercase ( self : Union[str, Any] ):
'''simple docstring'''
return len(self.encoder ) + len(self.lang_token_to_id )
@property
def __lowercase ( self : Dict ):
'''simple docstring'''
return self._src_lang
@src_lang.setter
def __lowercase ( self : List[str] ,A : str ):
'''simple docstring'''
UpperCAmelCase__ : Tuple = new_src_lang
self.set_src_lang_special_tokens(self._src_lang )
def __lowercase ( self : Optional[Any] ,A : str ):
'''simple docstring'''
return self.sp_model.encode(A ,out_type=A )
def __lowercase ( self : List[str] ,A : Dict ):
'''simple docstring'''
if token in self.lang_token_to_id:
return self.lang_token_to_id[token]
return self.encoder.get(A ,self.encoder[self.unk_token] )
def __lowercase ( self : Any ,A : int ):
'''simple docstring'''
if index in self.id_to_lang_token:
return self.id_to_lang_token[index]
return self.decoder.get(A ,self.unk_token )
def __lowercase ( self : Tuple ,A : List[str] ):
'''simple docstring'''
UpperCAmelCase__ : List[Any] = []
UpperCAmelCase__ : str = """"""
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
out_string += self.sp_model.decode(A ) + token
UpperCAmelCase__ : str = []
else:
current_sub_tokens.append(A )
out_string += self.sp_model.decode(A )
return out_string.strip()
def __lowercase ( self : Optional[int] ,A : List[int] ,A : Optional[List[int]] = None ,A : bool = False ):
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=A ,token_ids_a=A ,already_has_special_tokens=A )
UpperCAmelCase__ : Union[str, Any] = [1] * len(self.prefix_tokens )
UpperCAmelCase__ : Optional[int] = [1] * len(self.suffix_tokens )
if token_ids_a is None:
return prefix_ones + ([0] * len(A )) + suffix_ones
return prefix_ones + ([0] * len(A )) + ([0] * len(A )) + suffix_ones
def __lowercase ( self : Tuple ,A : List[int] ,A : Optional[List[int]] = None ):
'''simple docstring'''
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + self.suffix_tokens
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
def __lowercase ( self : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase__ : Optional[Any] = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : Any ):
'''simple docstring'''
UpperCAmelCase__ : List[Any] = self.__dict__.copy()
UpperCAmelCase__ : Dict = None
return state
def __setstate__( self : int ,A : Dict ):
'''simple docstring'''
UpperCAmelCase__ : Optional[Any] = d
# for backward compatibility
if not hasattr(self ,"""sp_model_kwargs""" ):
UpperCAmelCase__ : Union[str, Any] = {}
UpperCAmelCase__ : List[Any] = load_spm(self.spm_file ,self.sp_model_kwargs )
def __lowercase ( self : Any ,A : str ,A : Optional[str] = None ):
'''simple docstring'''
UpperCAmelCase__ : List[str] = Path(A )
if not save_dir.is_dir():
raise OSError(f"{save_directory} should be a directory" )
UpperCAmelCase__ : Tuple = save_dir / (
(filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""]
)
UpperCAmelCase__ : Any = save_dir / (
(filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""]
)
save_json(self.encoder ,A )
if os.path.abspath(self.spm_file ) != os.path.abspath(A ) and os.path.isfile(self.spm_file ):
copyfile(self.spm_file ,A )
elif not os.path.isfile(self.spm_file ):
with open(A ,"""wb""" ) as fi:
UpperCAmelCase__ : List[str] = self.sp_model.serialized_model_proto()
fi.write(A )
return (str(A ), str(A ))
def __lowercase ( self : str ,A : List[str] ,A : str = "en" ,A : Optional[List[str]] = None ,A : str = "ro" ,**A : List[Any] ,):
'''simple docstring'''
UpperCAmelCase__ : List[Any] = src_lang
UpperCAmelCase__ : str = tgt_lang
self.set_src_lang_special_tokens(self.src_lang )
return super().prepare_seqaseq_batch(A ,A ,**A )
def __lowercase ( self : Any ,A : Union[str, Any] ,A : Optional[str] ,A : Optional[str] ,**A : List[Any] ):
'''simple docstring'''
if src_lang is None or tgt_lang is None:
raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" )
UpperCAmelCase__ : List[Any] = src_lang
UpperCAmelCase__ : List[str] = self(A ,add_special_tokens=A ,**A )
UpperCAmelCase__ : List[Any] = self.get_lang_id(A )
UpperCAmelCase__ : List[str] = tgt_lang_id
return inputs
def __lowercase ( self : Union[str, Any] ):
'''simple docstring'''
self.set_src_lang_special_tokens(self.src_lang )
def __lowercase ( self : List[Any] ):
'''simple docstring'''
self.set_tgt_lang_special_tokens(self.tgt_lang )
def __lowercase ( self : int ,A : str ):
'''simple docstring'''
UpperCAmelCase__ : int = self.get_lang_token(A )
UpperCAmelCase__ : List[str] = self.lang_token_to_id[lang_token]
UpperCAmelCase__ : Union[str, Any] = [self.cur_lang_id]
UpperCAmelCase__ : int = [self.eos_token_id]
def __lowercase ( self : Dict ,A : str ):
'''simple docstring'''
UpperCAmelCase__ : int = self.get_lang_token(A )
UpperCAmelCase__ : List[Any] = self.lang_token_to_id[lang_token]
UpperCAmelCase__ : Optional[int] = [self.cur_lang_id]
UpperCAmelCase__ : str = [self.eos_token_id]
def __lowercase ( self : int ,A : str ):
'''simple docstring'''
return self.lang_code_to_token[lang]
def __lowercase ( self : Dict ,A : str ):
'''simple docstring'''
UpperCAmelCase__ : int = self.get_lang_token(A )
return self.lang_token_to_id[lang_token]
def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ):
'''simple docstring'''
UpperCAmelCase__ : Optional[Any] = sentencepiece.SentencePieceProcessor(**__UpperCamelCase )
spm.Load(str(__UpperCamelCase ) )
return spm
def lowerCAmelCase ( __UpperCamelCase ):
'''simple docstring'''
with open(__UpperCamelCase , """r""" ) as f:
return json.load(__UpperCamelCase )
def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ):
'''simple docstring'''
with open(__UpperCamelCase , """w""" ) as f:
json.dump(__UpperCamelCase , __UpperCamelCase , indent=2 )
| 65 |
import unittest
from transformers import load_tool
from transformers.utils import is_torch_available
if is_torch_available():
import torch
from transformers.testing_utils import require_torch
from .test_tools_common import ToolTesterMixin
@require_torch
class _a (unittest.TestCase , __magic_name__ ):
'''simple docstring'''
def __A ( self ):
A__ : List[str] = load_tool("""text-to-speech""" )
self.tool.setup()
def __A ( self ):
# SpeechT5 isn't deterministic
torch.manual_seed(0 )
A__ : Tuple = self.tool("""hey""" )
A__ : Tuple = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) )
def __A ( self ):
# SpeechT5 isn't deterministic
torch.manual_seed(0 )
A__ : Any = self.tool("""hey""" )
A__ : Optional[Any] = result.to_raw()
self.assertTrue(
torch.allclose(
resulting_tensor[:3] , torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] ) , ) )
| 456 | 0 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
A : int = logging.get_logger(__name__)
A : int = {
'weiweishi/roc-bert-base-zh': 'https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json',
}
class lowerCamelCase ( __UpperCAmelCase ):
_SCREAMING_SNAKE_CASE = "roc_bert"
def __init__( self : Optional[Any] , __snake_case : List[Any]=3_05_22 , __snake_case : Tuple=7_68 , __snake_case : Dict=12 , __snake_case : str=12 , __snake_case : List[Any]=30_72 , __snake_case : Dict="gelu" , __snake_case : List[Any]=0.1 , __snake_case : int=0.1 , __snake_case : Optional[int]=5_12 , __snake_case : str=2 , __snake_case : int=0.02 , __snake_case : Any=1e-12 , __snake_case : List[Any]=True , __snake_case : int=0 , __snake_case : Any="absolute" , __snake_case : List[Any]=None , __snake_case : Tuple=True , __snake_case : Any=True , __snake_case : Optional[int]=7_68 , __snake_case : Optional[Any]=9_10 , __snake_case : Union[str, Any]=5_12 , __snake_case : Optional[int]=2_48_58 , __snake_case : List[Any]=True , **__snake_case : Optional[int] , ):
'''simple docstring'''
_snake_case: str = vocab_size
_snake_case: Union[str, Any] = max_position_embeddings
_snake_case: Optional[Any] = hidden_size
_snake_case: Dict = num_hidden_layers
_snake_case: int = num_attention_heads
_snake_case: Optional[Any] = intermediate_size
_snake_case: Union[str, Any] = hidden_act
_snake_case: List[str] = hidden_dropout_prob
_snake_case: List[str] = attention_probs_dropout_prob
_snake_case: Any = initializer_range
_snake_case: str = type_vocab_size
_snake_case: Tuple = layer_norm_eps
_snake_case: List[Any] = use_cache
_snake_case: Union[str, Any] = enable_pronunciation
_snake_case: int = enable_shape
_snake_case: Union[str, Any] = pronunciation_embed_dim
_snake_case: Optional[int] = pronunciation_vocab_size
_snake_case: str = shape_embed_dim
_snake_case: Dict = shape_vocab_size
_snake_case: List[str] = concat_input
_snake_case: Dict = position_embedding_type
_snake_case: str = classifier_dropout
super().__init__(pad_token_id=__snake_case , **__snake_case )
| 273 |
'''simple docstring'''
A : List[str] = '\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n'
A : List[str] = [{'type': 'code', 'content': INSTALL_CONTENT}]
A : Dict = {
'{processor_class}': 'FakeProcessorClass',
'{model_class}': 'FakeModelClass',
'{object_class}': 'FakeObjectClass',
}
| 273 | 1 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_squeezebert import SqueezeBertTokenizer
__A : Union[str, Any] = logging.get_logger(__name__)
__A : Optional[Any] = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
__A : Any = {
"vocab_file": {
"squeezebert/squeezebert-uncased": (
"https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt"
),
"squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt",
"squeezebert/squeezebert-mnli-headless": (
"https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"squeezebert/squeezebert-uncased": (
"https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json"
),
"squeezebert/squeezebert-mnli": (
"https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json"
),
"squeezebert/squeezebert-mnli-headless": (
"https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json"
),
},
}
__A : Union[str, Any] = {
"squeezebert/squeezebert-uncased": 512,
"squeezebert/squeezebert-mnli": 512,
"squeezebert/squeezebert-mnli-headless": 512,
}
__A : List[str] = {
"squeezebert/squeezebert-uncased": {"do_lower_case": True},
"squeezebert/squeezebert-mnli": {"do_lower_case": True},
"squeezebert/squeezebert-mnli-headless": {"do_lower_case": True},
}
class lowerCamelCase( __snake_case ):
'''simple docstring'''
__magic_name__ = VOCAB_FILES_NAMES
__magic_name__ = PRETRAINED_VOCAB_FILES_MAP
__magic_name__ = PRETRAINED_INIT_CONFIGURATION
__magic_name__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__magic_name__ = SqueezeBertTokenizer
def __init__( self , snake_case_=None , snake_case_=None , snake_case_=True , snake_case_="[UNK]" , snake_case_="[SEP]" , snake_case_="[PAD]" , snake_case_="[CLS]" , snake_case_="[MASK]" , snake_case_=True , snake_case_=None , **snake_case_ , ):
super().__init__(
snake_case_ , tokenizer_file=snake_case_ , do_lower_case=snake_case_ , unk_token=snake_case_ , sep_token=snake_case_ , pad_token=snake_case_ , cls_token=snake_case_ , mask_token=snake_case_ , tokenize_chinese_chars=snake_case_ , strip_accents=snake_case_ , **snake_case_ , )
_A = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get('lowercase' , snake_case_ ) != do_lower_case
or normalizer_state.get('strip_accents' , snake_case_ ) != strip_accents
or normalizer_state.get('handle_chinese_chars' , snake_case_ ) != tokenize_chinese_chars
):
_A = getattr(snake_case_ , normalizer_state.pop('type' ) )
_A = do_lower_case
_A = strip_accents
_A = tokenize_chinese_chars
_A = normalizer_class(**snake_case_ )
_A = do_lower_case
def lowerCAmelCase__ ( self , snake_case_ , snake_case_=None ):
_A = [self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def lowerCAmelCase__ ( self , snake_case_ , snake_case_ = None ):
_A = [self.sep_token_id]
_A = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def lowerCAmelCase__ ( self , snake_case_ , snake_case_ = None ):
_A = self._tokenizer.model.save(snake_case_ , name=snake_case_ )
return tuple(snake_case_ )
| 27 |
"""simple docstring"""
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow
from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin
enable_full_determinism()
class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
__UpperCAmelCase : Union[str, Any] = StableDiffusionInpaintPipeline
__UpperCAmelCase : int = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
__UpperCAmelCase : str = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
__UpperCAmelCase : int = frozenset(
[] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
__UpperCAmelCase : Tuple = frozenset([] )
def __UpperCAmelCase ( self ):
torch.manual_seed(0 )
__a = UNetaDConditionModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_a , )
__a = PNDMScheduler(skip_prk_steps=_a )
torch.manual_seed(0 )
__a = AutoencoderKL(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , )
torch.manual_seed(0 )
__a = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act='''gelu''' , projection_dim=512 , )
__a = CLIPTextModel(_a )
__a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )
__a = {
'''unet''': unet,
'''scheduler''': scheduler,
'''vae''': vae,
'''text_encoder''': text_encoder,
'''tokenizer''': tokenizer,
'''safety_checker''': None,
'''feature_extractor''': None,
}
return components
def __UpperCAmelCase ( self , _a , _a=0 ):
# TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
__a = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a )
__a = image.cpu().permute(0 , 2 , 3 , 1 )[0]
__a = Image.fromarray(np.uinta(_a ) ).convert('''RGB''' ).resize((64, 64) )
__a = Image.fromarray(np.uinta(image + 4 ) ).convert('''RGB''' ).resize((64, 64) )
if str(_a ).startswith('''mps''' ):
__a = torch.manual_seed(_a )
else:
__a = torch.Generator(device=_a ).manual_seed(_a )
__a = {
'''prompt''': '''A painting of a squirrel eating a burger''',
'''image''': init_image,
'''mask_image''': mask_image,
'''generator''': generator,
'''num_inference_steps''': 2,
'''guidance_scale''': 6.0,
'''output_type''': '''numpy''',
}
return inputs
def __UpperCAmelCase ( self ):
__a = '''cpu''' # ensure determinism for the device-dependent torch.Generator
__a = self.get_dummy_components()
__a = StableDiffusionInpaintPipeline(**_a )
__a = sd_pipe.to(_a )
sd_pipe.set_progress_bar_config(disable=_a )
__a = self.get_dummy_inputs(_a )
__a = sd_pipe(**_a ).images
__a = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
__a = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def __UpperCAmelCase ( self ):
super().test_inference_batch_single_identical(expected_max_diff=3E-3 )
@slow
@require_torch_gpu
class __lowerCAmelCase ( unittest.TestCase ):
'''simple docstring'''
def __UpperCAmelCase ( self ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __UpperCAmelCase ( self ):
__a = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/sd2-inpaint/init_image.png''' )
__a = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' )
__a = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint'''
'''/yellow_cat_sitting_on_a_park_bench.npy''' )
__a = '''stabilityai/stable-diffusion-2-inpainting'''
__a = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a )
pipe.to(_a )
pipe.set_progress_bar_config(disable=_a )
pipe.enable_attention_slicing()
__a = '''Face of a yellow cat, high resolution, sitting on a park bench'''
__a = torch.manual_seed(0 )
__a = pipe(
prompt=_a , image=_a , mask_image=_a , generator=_a , output_type='''np''' , )
__a = output.images[0]
assert image.shape == (512, 512, 3)
assert np.abs(expected_image - image ).max() < 9E-3
def __UpperCAmelCase ( self ):
__a = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/sd2-inpaint/init_image.png''' )
__a = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' )
__a = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint'''
'''/yellow_cat_sitting_on_a_park_bench_fp16.npy''' )
__a = '''stabilityai/stable-diffusion-2-inpainting'''
__a = StableDiffusionInpaintPipeline.from_pretrained(
_a , torch_dtype=torch.floataa , safety_checker=_a , )
pipe.to(_a )
pipe.set_progress_bar_config(disable=_a )
pipe.enable_attention_slicing()
__a = '''Face of a yellow cat, high resolution, sitting on a park bench'''
__a = torch.manual_seed(0 )
__a = pipe(
prompt=_a , image=_a , mask_image=_a , generator=_a , output_type='''np''' , )
__a = output.images[0]
assert image.shape == (512, 512, 3)
assert np.abs(expected_image - image ).max() < 5E-1
def __UpperCAmelCase ( self ):
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated()
torch.cuda.reset_peak_memory_stats()
__a = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/sd2-inpaint/init_image.png''' )
__a = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' )
__a = '''stabilityai/stable-diffusion-2-inpainting'''
__a = PNDMScheduler.from_pretrained(_a , subfolder='''scheduler''' )
__a = StableDiffusionInpaintPipeline.from_pretrained(
_a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , )
pipe.to(_a )
pipe.set_progress_bar_config(disable=_a )
pipe.enable_attention_slicing(1 )
pipe.enable_sequential_cpu_offload()
__a = '''Face of a yellow cat, high resolution, sitting on a park bench'''
__a = torch.manual_seed(0 )
__a = pipe(
prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type='''np''' , )
__a = torch.cuda.max_memory_allocated()
# make sure that less than 2.65 GB is allocated
assert mem_bytes < 2.65 * 10**9
| 695 | 0 |
"""simple docstring"""
import unittest
from transformers import AlbertTokenizer, AlbertTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
__A = get_tests_dir("""fixtures/spiece.model""")
@require_sentencepiece
@require_tokenizers
class _lowerCAmelCase ( a , unittest.TestCase ):
"""simple docstring"""
__magic_name__ :Any = AlbertTokenizer
__magic_name__ :Optional[Any] = AlbertTokenizerFast
__magic_name__ :str = True
__magic_name__ :List[str] = True
__magic_name__ :Optional[int] = True
def snake_case ( self ):
'''simple docstring'''
super().setUp()
# We have a SentencePiece fixture for testing
lowerCAmelCase__ :List[Any] = AlbertTokenizer(__UpperCAmelCase )
tokenizer.save_pretrained(self.tmpdirname )
def snake_case ( self , __UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase__ :str = 'this is a test'
lowerCAmelCase__ :List[str] = 'this is a test'
return input_text, output_text
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :List[str] = '<pad>'
lowerCAmelCase__ :int = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase )
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Dict = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '<pad>' )
self.assertEqual(vocab_keys[1] , '<unk>' )
self.assertEqual(vocab_keys[-1] , '▁eloquent' )
self.assertEqual(len(__UpperCAmelCase ) , 3_0_0_0_0 )
def snake_case ( self ):
'''simple docstring'''
self.assertEqual(self.get_tokenizer().vocab_size , 3_0_0_0_0 )
def snake_case ( self ):
'''simple docstring'''
if not self.test_rust_tokenizer:
return
lowerCAmelCase__ :Tuple = self.get_tokenizer()
lowerCAmelCase__ :Optional[int] = self.get_rust_tokenizer()
lowerCAmelCase__ :List[Any] = 'I was born in 92000, and this is falsé.'
lowerCAmelCase__ :Tuple = tokenizer.tokenize(__UpperCAmelCase )
lowerCAmelCase__ :Tuple = rust_tokenizer.tokenize(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
lowerCAmelCase__ :List[str] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase )
lowerCAmelCase__ :str = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
lowerCAmelCase__ :str = self.get_rust_tokenizer()
lowerCAmelCase__ :Tuple = tokenizer.encode(__UpperCAmelCase )
lowerCAmelCase__ :Dict = rust_tokenizer.encode(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :int = AlbertTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase )
lowerCAmelCase__ :str = tokenizer.tokenize('This is a test' )
self.assertListEqual(__UpperCAmelCase , ['▁this', '▁is', '▁a', '▁test'] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [4_8, 2_5, 2_1, 1_2_8_9] )
lowerCAmelCase__ :Any = tokenizer.tokenize('I was born in 92000, and this is falsé.' )
self.assertListEqual(
__UpperCAmelCase , ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.'] )
lowerCAmelCase__ :Any = tokenizer.convert_tokens_to_ids(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , [3_1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9] )
lowerCAmelCase__ :Tuple = tokenizer.convert_ids_to_tokens(__UpperCAmelCase )
self.assertListEqual(
__UpperCAmelCase , ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.'] , )
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Optional[Any] = AlbertTokenizer(__UpperCAmelCase )
lowerCAmelCase__ :int = tokenizer.encode('sequence builders' )
lowerCAmelCase__ :Union[str, Any] = tokenizer.encode('multi-sequence build' )
lowerCAmelCase__ :Any = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase )
lowerCAmelCase__ :Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase )
assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [
tokenizer.sep_token_id
]
@slow
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Dict = {'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'input_ids': [[2, 2_1_9_7_0, 1_3, 5, 6_0_9_2, 1_6_7, 2_8, 7_1_0_3, 2_1_5_3, 6_7_3, 8, 7_0_2_8, 1_2_0_5_1, 1_8, 1_7, 7_1_0_3, 2_1_5_3, 6_7_3, 8, 3_5_1_5, 1_8_6_8_4, 8, 4_4_6_1, 6, 1_9_2_7, 2_9_7, 8, 1_2_0_6_0, 2_6_0_7, 1_8, 1_3, 5, 4_4_6_1, 1_5, 1_0_5_3_8, 3_8, 8, 1_3_5, 1_5, 8_2_2, 5_8, 1_5, 9_9_3, 1_0_3_6_3, 1_5, 1_4_6_0, 8_0_0_5, 4_4_6_1, 1_5, 9_9_3, 2_5_5, 2_3_2_8, 9, 9, 9, 6, 2_6, 1_1_1_2, 8_1_6, 3_2_6_0, 1_3, 5, 1_0_3, 2_3_7_7, 6, 1_7, 1_1_1_2, 8_1_6, 2_7_8_2, 1_3, 5, 1_0_3, 1_0_6_4_1, 6, 2_9, 8_4, 2_5_1_2, 2_4_3_0, 7_8_2, 1_8_6_8_4, 2_7_6_1, 1_9, 8_0_8, 2_4_3_0, 2_5_5_6, 1_7, 8_5_5, 1_4_8_0, 9_4_7_7, 4_0_9_1, 1_2_8, 1_1_7_1_2, 1_5, 7_1_0_3, 2_1_5_3, 6_7_3, 1_7, 2_4_8_8_3, 9_9_9_0, 9, 3], [2, 1_1_5_0_2, 2_5, 1_0_0_6, 2_0, 7_8_2, 8, 1_1_8_0_9, 8_5_5, 1_7_3_2, 1_9_3_9_3, 1_8_6_6_7, 3_7, 3_6_7, 2_1_0_1_8, 6_9, 1_8_5_4, 3_4, 1_1_8_6_0, 1_9_1_2_4, 2_7, 1_5_6, 2_2_5, 1_7, 1_9_3, 4_1_4_1, 1_9, 6_5, 9_1_2_4, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 1_4, 2_2_3_1, 8_8_6, 2_3_8_5, 1_7_6_5_9, 8_4, 1_4, 1_6_7_9_2, 1_9_5_2, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=__UpperCAmelCase , model_name='albert-base-v2' , revision='6b6560eaf5ff2e250b00c50f380c5389a9c2d82e' , )
| 560 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available
from ...utils import OptionalDependencyNotAvailable
__A = {"""configuration_dpt""": ["""DPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DPTConfig"""]}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ["""DPTFeatureExtractor"""]
__A = ["""DPTImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"""DPT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""DPTForDepthEstimation""",
"""DPTForSemanticSegmentation""",
"""DPTModel""",
"""DPTPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_dpt import DPTFeatureExtractor
from .image_processing_dpt import DPTImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_dpt import (
DPT_PRETRAINED_MODEL_ARCHIVE_LIST,
DPTForDepthEstimation,
DPTForSemanticSegmentation,
DPTModel,
DPTPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 560 | 1 |
import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import Audio, Features, Value
from .base import TaskTemplate
@dataclass(frozen=UpperCAmelCase )
class __A( UpperCAmelCase ):
SCREAMING_SNAKE_CASE = field(default='''automatic-speech-recognition''' , metadata={'''include_in_asdict_even_if_is_default''': True} )
SCREAMING_SNAKE_CASE = Features({'''audio''': Audio()} )
SCREAMING_SNAKE_CASE = Features({'''transcription''': Value('''string''' )} )
SCREAMING_SNAKE_CASE = "audio"
SCREAMING_SNAKE_CASE = "transcription"
def lowercase__ ( self : Optional[Any] , __UpperCamelCase : Optional[int] ):
if self.audio_column not in features:
raise ValueError(F'''Column {self.audio_column} is not present in features.''' )
if not isinstance(features[self.audio_column] , __UpperCamelCase ):
raise ValueError(F'''Column {self.audio_column} is not an Audio type.''' )
lowerCamelCase_ = copy.deepcopy(self )
lowerCamelCase_ = self.input_schema.copy()
lowerCamelCase_ = features[self.audio_column]
lowerCamelCase_ = input_schema
return task_template
@property
def lowercase__ ( self : str ):
return {self.audio_column: "audio", self.transcription_column: "transcription"}
| 272 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowercase = logging.get_logger(__name__)
lowercase = {
'''abeja/gpt-neox-japanese-2.7b''': '''https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json''',
}
class __A( UpperCAmelCase ):
SCREAMING_SNAKE_CASE = '''gpt_neox_japanese'''
def __init__( self : Union[str, Any] , __UpperCamelCase : str=3_2_0_0_0 , __UpperCamelCase : List[Any]=2_5_6_0 , __UpperCamelCase : Any=3_2 , __UpperCamelCase : List[str]=3_2 , __UpperCamelCase : List[str]=4 , __UpperCamelCase : Dict="gelu" , __UpperCamelCase : List[Any]=1.00 , __UpperCamelCase : Any=1_0_0_0_0 , __UpperCamelCase : Optional[Any]=2_0_4_8 , __UpperCamelCase : Tuple=0.02 , __UpperCamelCase : List[str]=1E-5 , __UpperCamelCase : str=True , __UpperCamelCase : str=3_1_9_9_6 , __UpperCamelCase : int=3_1_9_9_9 , __UpperCamelCase : Optional[Any]=0.1 , __UpperCamelCase : Tuple=0.0 , **__UpperCamelCase : List[str] , ):
super().__init__(bos_token_id=__UpperCamelCase , eos_token_id=__UpperCamelCase , **__UpperCamelCase )
lowerCamelCase_ = vocab_size
lowerCamelCase_ = max_position_embeddings
lowerCamelCase_ = hidden_size
lowerCamelCase_ = num_hidden_layers
lowerCamelCase_ = num_attention_heads
lowerCamelCase_ = intermediate_multiple_size
lowerCamelCase_ = hidden_act
lowerCamelCase_ = rotary_pct
lowerCamelCase_ = rotary_emb_base
lowerCamelCase_ = initializer_range
lowerCamelCase_ = layer_norm_eps
lowerCamelCase_ = use_cache
lowerCamelCase_ = attention_dropout
lowerCamelCase_ = hidden_dropout
| 272 | 1 |
'''simple docstring'''
import unittest
from transformers import AlbertTokenizer, AlbertTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
a : int = get_tests_dir("""fixtures/spiece.model""")
@require_sentencepiece
@require_tokenizers
class UpperCamelCase_ ( __magic_name__ , unittest.TestCase ):
lowercase = AlbertTokenizer
lowercase = AlbertTokenizerFast
lowercase = True
lowercase = True
lowercase = True
def _lowercase( self ) -> Tuple:
super().setUp()
# We have a SentencePiece fixture for testing
UpperCAmelCase : Union[str, Any] = AlbertTokenizer(A )
tokenizer.save_pretrained(self.tmpdirname )
def _lowercase( self , A ) -> int:
UpperCAmelCase : str = """this is a test"""
UpperCAmelCase : Any = """this is a test"""
return input_text, output_text
def _lowercase( self ) -> Optional[int]:
UpperCAmelCase : int = """<pad>"""
UpperCAmelCase : Any = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(A ) , A )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(A ) , A )
def _lowercase( self ) -> Union[str, Any]:
UpperCAmelCase : str = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , """<pad>""" )
self.assertEqual(vocab_keys[1] , """<unk>""" )
self.assertEqual(vocab_keys[-1] , """▁eloquent""" )
self.assertEqual(len(A ) , 30000 )
def _lowercase( self ) -> str:
self.assertEqual(self.get_tokenizer().vocab_size , 30000 )
def _lowercase( self ) -> Optional[int]:
if not self.test_rust_tokenizer:
return
UpperCAmelCase : Union[str, Any] = self.get_tokenizer()
UpperCAmelCase : Optional[int] = self.get_rust_tokenizer()
UpperCAmelCase : Optional[int] = """I was born in 92000, and this is falsé."""
UpperCAmelCase : List[Any] = tokenizer.tokenize(A )
UpperCAmelCase : Union[str, Any] = rust_tokenizer.tokenize(A )
self.assertListEqual(A , A )
UpperCAmelCase : Optional[int] = tokenizer.encode(A , add_special_tokens=A )
UpperCAmelCase : Tuple = rust_tokenizer.encode(A , add_special_tokens=A )
self.assertListEqual(A , A )
UpperCAmelCase : Union[str, Any] = self.get_rust_tokenizer()
UpperCAmelCase : Dict = tokenizer.encode(A )
UpperCAmelCase : List[Any] = rust_tokenizer.encode(A )
self.assertListEqual(A , A )
def _lowercase( self ) -> Optional[int]:
UpperCAmelCase : List[Any] = AlbertTokenizer(A , keep_accents=A )
UpperCAmelCase : Union[str, Any] = tokenizer.tokenize("""This is a test""" )
self.assertListEqual(A , ["""▁this""", """▁is""", """▁a""", """▁test"""] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) , [48, 25, 21, 1289] )
UpperCAmelCase : List[str] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" )
self.assertListEqual(
A , ["""▁i""", """▁was""", """▁born""", """▁in""", """▁9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """é""", """."""] )
UpperCAmelCase : Tuple = tokenizer.convert_tokens_to_ids(A )
self.assertListEqual(A , [31, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9] )
UpperCAmelCase : Any = tokenizer.convert_ids_to_tokens(A )
self.assertListEqual(
A , ["""▁i""", """▁was""", """▁born""", """▁in""", """▁9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """<unk>""", """."""] , )
def _lowercase( self ) -> Optional[Any]:
UpperCAmelCase : int = AlbertTokenizer(A )
UpperCAmelCase : Dict = tokenizer.encode("""sequence builders""" )
UpperCAmelCase : int = tokenizer.encode("""multi-sequence build""" )
UpperCAmelCase : List[Any] = tokenizer.build_inputs_with_special_tokens(A )
UpperCAmelCase : List[Any] = tokenizer.build_inputs_with_special_tokens(A , A )
assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [
tokenizer.sep_token_id
]
@slow
def _lowercase( self ) -> Union[str, Any]:
# fmt: off
UpperCAmelCase : Union[str, Any] = {"""attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """input_ids""": [[2, 21970, 13, 5, 6092, 167, 28, 7103, 2153, 673, 8, 7028, 12051, 18, 17, 7103, 2153, 673, 8, 3515, 18684, 8, 4461, 6, 1927, 297, 8, 12060, 2607, 18, 13, 5, 4461, 15, 10538, 38, 8, 135, 15, 822, 58, 15, 993, 10363, 15, 1460, 8005, 4461, 15, 993, 255, 2328, 9, 9, 9, 6, 26, 1112, 816, 3260, 13, 5, 103, 2377, 6, 17, 1112, 816, 2782, 13, 5, 103, 10641, 6, 29, 84, 2512, 2430, 782, 18684, 2761, 19, 808, 2430, 2556, 17, 855, 1480, 9477, 4091, 128, 11712, 15, 7103, 2153, 673, 17, 24883, 9990, 9, 3], [2, 11502, 25, 1006, 20, 782, 8, 11809, 855, 1732, 19393, 18667, 37, 367, 21018, 69, 1854, 34, 11860, 19124, 27, 156, 225, 17, 193, 4141, 19, 65, 9124, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 14, 2231, 886, 2385, 17659, 84, 14, 16792, 1952, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """token_type_ids""": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=A , model_name="""albert-base-v2""" , revision="""6b6560eaf5ff2e250b00c50f380c5389a9c2d82e""" , )
| 672 |
'''simple docstring'''
from scipy.stats import pearsonr
import datasets
a : str = """
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.
"""
a : Dict = """
Args:
predictions (`list` of `int`): Predicted class labels, as returned by a model.
references (`list` of `int`): Ground truth labels.
return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.
Returns:
pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.
p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.
Examples:
Example 1-A simple example using only predictions and references.
>>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
>>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
>>> print(round(results['pearsonr'], 2))
-0.74
Example 2-The same as Example 1, but that also returns the `p-value`.
>>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
>>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
>>> print(sorted(list(results.keys())))
['p-value', 'pearsonr']
>>> print(round(results['pearsonr'], 2))
-0.74
>>> print(round(results['p-value'], 2))
0.15
"""
a : Optional[int] = """
@article{2020SciPy-NMeth,
author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
Haberland, Matt and Reddy, Tyler and Cournapeau, David and
Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
Kern, Robert and Larson, Eric and Carey, C J and
Polat, Ilhan and Feng, Yu and Moore, Eric W. and
{VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
Harris, Charles R. and Archibald, Anne M. and
Ribeiro, Antonio H. and Pedregosa, Fabian and
{van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
Computing in Python}},
journal = {Nature Methods},
year = {2020},
volume = {17},
pages = {261--272},
adsurl = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class UpperCamelCase_ ( datasets.Metric ):
def _lowercase( self ) -> Optional[int]:
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"""predictions""": datasets.Value("""float""" ),
"""references""": datasets.Value("""float""" ),
} ) , reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html"""] , )
def _lowercase( self , A , A , A=False ) -> int:
if return_pvalue:
UpperCAmelCase : int = pearsonr(A , A )
return {"pearsonr": results[0], "p-value": results[1]}
else:
return {"pearsonr": float(pearsonr(A , A )[0] )}
| 672 | 1 |
'''simple docstring'''
from __future__ import annotations
import numpy as np
def UpperCamelCase_ ( A__ : np.ndarray ):
'''simple docstring'''
lowerCAmelCase_ : Tuple = np.shape(a_ )
if rows != columns:
lowerCAmelCase_ : Dict = (
'''\'table\' has to be of square shaped array but got a '''
f'{rows}x{columns} array:\n{table}'
)
raise ValueError(a_ )
lowerCAmelCase_ : Optional[Any] = np.zeros((rows, columns) )
lowerCAmelCase_ : Any = np.zeros((rows, columns) )
for i in range(a_ ):
for j in range(a_ ):
lowerCAmelCase_ : Optional[Any] = sum(lower[i][k] * upper[k][j] for k in range(a_ ) )
if upper[j][j] == 0:
raise ArithmeticError("""No LU decomposition exists""" )
lowerCAmelCase_ : List[Any] = (table[i][j] - total) / upper[j][j]
lowerCAmelCase_ : Optional[int] = 1
for j in range(a_ , a_ ):
lowerCAmelCase_ : Dict = sum(lower[i][k] * upper[k][j] for k in range(a_ ) )
lowerCAmelCase_ : int = table[i][j] - total
return lower, upper
if __name__ == "__main__":
import doctest
doctest.testmod()
| 275 |
"""simple docstring"""
from typing import Any, Callable, Dict, List, Optional, Union
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DiffusionPipeline,
LMSDiscreteScheduler,
PNDMScheduler,
StableDiffusionPipeline,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
lowerCamelCase__ : Union[str, Any] = "CompVis/stable-diffusion-v1-1"
lowerCamelCase__ : Optional[Any] = "CompVis/stable-diffusion-v1-2"
lowerCamelCase__ : Dict = "CompVis/stable-diffusion-v1-3"
lowerCamelCase__ : List[str] = "CompVis/stable-diffusion-v1-4"
class lowercase__( _UpperCAmelCase ):
'''simple docstring'''
def __init__( self :Any , lowerCamelCase_ :AutoencoderKL , lowerCamelCase_ :CLIPTextModel , lowerCamelCase_ :CLIPTokenizer , lowerCamelCase_ :UNetaDConditionModel , lowerCamelCase_ :Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , lowerCamelCase_ :StableDiffusionSafetyChecker , lowerCamelCase_ :CLIPImageProcessor , lowerCamelCase_ :bool = True , ) -> List[str]:
'''simple docstring'''
super()._init_()
SCREAMING_SNAKE_CASE : Tuple = StableDiffusionPipeline.from_pretrained(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Dict = StableDiffusionPipeline.from_pretrained(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Dict = StableDiffusionPipeline.from_pretrained(lowerCamelCase_ )
SCREAMING_SNAKE_CASE : Dict = StableDiffusionPipeline(
vae=lowerCamelCase_ , text_encoder=lowerCamelCase_ , tokenizer=lowerCamelCase_ , unet=lowerCamelCase_ , scheduler=lowerCamelCase_ , safety_checker=lowerCamelCase_ , feature_extractor=lowerCamelCase_ , requires_safety_checker=lowerCamelCase_ , )
self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea )
@property
def __lowerCAmelCase ( self :Dict ) -> Dict[str, Any]:
'''simple docstring'''
return {k: getattr(self , lowerCamelCase_ ) for k in self.config.keys() if not k.startswith('''_''' )}
def __lowerCAmelCase ( self :int , lowerCamelCase_ :Optional[Union[str, int]] = "auto" ) -> Tuple:
'''simple docstring'''
if slice_size == "auto":
# half the attention head size is usually a good trade-off between
# speed and memory
SCREAMING_SNAKE_CASE : str = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(lowerCamelCase_ )
def __lowerCAmelCase ( self :Union[str, Any] ) -> Dict:
'''simple docstring'''
self.enable_attention_slicing(lowerCamelCase_ )
@torch.no_grad()
def __lowerCAmelCase ( self :Union[str, Any] , lowerCamelCase_ :Union[str, List[str]] , lowerCamelCase_ :int = 5_12 , lowerCamelCase_ :int = 5_12 , lowerCamelCase_ :int = 50 , lowerCamelCase_ :float = 7.5 , lowerCamelCase_ :Optional[Union[str, List[str]]] = None , lowerCamelCase_ :Optional[int] = 1 , lowerCamelCase_ :float = 0.0 , lowerCamelCase_ :Optional[torch.Generator] = None , lowerCamelCase_ :Optional[torch.FloatTensor] = None , lowerCamelCase_ :Optional[str] = "pil" , lowerCamelCase_ :bool = True , lowerCamelCase_ :Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowerCamelCase_ :int = 1 , **lowerCamelCase_ :List[str] , ) -> Tuple:
'''simple docstring'''
return self.pipea(
prompt=lowerCamelCase_ , height=lowerCamelCase_ , width=lowerCamelCase_ , num_inference_steps=lowerCamelCase_ , guidance_scale=lowerCamelCase_ , negative_prompt=lowerCamelCase_ , num_images_per_prompt=lowerCamelCase_ , eta=lowerCamelCase_ , generator=lowerCamelCase_ , latents=lowerCamelCase_ , output_type=lowerCamelCase_ , return_dict=lowerCamelCase_ , callback=lowerCamelCase_ , callback_steps=lowerCamelCase_ , **lowerCamelCase_ , )
@torch.no_grad()
def __lowerCAmelCase ( self :int , lowerCamelCase_ :Union[str, List[str]] , lowerCamelCase_ :int = 5_12 , lowerCamelCase_ :int = 5_12 , lowerCamelCase_ :int = 50 , lowerCamelCase_ :float = 7.5 , lowerCamelCase_ :Optional[Union[str, List[str]]] = None , lowerCamelCase_ :Optional[int] = 1 , lowerCamelCase_ :float = 0.0 , lowerCamelCase_ :Optional[torch.Generator] = None , lowerCamelCase_ :Optional[torch.FloatTensor] = None , lowerCamelCase_ :Optional[str] = "pil" , lowerCamelCase_ :bool = True , lowerCamelCase_ :Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowerCamelCase_ :int = 1 , **lowerCamelCase_ :Tuple , ) -> Optional[Any]:
'''simple docstring'''
return self.pipea(
prompt=lowerCamelCase_ , height=lowerCamelCase_ , width=lowerCamelCase_ , num_inference_steps=lowerCamelCase_ , guidance_scale=lowerCamelCase_ , negative_prompt=lowerCamelCase_ , num_images_per_prompt=lowerCamelCase_ , eta=lowerCamelCase_ , generator=lowerCamelCase_ , latents=lowerCamelCase_ , output_type=lowerCamelCase_ , return_dict=lowerCamelCase_ , callback=lowerCamelCase_ , callback_steps=lowerCamelCase_ , **lowerCamelCase_ , )
@torch.no_grad()
def __lowerCAmelCase ( self :Dict , lowerCamelCase_ :Union[str, List[str]] , lowerCamelCase_ :int = 5_12 , lowerCamelCase_ :int = 5_12 , lowerCamelCase_ :int = 50 , lowerCamelCase_ :float = 7.5 , lowerCamelCase_ :Optional[Union[str, List[str]]] = None , lowerCamelCase_ :Optional[int] = 1 , lowerCamelCase_ :float = 0.0 , lowerCamelCase_ :Optional[torch.Generator] = None , lowerCamelCase_ :Optional[torch.FloatTensor] = None , lowerCamelCase_ :Optional[str] = "pil" , lowerCamelCase_ :bool = True , lowerCamelCase_ :Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowerCamelCase_ :int = 1 , **lowerCamelCase_ :Dict , ) -> List[str]:
'''simple docstring'''
return self.pipea(
prompt=lowerCamelCase_ , height=lowerCamelCase_ , width=lowerCamelCase_ , num_inference_steps=lowerCamelCase_ , guidance_scale=lowerCamelCase_ , negative_prompt=lowerCamelCase_ , num_images_per_prompt=lowerCamelCase_ , eta=lowerCamelCase_ , generator=lowerCamelCase_ , latents=lowerCamelCase_ , output_type=lowerCamelCase_ , return_dict=lowerCamelCase_ , callback=lowerCamelCase_ , callback_steps=lowerCamelCase_ , **lowerCamelCase_ , )
@torch.no_grad()
def __lowerCAmelCase ( self :int , lowerCamelCase_ :Union[str, List[str]] , lowerCamelCase_ :int = 5_12 , lowerCamelCase_ :int = 5_12 , lowerCamelCase_ :int = 50 , lowerCamelCase_ :float = 7.5 , lowerCamelCase_ :Optional[Union[str, List[str]]] = None , lowerCamelCase_ :Optional[int] = 1 , lowerCamelCase_ :float = 0.0 , lowerCamelCase_ :Optional[torch.Generator] = None , lowerCamelCase_ :Optional[torch.FloatTensor] = None , lowerCamelCase_ :Optional[str] = "pil" , lowerCamelCase_ :bool = True , lowerCamelCase_ :Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowerCamelCase_ :int = 1 , **lowerCamelCase_ :List[Any] , ) -> Optional[Any]:
'''simple docstring'''
return self.pipea(
prompt=lowerCamelCase_ , height=lowerCamelCase_ , width=lowerCamelCase_ , num_inference_steps=lowerCamelCase_ , guidance_scale=lowerCamelCase_ , negative_prompt=lowerCamelCase_ , num_images_per_prompt=lowerCamelCase_ , eta=lowerCamelCase_ , generator=lowerCamelCase_ , latents=lowerCamelCase_ , output_type=lowerCamelCase_ , return_dict=lowerCamelCase_ , callback=lowerCamelCase_ , callback_steps=lowerCamelCase_ , **lowerCamelCase_ , )
@torch.no_grad()
def __lowerCAmelCase ( self :Optional[Any] , lowerCamelCase_ :Union[str, List[str]] , lowerCamelCase_ :int = 5_12 , lowerCamelCase_ :int = 5_12 , lowerCamelCase_ :int = 50 , lowerCamelCase_ :float = 7.5 , lowerCamelCase_ :Optional[Union[str, List[str]]] = None , lowerCamelCase_ :Optional[int] = 1 , lowerCamelCase_ :float = 0.0 , lowerCamelCase_ :Optional[torch.Generator] = None , lowerCamelCase_ :Optional[torch.FloatTensor] = None , lowerCamelCase_ :Optional[str] = "pil" , lowerCamelCase_ :bool = True , lowerCamelCase_ :Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowerCamelCase_ :int = 1 , **lowerCamelCase_ :Optional[Any] , ) -> Tuple:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[int] = '''cuda''' if torch.cuda.is_available() else '''cpu'''
self.to(lowerCamelCase_ )
# Checks if the height and width are divisible by 8 or not
if height % 8 != 0 or width % 8 != 0:
raise ValueError(f"`height` and `width` must be divisible by 8 but are {height} and {width}." )
# Get first result from Stable Diffusion Checkpoint v1.1
SCREAMING_SNAKE_CASE : str = self.textaimg_sda_a(
prompt=lowerCamelCase_ , height=lowerCamelCase_ , width=lowerCamelCase_ , num_inference_steps=lowerCamelCase_ , guidance_scale=lowerCamelCase_ , negative_prompt=lowerCamelCase_ , num_images_per_prompt=lowerCamelCase_ , eta=lowerCamelCase_ , generator=lowerCamelCase_ , latents=lowerCamelCase_ , output_type=lowerCamelCase_ , return_dict=lowerCamelCase_ , callback=lowerCamelCase_ , callback_steps=lowerCamelCase_ , **lowerCamelCase_ , )
# Get first result from Stable Diffusion Checkpoint v1.2
SCREAMING_SNAKE_CASE : Optional[Any] = self.textaimg_sda_a(
prompt=lowerCamelCase_ , height=lowerCamelCase_ , width=lowerCamelCase_ , num_inference_steps=lowerCamelCase_ , guidance_scale=lowerCamelCase_ , negative_prompt=lowerCamelCase_ , num_images_per_prompt=lowerCamelCase_ , eta=lowerCamelCase_ , generator=lowerCamelCase_ , latents=lowerCamelCase_ , output_type=lowerCamelCase_ , return_dict=lowerCamelCase_ , callback=lowerCamelCase_ , callback_steps=lowerCamelCase_ , **lowerCamelCase_ , )
# Get first result from Stable Diffusion Checkpoint v1.3
SCREAMING_SNAKE_CASE : Tuple = self.textaimg_sda_a(
prompt=lowerCamelCase_ , height=lowerCamelCase_ , width=lowerCamelCase_ , num_inference_steps=lowerCamelCase_ , guidance_scale=lowerCamelCase_ , negative_prompt=lowerCamelCase_ , num_images_per_prompt=lowerCamelCase_ , eta=lowerCamelCase_ , generator=lowerCamelCase_ , latents=lowerCamelCase_ , output_type=lowerCamelCase_ , return_dict=lowerCamelCase_ , callback=lowerCamelCase_ , callback_steps=lowerCamelCase_ , **lowerCamelCase_ , )
# Get first result from Stable Diffusion Checkpoint v1.4
SCREAMING_SNAKE_CASE : Union[str, Any] = self.textaimg_sda_a(
prompt=lowerCamelCase_ , height=lowerCamelCase_ , width=lowerCamelCase_ , num_inference_steps=lowerCamelCase_ , guidance_scale=lowerCamelCase_ , negative_prompt=lowerCamelCase_ , num_images_per_prompt=lowerCamelCase_ , eta=lowerCamelCase_ , generator=lowerCamelCase_ , latents=lowerCamelCase_ , output_type=lowerCamelCase_ , return_dict=lowerCamelCase_ , callback=lowerCamelCase_ , callback_steps=lowerCamelCase_ , **lowerCamelCase_ , )
# Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
| 698 | 0 |
'''simple docstring'''
import warnings
from ...utils import logging
from .image_processing_deformable_detr import DeformableDetrImageProcessor
_lowercase : str = logging.get_logger(__name__)
class __magic_name__ ( _UpperCAmelCase):
def __init__( self : Optional[int] , *lowercase_ : Any , **lowercase_ : List[Any] ):
warnings.warn(
"""The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers."""
""" Please use DeformableDetrImageProcessor instead.""" , lowercase_ , )
super().__init__(*lowercase_ , **lowercase_ )
| 709 | '''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
if is_tf_available():
import tensorflow as tf
from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM
@require_tf
@require_sentencepiece
@require_tokenizers
class __magic_name__ ( unittest.TestCase):
@slow
def SCREAMING_SNAKE_CASE_ ( self : str ):
lowercase_ : Any = TFAutoModelForSeqaSeqLM.from_pretrained("""google/mt5-small""" )
lowercase_ : Dict = AutoTokenizer.from_pretrained("""google/mt5-small""" )
lowercase_ : Union[str, Any] = tokenizer("""Hello there""" , return_tensors="""tf""" ).input_ids
lowercase_ : List[str] = tokenizer("""Hi I am""" , return_tensors="""tf""" ).input_ids
lowercase_ : Optional[Any] = model(lowercase_ , labels=lowercase_ ).loss
lowercase_ : Optional[int] = -tf.math.reduce_mean(lowercase_ ).numpy()
lowercase_ : Optional[int] = -21.22_81_68
self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2E-4 )
| 30 | 0 |
'''simple docstring'''
import inspect
import unittest
from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
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 (
MODEL_MAPPING,
SegformerForImageClassification,
SegformerForSemanticSegmentation,
SegformerModel,
)
from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import SegformerImageProcessor
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(a_ , "hidden_sizes" ) )
self.parent.assertTrue(hasattr(a_ , "num_attention_heads" ) )
self.parent.assertTrue(hasattr(a_ , "num_encoder_blocks" ) )
class SCREAMING_SNAKE_CASE__ :
def __init__( self : List[Any] , a_ : Any , a_ : Tuple=13 , a_ : Optional[Any]=64 , a_ : str=3 , a_ : Any=4 , a_ : List[str]=[2, 2, 2, 2] , a_ : Optional[int]=[8, 4, 2, 1] , a_ : List[str]=[16, 32, 64, 128] , a_ : Union[str, Any]=[1, 4, 8, 16] , a_ : Dict=[1, 2, 4, 8] , a_ : Tuple=True , a_ : Optional[int]=True , a_ : int="gelu" , a_ : Optional[Any]=0.1 , a_ : Optional[int]=0.1 , a_ : int=0.02 , a_ : Optional[int]=3 , a_ : Any=None , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = image_size
__snake_case = num_channels
__snake_case = num_encoder_blocks
__snake_case = sr_ratios
__snake_case = depths
__snake_case = hidden_sizes
__snake_case = downsampling_rates
__snake_case = num_attention_heads
__snake_case = is_training
__snake_case = use_labels
__snake_case = hidden_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = scope
def A ( self : int ):
"""simple docstring"""
__snake_case = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
__snake_case = self.get_config()
return config, pixel_values, labels
def A ( self : Union[str, Any] ):
"""simple docstring"""
return SegformerConfig(
image_size=self.image_size , num_channels=self.num_channels , num_encoder_blocks=self.num_encoder_blocks , depths=self.depths , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , 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 A ( self : List[Any] , a_ : int , a_ : List[str] , a_ : Dict ):
"""simple docstring"""
__snake_case = SegformerModel(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ )
__snake_case = __snake_case = self.image_size // (self.downsampling_rates[-1] * 2)
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) )
def A ( self : int , a_ : List[Any] , a_ : Dict , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = SegformerForSemanticSegmentation(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) )
__snake_case = model(a_ , labels=a_ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) )
self.parent.assertGreater(result.loss , 0.0 )
def A ( self : Optional[int] , a_ : str , a_ : Dict , a_ : str ):
"""simple docstring"""
__snake_case = 1
__snake_case = SegformerForSemanticSegmentation(config=a_ )
model.to(a_ )
model.eval()
__snake_case = torch.randint(0 , 1 , (self.batch_size, self.image_size, self.image_size) ).to(a_ )
__snake_case = model(a_ , labels=a_ )
self.parent.assertGreater(result.loss , 0.0 )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
__snake_case , __snake_case , __snake_case = config_and_inputs
__snake_case = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(
SegformerModel,
SegformerForSemanticSegmentation,
SegformerForImageClassification,
)
if is_torch_available()
else ()
)
__SCREAMING_SNAKE_CASE = (
{
"""feature-extraction""": SegformerModel,
"""image-classification""": SegformerForImageClassification,
"""image-segmentation""": SegformerForSemanticSegmentation,
}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = True
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
def A ( self : Any ):
"""simple docstring"""
__snake_case = SegformerModelTester(self )
__snake_case = SegformerConfigTester(self , config_class=a_ )
def A ( self : Any ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a_ )
def A ( self : str ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_binary_image_segmentation(*a_ )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_segmentation(*a_ )
@unittest.skip("SegFormer does not use inputs_embeds" )
def A ( self : Tuple ):
"""simple docstring"""
pass
@unittest.skip("SegFormer does not have get_input_embeddings method and get_output_embeddings methods" )
def A ( self : Optional[Any] ):
"""simple docstring"""
pass
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case = model_class(a_ )
__snake_case = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__snake_case = [*signature.parameters.keys()]
__snake_case = ["pixel_values"]
self.assertListEqual(arg_names[:1] , a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = True
for model_class in self.all_model_classes:
__snake_case = True
__snake_case = False
__snake_case = True
__snake_case = model_class(a_ )
model.to(a_ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a_ , a_ ) )
__snake_case = outputs.attentions
__snake_case = sum(self.model_tester.depths )
self.assertEqual(len(a_ ) , a_ )
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
__snake_case = True
__snake_case = model_class(a_ )
model.to(a_ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a_ , a_ ) )
__snake_case = outputs.attentions
self.assertEqual(len(a_ ) , a_ )
# verify the first attentions (first block, first layer)
__snake_case = (self.model_tester.image_size // 4) ** 2
__snake_case = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , )
# verify the last attentions (last block, last layer)
__snake_case = (self.model_tester.image_size // 32) ** 2
__snake_case = (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
self.assertListEqual(
list(attentions[-1].shape[-3:] ) , [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len] , )
__snake_case = len(a_ )
# Check attention is always last and order is fine
__snake_case = True
__snake_case = True
__snake_case = model_class(a_ )
model.to(a_ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a_ , a_ ) )
self.assertEqual(out_len + 1 , len(a_ ) )
__snake_case = outputs.attentions
self.assertEqual(len(a_ ) , a_ )
# verify the first attentions (first block, first layer)
__snake_case = (self.model_tester.image_size // 4) ** 2
__snake_case = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
self.assertListEqual(
list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , )
def A ( self : int ):
"""simple docstring"""
def check_hidden_states_output(a_ : List[Any] , a_ : List[Any] , a_ : Tuple ):
__snake_case = model_class(a_ )
model.to(a_ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a_ , a_ ) )
__snake_case = outputs.hidden_states
__snake_case = self.model_tester.num_encoder_blocks
self.assertEqual(len(a_ ) , a_ )
# verify the first hidden states (first block)
self.assertListEqual(
list(hidden_states[0].shape[-3:] ) , [
self.model_tester.hidden_sizes[0],
self.model_tester.image_size // 4,
self.model_tester.image_size // 4,
] , )
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case = True
check_hidden_states_output(a_ , a_ , a_ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__snake_case = True
check_hidden_states_output(a_ , a_ , a_ )
def A ( self : Tuple ):
"""simple docstring"""
if not self.model_tester.is_training:
return
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = True
for model_class in self.all_model_classes:
if model_class in get_values(a_ ):
continue
__snake_case = model_class(a_ )
model.to(a_ )
model.train()
__snake_case = self._prepare_for_class(a_ , a_ , return_labels=a_ )
__snake_case = model(**a_ ).loss
loss.backward()
@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
def A ( self : int ):
"""simple docstring"""
pass
@slow
def A ( self : List[str] ):
"""simple docstring"""
for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__snake_case = SegformerModel.from_pretrained(a_ )
self.assertIsNotNone(a_ )
def __UpperCAmelCase ( ) -> List[Any]:
__snake_case = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@slow
def A ( self : Dict ):
"""simple docstring"""
__snake_case = SegformerImageProcessor(
image_scale=(512, 512) , keep_ratio=a_ , align=a_ , do_random_crop=a_ )
__snake_case = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512" ).to(
a_ )
__snake_case = prepare_img()
__snake_case = image_processor(images=a_ , return_tensors="pt" )
__snake_case = encoded_inputs.pixel_values.to(a_ )
with torch.no_grad():
__snake_case = model(a_ )
__snake_case = torch.Size((1, model.config.num_labels, 128, 128) )
self.assertEqual(outputs.logits.shape , a_ )
__snake_case = torch.tensor(
[
[[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]],
[[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
[[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
] ).to(a_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , a_ , atol=1e-4 ) )
@slow
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = SegformerImageProcessor(
image_scale=(512, 512) , keep_ratio=a_ , align=a_ , do_random_crop=a_ )
__snake_case = SegformerForSemanticSegmentation.from_pretrained(
"nvidia/segformer-b1-finetuned-cityscapes-1024-1024" ).to(a_ )
__snake_case = prepare_img()
__snake_case = image_processor(images=a_ , return_tensors="pt" )
__snake_case = encoded_inputs.pixel_values.to(a_ )
with torch.no_grad():
__snake_case = model(a_ )
__snake_case = torch.Size((1, model.config.num_labels, 128, 128) )
self.assertEqual(outputs.logits.shape , a_ )
__snake_case = torch.tensor(
[
[[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
[[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
[[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]],
] ).to(a_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , a_ , atol=1e-1 ) )
@slow
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = SegformerImageProcessor(
image_scale=(512, 512) , keep_ratio=a_ , align=a_ , do_random_crop=a_ )
__snake_case = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512" ).to(
a_ )
__snake_case = prepare_img()
__snake_case = image_processor(images=a_ , return_tensors="pt" )
__snake_case = encoded_inputs.pixel_values.to(a_ )
with torch.no_grad():
__snake_case = model(a_ )
__snake_case = outputs.logits.detach().cpu()
__snake_case = image_processor.post_process_semantic_segmentation(outputs=a_ , target_sizes=[(500, 300)] )
__snake_case = torch.Size((500, 300) )
self.assertEqual(segmentation[0].shape , a_ )
__snake_case = image_processor.post_process_semantic_segmentation(outputs=a_ )
__snake_case = torch.Size((128, 128) )
self.assertEqual(segmentation[0].shape , a_ )
| 69 |
'''simple docstring'''
import unittest
from transformers import GPTSwaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
a : List[Any] = get_tests_dir('''fixtures/test_sentencepiece_with_bytefallback.model''')
@require_sentencepiece
@require_tokenizers
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = GPTSwaTokenizer
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = True
__SCREAMING_SNAKE_CASE = False
def A ( self : int ):
"""simple docstring"""
super().setUp()
# We have a SentencePiece fixture for testing
__snake_case = GPTSwaTokenizer(a_ , eos_token="<unk>" , bos_token="<unk>" , pad_token="<unk>" )
tokenizer.save_pretrained(self.tmpdirname )
def A ( self : str , a_ : List[Any] ):
"""simple docstring"""
__snake_case = "This is a test"
__snake_case = "This is a test"
return input_text, output_text
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = "<s>"
__snake_case = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<unk>" )
self.assertEqual(vocab_keys[1] , "<s>" )
self.assertEqual(vocab_keys[-1] , "j" )
self.assertEqual(len(a_ ) , 2_000 )
def A ( self : Optional[int] ):
"""simple docstring"""
self.assertEqual(self.get_tokenizer().vocab_size , 2_000 )
def A ( self : Dict ):
"""simple docstring"""
__snake_case = GPTSwaTokenizer(a_ )
__snake_case = tokenizer.tokenize("This is a test" )
self.assertListEqual(a_ , ["▁This", "▁is", "▁a", "▁t", "est"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [465, 287, 265, 631, 842] )
__snake_case = tokenizer.tokenize("I was born in 92000, and this is falsé." )
# fmt: off
self.assertListEqual(
a_ , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] , )
# fmt: on
__snake_case = tokenizer.convert_tokens_to_ids(a_ )
self.assertListEqual(
a_ , [262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , )
__snake_case = tokenizer.convert_ids_to_tokens(a_ )
# fmt: off
self.assertListEqual(
a_ , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] )
# fmt: on
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = GPTSwaTokenizer(a_ )
__snake_case = ["This is a test", "I was born in 92000, and this is falsé."]
__snake_case = [
[465, 287, 265, 631, 842],
[262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260],
]
# Test that encode_fast returns the same as tokenize + convert_tokens_to_ids
for text, expected_ids in zip(a_ , a_ ):
self.assertListEqual(tokenizer.encode_fast(a_ ) , a_ )
# Test that decode_fast returns the input text
for text, token_ids in zip(a_ , a_ ):
self.assertEqual(tokenizer.decode_fast(a_ ) , a_ )
@slow
def A ( self : Any ):
"""simple docstring"""
__snake_case = [
"<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')",
"Hey there, how are you doing this fine day?",
"This is a text with a trailing spaces followed by a dot .",
"Häj sväjs lillebrör! =)",
"Det är inget fel på Mr. Cool",
]
# fmt: off
__snake_case = {"input_ids": [[63_423, 5, 6_811, 14_954, 282, 816, 3_821, 63_466, 63_425, 63_462, 18, 63_978, 678, 301, 1_320, 63_423, 63_455, 63_458, 18, 63_982, 4_246, 3_940, 1_901, 47_789, 5_547, 18_994], [19_630, 1_100, 63_446, 1_342, 633, 544, 4_488, 593, 5_102, 2_416, 63_495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_652, 428, 268, 1_936, 515, 268, 58_593, 22_413, 9_106, 546, 268, 33_213, 63_979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55_130, 63_450, 924, 63_449, 2_249, 4_062, 1_558, 318, 63_504, 21_498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2_827, 2_559, 332, 6_575, 63_443, 26_801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=a_ , model_name="AI-Sweden/gpt-sw3-126m" , sequences=a_ , )
| 69 | 1 |
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on
import numpy # noqa: F401 # Here to have a nice missing dependency error message early on
import requests # noqa: F401 # Here to have a nice missing dependency error message early on
import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on
import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on
from mauve import compute_mauve # From: mauve-text
import datasets
__SCREAMING_SNAKE_CASE : Union[str, Any] = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n'
__SCREAMING_SNAKE_CASE : List[str] = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n'
__SCREAMING_SNAKE_CASE : Optional[int] = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class lowercase_ ( datasets.Metric ):
def UpperCamelCase ( self ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , homepage="https://github.com/krishnap25/mauve" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"predictions": datasets.Value("string" , id="sequence" ),
"references": datasets.Value("string" , id="sequence" ),
} ) , codebase_urls=["https://github.com/krishnap25/mauve"] , reference_urls=[
"https://arxiv.org/abs/2102.01454",
"https://github.com/krishnap25/mauve",
] , )
def UpperCamelCase ( self , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_="auto" , lowercase_=-1 , lowercase_=0.9 , lowercase_=5 , lowercase_=500 , lowercase_="gpt2-large" , lowercase_=-1 , lowercase_=1_024 , lowercase_=25 , lowercase_=5 , lowercase_=True , lowercase_=25 , ):
_snake_case : Tuple = compute_mauve(
p_text=lowercase_ , q_text=lowercase_ , p_features=lowercase_ , q_features=lowercase_ , p_tokens=lowercase_ , q_tokens=lowercase_ , num_buckets=lowercase_ , pca_max_data=lowercase_ , kmeans_explained_var=lowercase_ , kmeans_num_redo=lowercase_ , kmeans_max_iter=lowercase_ , featurize_model_name=lowercase_ , device_id=lowercase_ , max_text_length=lowercase_ , divergence_curve_discretization_size=lowercase_ , mauve_scaling_factor=lowercase_ , verbose=lowercase_ , seed=lowercase_ , )
return out | 580 | from typing import Callable, Dict, Optional, Tuple
import torch
from torch import nn
from torch.distributions import (
AffineTransform,
Distribution,
Independent,
NegativeBinomial,
Normal,
StudentT,
TransformedDistribution,
)
class lowercase_ ( __snake_case ):
def __init__( self , lowercase_ , lowercase_=None , lowercase_=None , lowercase_=0 ):
_snake_case : Optional[Any] = 1.0 if scale is None else scale
_snake_case : Optional[Any] = 0.0 if loc is None else loc
super().__init__(lowercase_ , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=lowercase_ )] )
@property
def UpperCamelCase ( self ):
return self.base_dist.mean * self.scale + self.loc
@property
def UpperCamelCase ( self ):
return self.base_dist.variance * self.scale**2
@property
def UpperCamelCase ( self ):
return self.variance.sqrt()
class lowercase_ ( nn.Module ):
def __init__( self , lowercase_ , lowercase_ , lowercase_ , **lowercase_ ):
super().__init__(**lowercase_ )
_snake_case : List[Any] = args_dim
_snake_case : Any = nn.ModuleList([nn.Linear(lowercase_ , lowercase_ ) for dim in args_dim.values()] )
_snake_case : List[Any] = domain_map
def UpperCamelCase ( self , lowercase_ ):
_snake_case : int = [proj(lowercase_ ) for proj in self.proj]
return self.domain_map(*lowercase_ )
class lowercase_ ( nn.Module ):
def __init__( self , lowercase_ ):
super().__init__()
_snake_case : Optional[int] = function
def UpperCamelCase ( self , lowercase_ , *lowercase_ ):
return self.function(lowercase_ , *lowercase_ )
class lowercase_ :
_lowerCamelCase = 42
_lowerCamelCase = 42
_lowerCamelCase = 42
def __init__( self , lowercase_ = 1 ):
_snake_case : Any = dim
_snake_case : Optional[int] = {k: dim * self.args_dim[k] for k in self.args_dim}
def UpperCamelCase ( self , lowercase_ ):
if self.dim == 1:
return self.distribution_class(*lowercase_ )
else:
return Independent(self.distribution_class(*lowercase_ ) , 1 )
def UpperCamelCase ( self , lowercase_ , lowercase_ = None , lowercase_ = None , ):
_snake_case : Union[str, Any] = self._base_distribution(lowercase_ )
if loc is None and scale is None:
return distr
else:
return AffineTransformed(lowercase_ , loc=lowercase_ , scale=lowercase_ , event_dim=self.event_dim )
@property
def UpperCamelCase ( self ):
return () if self.dim == 1 else (self.dim,)
@property
def UpperCamelCase ( self ):
return len(self.event_shape )
@property
def UpperCamelCase ( self ):
return 0.0
def UpperCamelCase ( self , lowercase_ ):
return ParameterProjection(
in_features=lowercase_ , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , )
def UpperCamelCase ( self , *lowercase_ ):
raise NotImplementedError()
@staticmethod
def UpperCamelCase ( lowercase_ ):
return (x + torch.sqrt(torch.square(lowercase_ ) + 4.0 )) / 2.0
class lowercase_ ( __snake_case ):
_lowerCamelCase = {"df": 1, "loc": 1, "scale": 1}
_lowerCamelCase = StudentT
@classmethod
def UpperCamelCase ( cls , lowercase_ , lowercase_ , lowercase_ ):
_snake_case : int = cls.squareplus(lowercase_ ).clamp_min(torch.finfo(scale.dtype ).eps )
_snake_case : Optional[Any] = 2.0 + cls.squareplus(lowercase_ )
return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 )
class lowercase_ ( __snake_case ):
_lowerCamelCase = {"loc": 1, "scale": 1}
_lowerCamelCase = Normal
@classmethod
def UpperCamelCase ( cls , lowercase_ , lowercase_ ):
_snake_case : Optional[int] = cls.squareplus(lowercase_ ).clamp_min(torch.finfo(scale.dtype ).eps )
return loc.squeeze(-1 ), scale.squeeze(-1 )
class lowercase_ ( __snake_case ):
_lowerCamelCase = {"total_count": 1, "logits": 1}
_lowerCamelCase = NegativeBinomial
@classmethod
def UpperCamelCase ( cls , lowercase_ , lowercase_ ):
_snake_case : Optional[Any] = cls.squareplus(lowercase_ )
return total_count.squeeze(-1 ), logits.squeeze(-1 )
def UpperCamelCase ( self , lowercase_ ):
_snake_case ,_snake_case : int = distr_args
if self.dim == 1:
return self.distribution_class(total_count=lowercase_ , logits=lowercase_ )
else:
return Independent(self.distribution_class(total_count=lowercase_ , logits=lowercase_ ) , 1 )
def UpperCamelCase ( self , lowercase_ , lowercase_ = None , lowercase_ = None ):
_snake_case ,_snake_case : int = distr_args
if scale is not None:
# See scaling property of Gamma.
logits += scale.log()
return self._base_distribution((total_count, logits) ) | 580 | 1 |
def _SCREAMING_SNAKE_CASE ( lowercase : int , lowercase : int ):
'''simple docstring'''
return abs(lowercase ) if a == 0 else greatest_common_divisor(b % a , lowercase )
def _SCREAMING_SNAKE_CASE ( lowercase : int , lowercase : int ):
'''simple docstring'''
while y: # --> when y=0 then loop will terminate and return x as final GCD.
lowerCamelCase_ = y, x % y
return abs(lowercase )
def _SCREAMING_SNAKE_CASE ( ):
'''simple docstring'''
try:
lowerCamelCase_ = input('Enter two integers separated by comma (,): ' ).split(',' )
lowerCamelCase_ = int(nums[0] )
lowerCamelCase_ = int(nums[1] )
print(
f"""greatest_common_divisor({num_a}, {num_a}) = """
f"""{greatest_common_divisor(lowercase , lowercase )}""" )
print(f"""By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(lowercase , lowercase )}""" )
except (IndexError, UnboundLocalError, ValueError):
print('Wrong input' )
if __name__ == "__main__":
main()
| 70 |
"""simple docstring"""
import argparse
import math
import os
from copy import deepcopy
import torch
from audio_diffusion.models import DiffusionAttnUnetaD
from diffusion import sampling
from torch import nn
from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
_lowerCAmelCase : Tuple = {
"""gwf-440k""": {
"""url""": """https://model-server.zqevans2.workers.dev/gwf-440k.ckpt""",
"""sample_rate""": 48_000,
"""sample_size""": 65_536,
},
"""jmann-small-190k""": {
"""url""": """https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt""",
"""sample_rate""": 48_000,
"""sample_size""": 65_536,
},
"""jmann-large-580k""": {
"""url""": """https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt""",
"""sample_rate""": 48_000,
"""sample_size""": 131_072,
},
"""maestro-uncond-150k""": {
"""url""": """https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt""",
"""sample_rate""": 16_000,
"""sample_size""": 65_536,
},
"""unlocked-uncond-250k""": {
"""url""": """https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt""",
"""sample_rate""": 16_000,
"""sample_size""": 65_536,
},
"""honk-140k""": {
"""url""": """https://model-server.zqevans2.workers.dev/honk-140k.ckpt""",
"""sample_rate""": 16_000,
"""sample_size""": 65_536,
},
}
def SCREAMING_SNAKE_CASE__ ( snake_case : Optional[int] , snake_case : List[str] )-> Optional[int]:
'''simple docstring'''
return torch.atana(snake_case , snake_case ) / math.pi * 2
def SCREAMING_SNAKE_CASE__ ( snake_case : List[Any] )-> List[Any]:
'''simple docstring'''
UpperCAmelCase__ : Dict = torch.sin(t * math.pi / 2 ) ** 2
UpperCAmelCase__ : Optional[int] = (1 - sigma**2) ** 0.5
return alpha_sigma_to_t(snake_case , snake_case )
class lowerCAmelCase__ ( __magic_name__ ):
pass
class lowerCAmelCase__ ( nn.Module ):
def __init__( self : Any , snake_case__ : str ):
'''simple docstring'''
super().__init__()
UpperCAmelCase__ : Any = DiffusionAttnUnetaD(snake_case__ , n_attn_layers=4 )
UpperCAmelCase__ : Any = deepcopy(self.diffusion )
UpperCAmelCase__ : Optional[Any] = torch.quasirandom.SobolEngine(1 , scramble=snake_case__ )
def SCREAMING_SNAKE_CASE__ ( snake_case : Optional[Any] )-> str:
'''simple docstring'''
UpperCAmelCase__ : Any = MODELS_MAP[model_name]["url"]
os.system(f'wget {url} ./' )
return f'./{model_name}.ckpt'
_lowerCAmelCase : List[Any] = {
"""1""": """resnets.0""",
"""2""": """attentions.0""",
"""3""": """resnets.1""",
"""4""": """attentions.1""",
"""5""": """resnets.2""",
"""6""": """attentions.2""",
}
_lowerCAmelCase : Optional[Any] = {
"""8""": """resnets.0""",
"""9""": """attentions.0""",
"""10""": """resnets.1""",
"""11""": """attentions.1""",
"""12""": """resnets.2""",
"""13""": """attentions.2""",
}
_lowerCAmelCase : List[str] = {
"""1""": """resnets.0""",
"""2""": """attentions.0""",
"""3""": """resnets.1""",
"""4""": """attentions.1""",
"""5""": """resnets.2""",
"""6""": """attentions.2""",
"""8""": """resnets.3""",
"""9""": """attentions.3""",
"""10""": """resnets.4""",
"""11""": """attentions.4""",
"""12""": """resnets.5""",
"""13""": """attentions.5""",
}
_lowerCAmelCase : List[str] = {
"""0""": """resnets.0""",
"""1""": """resnets.1""",
"""2""": """resnets.2""",
"""4""": """resnets.0""",
"""5""": """resnets.1""",
"""6""": """resnets.2""",
}
_lowerCAmelCase : Dict = {
"""skip""": """conv_skip""",
"""main.0""": """conv_1""",
"""main.1""": """group_norm_1""",
"""main.3""": """conv_2""",
"""main.4""": """group_norm_2""",
}
_lowerCAmelCase : List[Any] = {
"""norm""": """group_norm""",
"""qkv_proj""": ["""query""", """key""", """value"""],
"""out_proj""": ["""proj_attn"""],
}
def SCREAMING_SNAKE_CASE__ ( snake_case : Tuple )-> Dict:
'''simple docstring'''
if name.startswith("skip" ):
return name.replace("skip" , RES_CONV_MAP["skip"] )
# name has to be of format main.{digit}
if not name.startswith("main." ):
raise ValueError(f'ResConvBlock error with {name}' )
return name.replace(name[:6] , RES_CONV_MAP[name[:6]] )
def SCREAMING_SNAKE_CASE__ ( snake_case : Union[str, Any] )-> int:
'''simple docstring'''
for key, value in ATTN_MAP.items():
if name.startswith(snake_case ) and not isinstance(snake_case , snake_case ):
return name.replace(snake_case , snake_case )
elif name.startswith(snake_case ):
return [name.replace(snake_case , snake_case ) for v in value]
raise ValueError(f'Attn error with {name}' )
def SCREAMING_SNAKE_CASE__ ( snake_case : List[Any] , snake_case : Optional[Any]=13 )-> str:
'''simple docstring'''
UpperCAmelCase__ : Any = input_string
if string.split("." )[0] == "timestep_embed":
return string.replace("timestep_embed" , "time_proj" )
UpperCAmelCase__ : Tuple = 0
if string.startswith("net.3." ):
depth += 1
UpperCAmelCase__ : Dict = string[6:]
elif string.startswith("net." ):
UpperCAmelCase__ : Tuple = string[4:]
while string.startswith("main.7." ):
depth += 1
UpperCAmelCase__ : Any = string[7:]
if string.startswith("main." ):
UpperCAmelCase__ : Union[str, Any] = string[5:]
# mid block
if string[:2].isdigit():
UpperCAmelCase__ : Optional[Any] = string[:2]
UpperCAmelCase__ : int = string[2:]
else:
UpperCAmelCase__ : Optional[int] = string[0]
UpperCAmelCase__ : Any = string[1:]
if depth == max_depth:
UpperCAmelCase__ : Any = MID_NUM_TO_LAYER[layer_num]
UpperCAmelCase__ : int = "mid_block"
elif depth > 0 and int(snake_case ) < 7:
UpperCAmelCase__ : Optional[Any] = DOWN_NUM_TO_LAYER[layer_num]
UpperCAmelCase__ : int = f'down_blocks.{depth}'
elif depth > 0 and int(snake_case ) > 7:
UpperCAmelCase__ : Optional[int] = UP_NUM_TO_LAYER[layer_num]
UpperCAmelCase__ : Tuple = f'up_blocks.{max_depth - depth - 1}'
elif depth == 0:
UpperCAmelCase__ : Tuple = DEPTH_0_TO_LAYER[layer_num]
UpperCAmelCase__ : Optional[Any] = f'up_blocks.{max_depth - 1}' if int(snake_case ) > 3 else "down_blocks.0"
if not string_left.startswith("." ):
raise ValueError(f'Naming error with {input_string} and string_left: {string_left}.' )
UpperCAmelCase__ : List[Any] = string_left[1:]
if "resnets" in new_layer:
UpperCAmelCase__ : Optional[int] = convert_resconv_naming(snake_case )
elif "attentions" in new_layer:
UpperCAmelCase__ : Optional[int] = convert_attn_naming(snake_case )
UpperCAmelCase__ : Any = new_string_left
if not isinstance(snake_case , snake_case ):
UpperCAmelCase__ : Tuple = prefix + "." + new_layer + "." + string_left
else:
UpperCAmelCase__ : str = [prefix + "." + new_layer + "." + s for s in string_left]
return new_string
def SCREAMING_SNAKE_CASE__ ( snake_case : List[str] )-> Tuple:
'''simple docstring'''
UpperCAmelCase__ : str = {}
for k, v in state_dict.items():
if k.endswith("kernel" ):
# up- and downsample layers, don't have trainable weights
continue
UpperCAmelCase__ : Optional[int] = rename(snake_case )
# check if we need to transform from Conv => Linear for attention
if isinstance(snake_case , snake_case ):
UpperCAmelCase__ : Optional[Any] = transform_conv_attns(snake_case , snake_case , snake_case )
else:
UpperCAmelCase__ : List[Any] = v
return new_state_dict
def SCREAMING_SNAKE_CASE__ ( snake_case : Union[str, Any] , snake_case : List[Any] , snake_case : int )-> Union[str, Any]:
'''simple docstring'''
if len(snake_case ) == 1:
if len(v.shape ) == 3:
# weight
UpperCAmelCase__ : Optional[int] = v[:, :, 0]
else:
# bias
UpperCAmelCase__ : Any = v
else:
# qkv matrices
UpperCAmelCase__ : Any = v.shape[0]
UpperCAmelCase__ : Optional[Any] = trippled_shape // 3
for i in range(3 ):
if len(v.shape ) == 3:
UpperCAmelCase__ : List[Any] = v[i * single_shape : (i + 1) * single_shape, :, 0]
else:
UpperCAmelCase__ : Any = v[i * single_shape : (i + 1) * single_shape]
return new_state_dict
def SCREAMING_SNAKE_CASE__ ( snake_case : Union[str, Any] )-> Tuple:
'''simple docstring'''
UpperCAmelCase__ : Tuple = torch.device("cuda" if torch.cuda.is_available() else "cpu" )
UpperCAmelCase__ : List[str] = args.model_path.split("/" )[-1].split("." )[0]
if not os.path.isfile(args.model_path ):
assert (
model_name == args.model_path
), f'Make sure to provide one of the official model names {MODELS_MAP.keys()}'
UpperCAmelCase__ : Optional[int] = download(snake_case )
UpperCAmelCase__ : List[str] = MODELS_MAP[model_name]["sample_rate"]
UpperCAmelCase__ : Dict = MODELS_MAP[model_name]["sample_size"]
UpperCAmelCase__ : Optional[int] = Object()
UpperCAmelCase__ : int = sample_size
UpperCAmelCase__ : List[Any] = sample_rate
UpperCAmelCase__ : int = 0
UpperCAmelCase__ : int = UNetaDModel(sample_size=snake_case , sample_rate=snake_case )
UpperCAmelCase__ : int = diffusers_model.state_dict()
UpperCAmelCase__ : Optional[Any] = DiffusionUncond(snake_case )
orig_model.load_state_dict(torch.load(args.model_path , map_location=snake_case )["state_dict"] )
UpperCAmelCase__ : List[str] = orig_model.diffusion_ema.eval()
UpperCAmelCase__ : Optional[int] = orig_model.state_dict()
UpperCAmelCase__ : Any = rename_orig_weights(snake_case )
UpperCAmelCase__ : List[Any] = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() )
UpperCAmelCase__ : Optional[int] = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() )
assert len(snake_case ) == 0, f'Problem with {renamed_minus_diffusers}'
assert all(k.endswith("kernel" ) for k in list(snake_case ) ), f'Problem with {diffusers_minus_renamed}'
for key, value in renamed_state_dict.items():
assert (
diffusers_state_dict[key].squeeze().shape == value.squeeze().shape
), f'Shape for {key} doesn\'t match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}'
if key == "time_proj.weight":
UpperCAmelCase__ : Union[str, Any] = value.squeeze()
UpperCAmelCase__ : List[str] = value
diffusers_model.load_state_dict(snake_case )
UpperCAmelCase__ : Any = 100
UpperCAmelCase__ : str = 33
UpperCAmelCase__ : Optional[int] = IPNDMScheduler(num_train_timesteps=snake_case )
UpperCAmelCase__ : Any = torch.manual_seed(snake_case )
UpperCAmelCase__ : List[str] = torch.randn([1, 2, config.sample_size] , generator=snake_case ).to(snake_case )
UpperCAmelCase__ : Dict = torch.linspace(1 , 0 , steps + 1 , device=snake_case )[:-1]
UpperCAmelCase__ : List[str] = get_crash_schedule(snake_case )
UpperCAmelCase__ : List[str] = DanceDiffusionPipeline(unet=snake_case , scheduler=snake_case )
UpperCAmelCase__ : Optional[Any] = torch.manual_seed(33 )
UpperCAmelCase__ : int = pipe(num_inference_steps=snake_case , generator=snake_case ).audios
UpperCAmelCase__ : Optional[Any] = sampling.iplms_sample(snake_case , snake_case , snake_case , {} )
UpperCAmelCase__ : Tuple = generated.clamp(-1 , 1 )
UpperCAmelCase__ : Optional[int] = (generated - audio).abs().sum()
UpperCAmelCase__ : List[Any] = (generated - audio).abs().max()
if args.save:
pipe.save_pretrained(args.checkpoint_path )
print("Diff sum" , snake_case )
print("Diff max" , snake_case )
assert diff_max < 1E-3, f'Diff max: {diff_max} is too much :-/'
print(f'Conversion for {model_name} successful!' )
if __name__ == "__main__":
_lowerCAmelCase : Dict = argparse.ArgumentParser()
parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""")
parser.add_argument(
"""--save""", default=True, type=bool, required=False, help="""Whether to save the converted model or not."""
)
parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""")
_lowerCAmelCase : Tuple = parser.parse_args()
main(args)
| 438 | 0 |
import random
def _lowerCamelCase ( snake_case ):
_lowerCAmelCase = num - 1
_lowerCAmelCase = 0
while s % 2 == 0:
_lowerCAmelCase = s // 2
t += 1
for _ in range(5 ):
_lowerCAmelCase = random.randrange(2 , num - 1 )
_lowerCAmelCase = pow(snake_case , snake_case , snake_case )
if v != 1:
_lowerCAmelCase = 0
while v != (num - 1):
if i == t - 1:
return False
else:
_lowerCAmelCase = i + 1
_lowerCAmelCase = (v**2) % num
return True
def _lowerCamelCase ( snake_case ):
if num < 2:
return False
_lowerCAmelCase = [
2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
]
if num in low_primes:
return True
for prime in low_primes:
if (num % prime) == 0:
return False
return rabin_miller(snake_case )
def _lowerCamelCase ( snake_case = 1_024 ):
while True:
_lowerCAmelCase = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) )
if is_prime_low_num(snake_case ):
return num
if __name__ == "__main__":
_lowercase: Optional[int] = generate_large_prime()
print(('''Prime number:''', num))
print(('''is_prime_low_num:''', is_prime_low_num(num)))
| 709 | from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowercase: List[str] = logging.get_logger(__name__)
_lowercase: Optional[Any] = {
'''tiiuae/falcon-40b''': '''https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json''',
'''tiiuae/falcon-7b''': '''https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json''',
}
class lowerCamelCase__ ( UpperCAmelCase ):
UpperCamelCase__ ="falcon"
UpperCamelCase__ =["past_key_values"]
def __init__( self : Optional[Any] , lowercase__ : List[Any]=6_50_24 , lowercase__ : Optional[Any]=45_44 , lowercase__ : int=32 , lowercase__ : List[Any]=71 , lowercase__ : Any=1e-5 , lowercase__ : Dict=0.0_2 , lowercase__ : Union[str, Any]=True , lowercase__ : Optional[Any]=0.0 , lowercase__ : int=0.0 , lowercase__ : Optional[Any]=None , lowercase__ : List[Any]=False , lowercase__ : Tuple=False , lowercase__ : int=True , lowercase__ : List[Any]=True , lowercase__ : Optional[Any]=False , lowercase__ : Optional[Any]=11 , lowercase__ : Optional[Any]=11 , **lowercase__ : Union[str, Any] , ):
_lowerCAmelCase = vocab_size
# Backward compatibility with n_embed kwarg
_lowerCAmelCase = kwargs.pop('n_embed' , lowercase__ )
_lowerCAmelCase = hidden_size if n_embed is None else n_embed
_lowerCAmelCase = num_hidden_layers
_lowerCAmelCase = num_attention_heads
_lowerCAmelCase = layer_norm_epsilon
_lowerCAmelCase = initializer_range
_lowerCAmelCase = use_cache
_lowerCAmelCase = hidden_dropout
_lowerCAmelCase = attention_dropout
_lowerCAmelCase = bos_token_id
_lowerCAmelCase = eos_token_id
_lowerCAmelCase = num_attention_heads if num_kv_heads is None else num_kv_heads
_lowerCAmelCase = alibi
_lowerCAmelCase = new_decoder_architecture
_lowerCAmelCase = multi_query # Ignored when new_decoder_architecture is True
_lowerCAmelCase = parallel_attn
_lowerCAmelCase = bias
super().__init__(bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ )
@property
def SCREAMING_SNAKE_CASE__ ( self : Tuple ):
return self.hidden_size // self.num_attention_heads
@property
def SCREAMING_SNAKE_CASE__ ( self : List[Any] ):
return not self.alibi
| 225 | 0 |
import unittest
from parameterized import parameterized
from transformers import LlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer
class _UpperCamelCase :
"""simple docstring"""
def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=13 , lowerCAmelCase__=7 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=False , lowerCAmelCase__=True , lowerCAmelCase__=99 , lowerCAmelCase__=32 , lowerCAmelCase__=5 , lowerCAmelCase__=4 , lowerCAmelCase__=37 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_12 , lowerCAmelCase__=16 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=3 , lowerCAmelCase__=4 , lowerCAmelCase__=None , ) -> List[str]:
'''simple docstring'''
__lowercase = parent
__lowercase = batch_size
__lowercase = seq_length
__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 = num_labels
__lowercase = num_choices
__lowercase = scope
def _SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
'''simple docstring'''
__lowercase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__lowercase = None
if self.use_input_mask:
__lowercase = random_attention_mask([self.batch_size, self.seq_length] )
__lowercase = None
if self.use_token_type_ids:
__lowercase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
__lowercase = None
__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.seq_length] , self.num_labels )
__lowercase = ids_tensor([self.batch_size] , self.num_choices )
__lowercase = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def _SCREAMING_SNAKE_CASE ( self ) -> Dict:
'''simple docstring'''
return LlamaConfig(
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=_a , initializer_range=self.initializer_range , )
def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> str:
'''simple docstring'''
__lowercase = LlamaModel(config=_a )
model.to(_a )
model.eval()
__lowercase = model(_a , attention_mask=_a )
__lowercase = model(_a )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> List[str]:
'''simple docstring'''
__lowercase = True
__lowercase = LlamaModel(_a )
model.to(_a )
model.eval()
__lowercase = model(
_a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , )
__lowercase = model(
_a , attention_mask=_a , encoder_hidden_states=_a , )
__lowercase = model(_a , attention_mask=_a )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> int:
'''simple docstring'''
__lowercase = LlamaForCausalLM(config=_a )
model.to(_a )
model.eval()
__lowercase = model(_a , attention_mask=_a , labels=_a )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> Optional[int]:
'''simple docstring'''
__lowercase = True
__lowercase = True
__lowercase = LlamaForCausalLM(config=_a )
model.to(_a )
model.eval()
# first forward pass
__lowercase = model(
_a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , use_cache=_a , )
__lowercase = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
__lowercase = ids_tensor((self.batch_size, 3) , config.vocab_size )
__lowercase = ids_tensor((self.batch_size, 3) , vocab_size=2 )
# append to next input_ids and
__lowercase = torch.cat([input_ids, next_tokens] , dim=-1 )
__lowercase = torch.cat([input_mask, next_mask] , dim=-1 )
__lowercase = model(
_a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , output_hidden_states=_a , )["""hidden_states"""][0]
__lowercase = model(
_a , attention_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , past_key_values=_a , output_hidden_states=_a , )["""hidden_states"""][0]
# select random slice
__lowercase = ids_tensor((1,) , output_from_past.shape[-1] ).item()
__lowercase = output_from_no_past[:, -3:, random_slice_idx].detach()
__lowercase = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(_a , _a , atol=1E-3 ) )
def _SCREAMING_SNAKE_CASE ( self ) -> Tuple:
'''simple docstring'''
__lowercase = self.prepare_config_and_inputs()
(
__lowercase
) = config_and_inputs
__lowercase = {"""input_ids""": input_ids, """attention_mask""": input_mask}
return config, inputs_dict
@require_torch
class _UpperCamelCase ( __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,unittest.TestCase ):
"""simple docstring"""
__a : Optional[int] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
__a : List[str] = (LlamaForCausalLM,) if is_torch_available() else ()
__a : Any = (
{
'''feature-extraction''': LlamaModel,
'''text-classification''': LlamaForSequenceClassification,
'''text-generation''': LlamaForCausalLM,
'''zero-shot''': LlamaForSequenceClassification,
}
if is_torch_available()
else {}
)
__a : Dict = False
__a : List[Any] = False
def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
'''simple docstring'''
__lowercase = LlamaModelTester(self )
__lowercase = ConfigTester(self , config_class=_a , hidden_size=37 )
def _SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
'''simple docstring'''
self.config_tester.run_common_tests()
def _SCREAMING_SNAKE_CASE ( self ) -> List[str]:
'''simple docstring'''
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_a )
def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
'''simple docstring'''
__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(*_a )
def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
'''simple docstring'''
__lowercase = self.model_tester.prepare_config_and_inputs_for_common()
__lowercase = 3
__lowercase = input_dict["""input_ids"""]
__lowercase = input_ids.ne(1 ).to(_a )
__lowercase = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size )
__lowercase = LlamaForSequenceClassification(_a )
model.to(_a )
model.eval()
__lowercase = model(_a , attention_mask=_a , labels=_a )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def _SCREAMING_SNAKE_CASE ( self ) -> Any:
'''simple docstring'''
__lowercase = self.model_tester.prepare_config_and_inputs_for_common()
__lowercase = 3
__lowercase = """single_label_classification"""
__lowercase = input_dict["""input_ids"""]
__lowercase = input_ids.ne(1 ).to(_a )
__lowercase = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size )
__lowercase = LlamaForSequenceClassification(_a )
model.to(_a )
model.eval()
__lowercase = model(_a , attention_mask=_a , labels=_a )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def _SCREAMING_SNAKE_CASE ( self ) -> Optional[int]:
'''simple docstring'''
__lowercase = self.model_tester.prepare_config_and_inputs_for_common()
__lowercase = 3
__lowercase = """multi_label_classification"""
__lowercase = input_dict["""input_ids"""]
__lowercase = input_ids.ne(1 ).to(_a )
__lowercase = ids_tensor(
[self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float )
__lowercase = LlamaForSequenceClassification(_a )
model.to(_a )
model.eval()
__lowercase = model(_a , attention_mask=_a , labels=_a )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
@unittest.skip('''LLaMA buffers include complex numbers, which breaks this test''' )
def _SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
'''simple docstring'''
pass
@parameterized.expand([('''linear''',), ('''dynamic''',)] )
def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ ) -> Union[str, Any]:
'''simple docstring'''
__lowercase = self.model_tester.prepare_config_and_inputs_for_common()
__lowercase = ids_tensor([1, 10] , config.vocab_size )
__lowercase = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size )
set_seed(42 ) # Fixed seed at init time so the two models get the same random weights
__lowercase = LlamaModel(_a )
original_model.to(_a )
original_model.eval()
__lowercase = original_model(_a ).last_hidden_state
__lowercase = original_model(_a ).last_hidden_state
set_seed(42 ) # Fixed seed at init time so the two models get the same random weights
__lowercase = {"""type""": scaling_type, """factor""": 10.0}
__lowercase = LlamaModel(_a )
scaled_model.to(_a )
scaled_model.eval()
__lowercase = scaled_model(_a ).last_hidden_state
__lowercase = scaled_model(_a ).last_hidden_state
# Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
# maximum sequence length, so the outputs for the short input should match.
if scaling_type == "dynamic":
self.assertTrue(torch.allclose(_a , _a , atol=1E-5 ) )
else:
self.assertFalse(torch.allclose(_a , _a , atol=1E-5 ) )
# The output should be different for long inputs
self.assertFalse(torch.allclose(_a , _a , atol=1E-5 ) )
@require_torch
class _UpperCamelCase ( unittest.TestCase ):
"""simple docstring"""
@unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' )
@slow
def _SCREAMING_SNAKE_CASE ( self ) -> Optional[int]:
'''simple docstring'''
__lowercase = [1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
__lowercase = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-7b-hf''' , device_map='''auto''' )
__lowercase = model(torch.tensor([input_ids] ) )
# Expected mean on dim = -1
__lowercase = torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]] )
torch.testing.assert_close(out.mean(-1 ) , _a , atol=1E-2 , rtol=1E-2 )
# slicing logits[0, 0, 0:30]
# fmt: off
__lowercase = torch.tensor([-12.8281, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.8281, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,] )
# fmt: on
torch.testing.assert_close(out[0, 0, :30] , _a , atol=1E-5 , rtol=1E-5 )
@unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' )
@slow
def _SCREAMING_SNAKE_CASE ( self ) -> Dict:
'''simple docstring'''
__lowercase = [1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
__lowercase = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-hf''' , device_map='''auto''' )
__lowercase = model(torch.tensor(_a ) )
# Expected mean on dim = -1
__lowercase = torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]] )
torch.testing.assert_close(out.mean(-1 ) , _a , atol=1E-2 , rtol=1E-2 )
# slicing logits[0, 0, 0:30]
# fmt: off
__lowercase = torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273] )
# fmt: on
torch.testing.assert_close(out[0, 0, :30] , _a , atol=1E-5 , rtol=1E-5 )
@unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' )
@slow
def _SCREAMING_SNAKE_CASE ( self ) -> Dict:
'''simple docstring'''
__lowercase = [1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
__lowercase = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''' , device_map='''auto''' )
__lowercase = model(torch.tensor(_a ) )
# Expected mean on dim = -1
__lowercase = torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]] )
torch.testing.assert_close(out.mean(-1 ) , _a , atol=1E-2 , rtol=1E-2 )
# slicing logits[0, 0, 0:30]
# fmt: off
__lowercase = torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513] )
# fmt: on
torch.testing.assert_close(out.mean(-1 ) , _a , atol=1E-2 , rtol=1E-2 )
@unittest.skip(
'''Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test''' )
@slow
def _SCREAMING_SNAKE_CASE ( self ) -> str:
'''simple docstring'''
__lowercase = [1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
__lowercase = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-70b-hf''' , device_map='''auto''' )
__lowercase = model(torch.tensor(_a ) )
__lowercase = torch.tensor(
[[-4.2327, -3.3360, -4.6665, -4.7631, -1.8180, -3.4170, -1.4211, -3.1810]] , dtype=torch.floataa )
torch.testing.assert_close(out.mean(-1 ) , _a , atol=1E-2 , rtol=1E-2 )
# fmt: off
__lowercase = torch.tensor([-9.4922, -3.9551, 1.7998, -5.6758, -5.1055, -5.8984, -4.8320, -6.8086, -6.5391, -5.6172, -5.5820, -5.5352, 1.7881, 3.6289, -6.5117, -3.4785, -9.5000, -6.0352, -6.8125, -6.0195, -6.6836, -5.4727, -6.2812, -6.0391, -7.3398, -7.4297, -7.4844, -6.5820, -5.8789, -5.5312] )
# fmt: on
torch.testing.assert_close(out[0, 0, :30] , _a , atol=1E-5 , rtol=1E-5 )
@unittest.skip('''Model is curently gated''' )
@slow
def _SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
'''simple docstring'''
__lowercase = """Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi"""
__lowercase = """Simply put, the theory of relativity states that """
__lowercase = LlamaTokenizer.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''' )
__lowercase = tokenizer.encode(_a , return_tensors='''pt''' )
__lowercase = LlamaForCausalLM.from_pretrained(
'''meta-llama/Llama-2-13b-chat-hf''' , device_map='''sequential''' , use_safetensors=_a )
# greedy generation outputs
__lowercase = model.generate(_a , max_new_tokens=64 , top_p=_a , temperature=1 , do_sample=_a )
__lowercase = tokenizer.decode(generated_ids[0] , skip_special_tokens=_a )
self.assertEqual(_a , _a ) | 534 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
__magic_name__ = {
'configuration_altclip': [
'ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP',
'AltCLIPConfig',
'AltCLIPTextConfig',
'AltCLIPVisionConfig',
],
'processing_altclip': ['AltCLIPProcessor'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ = [
'ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST',
'AltCLIPPreTrainedModel',
'AltCLIPModel',
'AltCLIPTextModel',
'AltCLIPVisionModel',
]
if TYPE_CHECKING:
from .configuration_altclip import (
ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
AltCLIPConfig,
AltCLIPTextConfig,
AltCLIPVisionConfig,
)
from .processing_altclip import AltCLIPProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_altclip import (
ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
AltCLIPModel,
AltCLIPPreTrainedModel,
AltCLIPTextModel,
AltCLIPVisionModel,
)
else:
import sys
__magic_name__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 665 | 0 |
import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union
import pandas as pd
import pyarrow as pa
import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal
lowerCamelCase = datasets.utils.logging.get_logger(__name__)
lowerCamelCase = ['names', 'prefix']
lowerCamelCase = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols']
lowerCamelCase = ['encoding_errors', 'on_bad_lines']
lowerCamelCase = ['date_format']
@dataclass
class snake_case__ ( datasets.BuilderConfig ):
_lowerCAmelCase =','
_lowerCAmelCase =None
_lowerCAmelCase ='infer'
_lowerCAmelCase =None
_lowerCAmelCase =None
_lowerCAmelCase =None
_lowerCAmelCase =None
_lowerCAmelCase =None
_lowerCAmelCase =True
_lowerCAmelCase =None
_lowerCAmelCase =None
_lowerCAmelCase =None
_lowerCAmelCase =None
_lowerCAmelCase =False
_lowerCAmelCase =None
_lowerCAmelCase =None
_lowerCAmelCase =None
_lowerCAmelCase =True
_lowerCAmelCase =True
_lowerCAmelCase =False
_lowerCAmelCase =True
_lowerCAmelCase =None
_lowerCAmelCase ='.'
_lowerCAmelCase =None
_lowerCAmelCase ='"'
_lowerCAmelCase =0
_lowerCAmelCase =None
_lowerCAmelCase =None
_lowerCAmelCase =None
_lowerCAmelCase =None
_lowerCAmelCase =True
_lowerCAmelCase =True
_lowerCAmelCase =0
_lowerCAmelCase =True
_lowerCAmelCase =False
_lowerCAmelCase =None
_lowerCAmelCase =10000
_lowerCAmelCase =None
_lowerCAmelCase ='strict'
_lowerCAmelCase ='error'
_lowerCAmelCase =None
def UpperCAmelCase__ ( self : Tuple ):
if self.delimiter is not None:
snake_case__ : List[Any] = self.delimiter
if self.column_names is not None:
snake_case__ : str = self.column_names
@property
def UpperCAmelCase__ ( self : Union[str, Any] ):
snake_case__ : Union[str, Any] = {
'sep': self.sep,
'header': self.header,
'names': self.names,
'index_col': self.index_col,
'usecols': self.usecols,
'prefix': self.prefix,
'mangle_dupe_cols': self.mangle_dupe_cols,
'engine': self.engine,
'converters': self.converters,
'true_values': self.true_values,
'false_values': self.false_values,
'skipinitialspace': self.skipinitialspace,
'skiprows': self.skiprows,
'nrows': self.nrows,
'na_values': self.na_values,
'keep_default_na': self.keep_default_na,
'na_filter': self.na_filter,
'verbose': self.verbose,
'skip_blank_lines': self.skip_blank_lines,
'thousands': self.thousands,
'decimal': self.decimal,
'lineterminator': self.lineterminator,
'quotechar': self.quotechar,
'quoting': self.quoting,
'escapechar': self.escapechar,
'comment': self.comment,
'encoding': self.encoding,
'dialect': self.dialect,
'error_bad_lines': self.error_bad_lines,
'warn_bad_lines': self.warn_bad_lines,
'skipfooter': self.skipfooter,
'doublequote': self.doublequote,
'memory_map': self.memory_map,
'float_precision': self.float_precision,
'chunksize': self.chunksize,
'encoding_errors': self.encoding_errors,
'on_bad_lines': self.on_bad_lines,
'date_format': self.date_format,
}
# some kwargs must not be passed if they don't have a default value
# some others are deprecated and we can also not pass them if they are the default value
for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , _lowerCamelCase ):
del pd_read_csv_kwargs[pd_read_csv_parameter]
# Remove 2.0 new arguments
if not (datasets.config.PANDAS_VERSION.major >= 2):
for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
del pd_read_csv_kwargs[pd_read_csv_parameter]
# Remove 1.3 new arguments
if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
del pd_read_csv_kwargs[pd_read_csv_parameter]
return pd_read_csv_kwargs
class snake_case__ ( datasets.ArrowBasedBuilder ):
_lowerCAmelCase =CsvConfig
def UpperCAmelCase__ ( self : Optional[int] ):
return datasets.DatasetInfo(features=self.config.features )
def UpperCAmelCase__ ( self : Any , _lowerCamelCase : List[Any] ):
if not self.config.data_files:
raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}''' )
snake_case__ : Optional[Any] = dl_manager.download_and_extract(self.config.data_files )
if isinstance(_lowerCamelCase , (str, list, tuple) ):
snake_case__ : Optional[int] = data_files
if isinstance(_lowerCamelCase , _lowerCamelCase ):
snake_case__ : Tuple = [files]
snake_case__ : str = [dl_manager.iter_files(_lowerCamelCase ) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files} )]
snake_case__ : str = []
for split_name, files in data_files.items():
if isinstance(_lowerCamelCase , _lowerCamelCase ):
snake_case__ : Optional[int] = [files]
snake_case__ : Any = [dl_manager.iter_files(_lowerCamelCase ) for file in files]
splits.append(datasets.SplitGenerator(name=_lowerCamelCase , gen_kwargs={'files': files} ) )
return splits
def UpperCAmelCase__ ( self : Optional[int] , _lowerCamelCase : pa.Table ):
if self.config.features is not None:
snake_case__ : Union[str, Any] = self.config.features.arrow_schema
if all(not require_storage_cast(_lowerCamelCase ) for feature in self.config.features.values() ):
# cheaper cast
snake_case__ : Dict = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=_lowerCamelCase )
else:
# more expensive cast; allows str <-> int/float or str to Audio for example
snake_case__ : str = table_cast(_lowerCamelCase , _lowerCamelCase )
return pa_table
def UpperCAmelCase__ ( self : Optional[int] , _lowerCamelCase : str ):
snake_case__ : List[Any] = self.config.features.arrow_schema if self.config.features else None
# dtype allows reading an int column as str
snake_case__ : Optional[Any] = (
{
name: dtype.to_pandas_dtype() if not require_storage_cast(_lowerCamelCase ) else object
for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() )
}
if schema is not None
else None
)
for file_idx, file in enumerate(itertools.chain.from_iterable(_lowerCamelCase ) ):
snake_case__ : Union[str, Any] = pd.read_csv(_lowerCamelCase , iterator=_lowerCamelCase , dtype=_lowerCamelCase , **self.config.pd_read_csv_kwargs )
try:
for batch_idx, df in enumerate(_lowerCamelCase ):
snake_case__ : List[Any] = pa.Table.from_pandas(_lowerCamelCase )
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield (file_idx, batch_idx), self._cast_table(_lowerCamelCase )
except ValueError as e:
logger.error(F'''Failed to read file \'{file}\' with error {type(_lowerCamelCase )}: {e}''' )
raise
| 716 |
from datetime import datetime
import requests
from bsa import BeautifulSoup
if __name__ == "__main__":
lowerCamelCase : str = input('Enter image url: ').strip()
print(F"""Downloading image from {url} ...""")
lowerCamelCase : Optional[Any] = BeautifulSoup(requests.get(url).content, 'html.parser')
# The image URL is in the content field of the first meta tag with property og:image
lowerCamelCase : Dict = soup.find('meta', {'property': 'og:image'})['content']
lowerCamelCase : str = requests.get(image_url).content
lowerCamelCase : Union[str, Any] = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg"""
with open(file_name, 'wb') as fp:
fp.write(image_data)
print(F"""Done. Image saved to disk as {file_name}.""")
| 303 | 0 |
"""simple docstring"""
class _lowerCAmelCase :
def __init__( self , a_ = "" , a_ = False ) -> None:
# Mapping from the first character of the prefix of the node
_UpperCAmelCase = {}
# A node will be a leaf if the tree contains its word
_UpperCAmelCase = is_leaf
_UpperCAmelCase = prefix
def _a ( self , a_ ) -> tuple[str, str, str]:
_UpperCAmelCase = 0
for q, w in zip(self.prefix , a_ ):
if q != w:
break
x += 1
return self.prefix[:x], self.prefix[x:], word[x:]
def _a ( self , a_ ) -> None:
for word in words:
self.insert(a_ )
def _a ( self , a_ ) -> None:
# Case 1: If the word is the prefix of the node
# Solution: We set the current node as leaf
if self.prefix == word:
_UpperCAmelCase = True
# Case 2: The node has no edges that have a prefix to the word
# Solution: We create an edge from the current node to a new one
# containing the word
elif word[0] not in self.nodes:
_UpperCAmelCase = RadixNode(prefix=a_ , is_leaf=a_ )
else:
_UpperCAmelCase = self.nodes[word[0]]
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = incoming_node.match(
a_ )
# Case 3: The node prefix is equal to the matching
# Solution: We insert remaining word on the next node
if remaining_prefix == "":
self.nodes[matching_string[0]].insert(a_ )
# Case 4: The word is greater equal to the matching
# Solution: Create a node in between both nodes, change
# prefixes and add the new node for the remaining word
else:
_UpperCAmelCase = remaining_prefix
_UpperCAmelCase = self.nodes[matching_string[0]]
_UpperCAmelCase = RadixNode(a_ , a_ )
_UpperCAmelCase = aux_node
if remaining_word == "":
_UpperCAmelCase = True
else:
self.nodes[matching_string[0]].insert(a_ )
def _a ( self , a_ ) -> bool:
_UpperCAmelCase = self.nodes.get(word[0] , a_ )
if not incoming_node:
return False
else:
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = incoming_node.match(
a_ )
# If there is remaining prefix, the word can't be on the tree
if remaining_prefix != "":
return False
# This applies when the word and the prefix are equal
elif remaining_word == "":
return incoming_node.is_leaf
# We have word remaining so we check the next node
else:
return incoming_node.find(a_ )
def _a ( self , a_ ) -> bool:
_UpperCAmelCase = self.nodes.get(word[0] , a_ )
if not incoming_node:
return False
else:
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = incoming_node.match(
a_ )
# If there is remaining prefix, the word can't be on the tree
if remaining_prefix != "":
return False
# We have word remaining so we check the next node
elif remaining_word != "":
return incoming_node.delete(a_ )
else:
# If it is not a leaf, we don't have to delete
if not incoming_node.is_leaf:
return False
else:
# We delete the nodes if no edges go from it
if len(incoming_node.nodes ) == 0:
del self.nodes[word[0]]
# We merge the current node with its only child
if len(self.nodes ) == 1 and not self.is_leaf:
_UpperCAmelCase = list(self.nodes.values() )[0]
_UpperCAmelCase = merging_node.is_leaf
self.prefix += merging_node.prefix
_UpperCAmelCase = merging_node.nodes
# If there is more than 1 edge, we just mark it as non-leaf
elif len(incoming_node.nodes ) > 1:
_UpperCAmelCase = False
# If there is 1 edge, we merge it with its child
else:
_UpperCAmelCase = list(incoming_node.nodes.values() )[0]
_UpperCAmelCase = merging_node.is_leaf
incoming_node.prefix += merging_node.prefix
_UpperCAmelCase = merging_node.nodes
return True
def _a ( self , a_ = 0 ) -> None:
if self.prefix != "":
print("-" * height , self.prefix , " (leaf)" if self.is_leaf else "" )
for value in self.nodes.values():
value.print_tree(height + 1 )
def __lowerCamelCase ( ):
"""simple docstring"""
_UpperCAmelCase = "banana bananas bandana band apple all beast".split()
_UpperCAmelCase = RadixNode()
root.insert_many(UpperCamelCase__ )
assert all(root.find(UpperCamelCase__ ) for word in words )
assert not root.find("bandanas" )
assert not root.find("apps" )
root.delete("all" )
assert not root.find("all" )
root.delete("banana" )
assert not root.find("banana" )
assert root.find("bananas" )
return True
def __lowerCamelCase ( ):
"""simple docstring"""
assert test_trie()
def __lowerCamelCase ( ):
"""simple docstring"""
_UpperCAmelCase = RadixNode()
_UpperCAmelCase = "banana bananas bandanas bandana band apple all beast".split()
root.insert_many(UpperCamelCase__ )
print("Words:" , UpperCamelCase__ )
print("Tree:" )
root.print_tree()
if __name__ == "__main__":
main()
| 657 |
"""simple docstring"""
def __lowerCamelCase ( UpperCamelCase__ ):
"""simple docstring"""
return 10 - x * x
def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ):
"""simple docstring"""
if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) >= 0:
raise ValueError("Wrong space!" )
_UpperCAmelCase = a
while (b - a) >= 0.01:
# Find middle point
_UpperCAmelCase = (a + b) / 2
# Check if middle point is root
if equation(UpperCamelCase__ ) == 0.0:
break
# Decide the side to repeat the steps
if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) < 0:
_UpperCAmelCase = c
else:
_UpperCAmelCase = c
return c
if __name__ == "__main__":
import doctest
doctest.testmod()
print(bisection(-2, 5))
print(bisection(0, 6))
| 657 | 1 |
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert 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 AlignProcessor, EfficientNetImageProcessor
@require_vision
class lowercase_ ( unittest.TestCase ):
def _lowercase ( self: str):
'''simple docstring'''
__lowerCAmelCase = tempfile.mkdtemp()
__lowerCAmelCase = [
"""[UNK]""",
"""[CLS]""",
"""[SEP]""",
"""[PAD]""",
"""[MASK]""",
"""want""",
"""##want""",
"""##ed""",
"""wa""",
"""un""",
"""runn""",
"""##ing""",
""",""",
"""low""",
"""lowest""",
]
__lowerCAmelCase = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""vocab_file"""])
with open(self.vocab_file, """w""", encoding="""utf-8""") as vocab_writer:
vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]))
__lowerCAmelCase = {
"""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],
}
__lowerCAmelCase = os.path.join(self.tmpdirname, _lowercase)
with open(self.image_processor_file, """w""", encoding="""utf-8""") as fp:
json.dump(_lowercase, _lowercase)
def _lowercase ( self: Optional[Any], **_lowercase: List[str]):
'''simple docstring'''
return BertTokenizer.from_pretrained(self.tmpdirname, **_lowercase)
def _lowercase ( self: str, **_lowercase: Optional[int]):
'''simple docstring'''
return BertTokenizerFast.from_pretrained(self.tmpdirname, **_lowercase)
def _lowercase ( self: str, **_lowercase: List[Any]):
'''simple docstring'''
return EfficientNetImageProcessor.from_pretrained(self.tmpdirname, **_lowercase)
def _lowercase ( self: Optional[Any]):
'''simple docstring'''
shutil.rmtree(self.tmpdirname)
def _lowercase ( self: Dict):
'''simple docstring'''
__lowerCAmelCase = [np.random.randint(255, size=(3, 30, 400), dtype=np.uinta)]
__lowerCAmelCase = [Image.fromarray(np.moveaxis(_lowercase, 0, -1)) for x in image_inputs]
return image_inputs
def _lowercase ( self: List[Any]):
'''simple docstring'''
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = self.get_rust_tokenizer()
__lowerCAmelCase = self.get_image_processor()
__lowerCAmelCase = AlignProcessor(tokenizer=_lowercase, image_processor=_lowercase)
processor_slow.save_pretrained(self.tmpdirname)
__lowerCAmelCase = AlignProcessor.from_pretrained(self.tmpdirname, use_fast=_lowercase)
__lowerCAmelCase = AlignProcessor(tokenizer=_lowercase, image_processor=_lowercase)
processor_fast.save_pretrained(self.tmpdirname)
__lowerCAmelCase = AlignProcessor.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, _lowercase)
self.assertIsInstance(processor_fast.tokenizer, _lowercase)
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, _lowercase)
self.assertIsInstance(processor_fast.image_processor, _lowercase)
def _lowercase ( self: Optional[int]):
'''simple docstring'''
__lowerCAmelCase = AlignProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor())
processor.save_pretrained(self.tmpdirname)
__lowerCAmelCase = self.get_tokenizer(bos_token="""(BOS)""", eos_token="""(EOS)""")
__lowerCAmelCase = self.get_image_processor(do_normalize=_lowercase, padding_value=1.0)
__lowerCAmelCase = AlignProcessor.from_pretrained(
self.tmpdirname, bos_token="""(BOS)""", eos_token="""(EOS)""", do_normalize=_lowercase, padding_value=1.0)
self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
self.assertIsInstance(processor.tokenizer, _lowercase)
self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string())
self.assertIsInstance(processor.image_processor, _lowercase)
def _lowercase ( self: Any):
'''simple docstring'''
__lowerCAmelCase = self.get_image_processor()
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = AlignProcessor(tokenizer=_lowercase, image_processor=_lowercase)
__lowerCAmelCase = self.prepare_image_inputs()
__lowerCAmelCase = image_processor(_lowercase, return_tensors="""np""")
__lowerCAmelCase = processor(images=_lowercase, 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 _lowercase ( self: List[Any]):
'''simple docstring'''
__lowerCAmelCase = self.get_image_processor()
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = AlignProcessor(tokenizer=_lowercase, image_processor=_lowercase)
__lowerCAmelCase = """lower newer"""
__lowerCAmelCase = processor(text=_lowercase)
__lowerCAmelCase = tokenizer(_lowercase, padding="""max_length""", max_length=64)
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key], encoded_processor[key])
def _lowercase ( self: int):
'''simple docstring'''
__lowerCAmelCase = self.get_image_processor()
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = AlignProcessor(tokenizer=_lowercase, image_processor=_lowercase)
__lowerCAmelCase = """lower newer"""
__lowerCAmelCase = self.prepare_image_inputs()
__lowerCAmelCase = processor(text=_lowercase, images=_lowercase)
self.assertListEqual(list(inputs.keys()), ["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""])
# test if it raises when no input is passed
with pytest.raises(_lowercase):
processor()
def _lowercase ( self: Dict):
'''simple docstring'''
__lowerCAmelCase = self.get_image_processor()
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = AlignProcessor(tokenizer=_lowercase, image_processor=_lowercase)
__lowerCAmelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
__lowerCAmelCase = processor.batch_decode(_lowercase)
__lowerCAmelCase = tokenizer.batch_decode(_lowercase)
self.assertListEqual(_lowercase, _lowercase)
def _lowercase ( self: int):
'''simple docstring'''
__lowerCAmelCase = self.get_image_processor()
__lowerCAmelCase = self.get_tokenizer()
__lowerCAmelCase = AlignProcessor(tokenizer=_lowercase, image_processor=_lowercase)
__lowerCAmelCase = """lower newer"""
__lowerCAmelCase = self.prepare_image_inputs()
__lowerCAmelCase = processor(text=_lowercase, images=_lowercase)
self.assertListEqual(list(inputs.keys()), processor.model_input_names)
| 334 |
import argparse
import logging
import pickle
from collections import Counter
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO
)
__A : Optional[Any] = logging.getLogger(__name__)
if __name__ == "__main__":
__A : int = argparse.ArgumentParser(
description="Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)"
)
parser.add_argument(
"--data_file", type=str, default="data/dump.bert-base-uncased.pickle", help="The binarized dataset."
)
parser.add_argument(
"--token_counts_dump", type=str, default="data/token_counts.bert-base-uncased.pickle", help="The dump file."
)
parser.add_argument("--vocab_size", default=30_522, type=int)
__A : Optional[Any] = parser.parse_args()
logger.info(f"""Loading data from {args.data_file}""")
with open(args.data_file, "rb") as fp:
__A : Union[str, Any] = pickle.load(fp)
logger.info("Counting occurrences for MLM.")
__A : Optional[Any] = Counter()
for tk_ids in data:
counter.update(tk_ids)
__A : int = [0] * args.vocab_size
for k, v in counter.items():
__A : Optional[int] = v
logger.info(f"""Dump to {args.token_counts_dump}""")
with open(args.token_counts_dump, "wb") as handle:
pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
| 334 | 1 |
'''simple docstring'''
import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path
import torch_xla.distributed.xla_multiprocessing as xmp
def _a ( ) -> Any:
"""simple docstring"""
__snake_case : Tuple = ArgumentParser(
description=(
"""PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes"""
) )
# Optional arguments for the launch helper
parser.add_argument("""--num_cores""" , type=_lowerCamelCase , default=1 , help="""Number of TPU cores to use (1 or 8).""" )
# positional
parser.add_argument(
"""training_script""" , type=_lowerCamelCase , help=(
"""The full path to the single TPU training """
"""program/script to be launched in parallel, """
"""followed by all the arguments for the """
"""training script"""
) , )
# rest from the training program
parser.add_argument("""training_script_args""" , nargs=_lowerCamelCase )
return parser.parse_args()
def _a ( ) -> str:
"""simple docstring"""
__snake_case : Optional[Any] = parse_args()
# Import training_script as a module.
__snake_case : Optional[int] = Path(args.training_script )
sys.path.append(str(script_fpath.parent.resolve() ) )
__snake_case : Any = script_fpath.stem
__snake_case : List[str] = importlib.import_module(_lowerCamelCase )
# Patch sys.argv
__snake_case : int = [args.training_script] + args.training_script_args + ["""--tpu_num_cores""", str(args.num_cores )]
xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores )
if __name__ == "__main__":
main()
| 26 |
'''simple docstring'''
import json
import os
import unittest
from transformers.models.roc_bert.tokenization_roc_bert import (
VOCAB_FILES_NAMES,
RoCBertBasicTokenizer,
RoCBertTokenizer,
RoCBertWordpieceTokenizer,
_is_control,
_is_punctuation,
_is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english
@require_tokenizers
class lowercase__ ( snake_case_, unittest.TestCase ):
'''simple docstring'''
_snake_case = RoCBertTokenizer
_snake_case = None
_snake_case = False
_snake_case = True
_snake_case = filter_non_english
def UpperCAmelCase ( self ):
'''simple docstring'''
super().setUp()
UpperCamelCase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''你''', '''好''', '''是''', '''谁''', '''a''', '''b''', '''c''', '''d''']
UpperCamelCase = {}
UpperCamelCase = {}
for i, value in enumerate(lowerCamelCase__ ):
UpperCamelCase = i
UpperCamelCase = i
UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''word_shape_file'''] )
UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''word_pronunciation_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
with open(self.word_shape_file , '''w''' , encoding='''utf-8''' ) as word_shape_writer:
json.dump(lowerCamelCase__ , lowerCamelCase__ , ensure_ascii=lowerCamelCase__ )
with open(self.word_pronunciation_file , '''w''' , encoding='''utf-8''' ) as word_pronunciation_writer:
json.dump(lowerCamelCase__ , lowerCamelCase__ , ensure_ascii=lowerCamelCase__ )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file )
UpperCamelCase = tokenizer.tokenize('''你好[SEP]你是谁''' )
self.assertListEqual(lowerCamelCase__ , ['''你''', '''好''', '''[SEP]''', '''你''', '''是''', '''谁'''] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) , [5, 6, 2, 5, 7, 8] )
self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(lowerCamelCase__ ) , [5, 6, 2, 5, 7, 8] )
self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(lowerCamelCase__ ) , [5, 6, 2, 5, 7, 8] )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = RoCBertBasicTokenizer()
self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase__ )
self.assertListEqual(
tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] )
self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase__ , strip_accents=lowerCamelCase__ )
self.assertListEqual(
tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] )
self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase__ , strip_accents=lowerCamelCase__ )
self.assertListEqual(
tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] )
self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase__ )
self.assertListEqual(
tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] )
self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase__ )
self.assertListEqual(
tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase__ , strip_accents=lowerCamelCase__ )
self.assertListEqual(
tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase__ , strip_accents=lowerCamelCase__ )
self.assertListEqual(
tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = RoCBertBasicTokenizer(do_lower_case=lowerCamelCase__ , never_split=['''[UNK]'''] )
self.assertListEqual(
tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''']
UpperCamelCase = {}
for i, token in enumerate(lowerCamelCase__ ):
UpperCamelCase = i
UpperCamelCase = RoCBertWordpieceTokenizer(vocab=lowerCamelCase__ , unk_token='''[UNK]''' )
self.assertListEqual(tokenizer.tokenize('''''' ) , [] )
self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) , ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] )
self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) , ['''[UNK]''', '''runn''', '''##ing'''] )
def UpperCAmelCase ( self ):
'''simple docstring'''
self.assertTrue(_is_whitespace(''' ''' ) )
self.assertTrue(_is_whitespace('''\t''' ) )
self.assertTrue(_is_whitespace('''\r''' ) )
self.assertTrue(_is_whitespace('''\n''' ) )
self.assertTrue(_is_whitespace('''\u00A0''' ) )
self.assertFalse(_is_whitespace('''A''' ) )
self.assertFalse(_is_whitespace('''-''' ) )
def UpperCAmelCase ( self ):
'''simple docstring'''
self.assertTrue(_is_control('''\u0005''' ) )
self.assertFalse(_is_control('''A''' ) )
self.assertFalse(_is_control(''' ''' ) )
self.assertFalse(_is_control('''\t''' ) )
self.assertFalse(_is_control('''\r''' ) )
def UpperCAmelCase ( self ):
'''simple docstring'''
self.assertTrue(_is_punctuation('''-''' ) )
self.assertTrue(_is_punctuation('''$''' ) )
self.assertTrue(_is_punctuation('''`''' ) )
self.assertTrue(_is_punctuation('''.''' ) )
self.assertFalse(_is_punctuation('''A''' ) )
self.assertFalse(_is_punctuation(''' ''' ) )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = self.get_tokenizer()
# Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
self.assertListEqual([tokenizer.tokenize(lowerCamelCase__ ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] )
if self.test_rust_tokenizer:
UpperCamelCase = self.get_rust_tokenizer()
self.assertListEqual(
[rust_tokenizer.tokenize(lowerCamelCase__ ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] )
def UpperCAmelCase ( self ):
'''simple docstring'''
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ):
UpperCamelCase = self.rust_tokenizer_class.from_pretrained(lowerCamelCase__ , **lowerCamelCase__ )
UpperCamelCase = f'A, naïve {tokenizer_r.mask_token} AllenNLP sentence.'
UpperCamelCase = tokenizer_r.encode_plus(
lowerCamelCase__ , return_attention_mask=lowerCamelCase__ , return_token_type_ids=lowerCamelCase__ , return_offsets_mapping=lowerCamelCase__ , add_special_tokens=lowerCamelCase__ , )
UpperCamelCase = tokenizer_r.do_lower_case if hasattr(lowerCamelCase__ , '''do_lower_case''' ) else False
UpperCamelCase = (
[
((0, 0), tokenizer_r.cls_token),
((0, 1), '''A'''),
((1, 2), ''','''),
((3, 5), '''na'''),
((5, 6), '''##ï'''),
((6, 8), '''##ve'''),
((9, 1_5), tokenizer_r.mask_token),
((1_6, 2_1), '''Allen'''),
((2_1, 2_3), '''##NL'''),
((2_3, 2_4), '''##P'''),
((2_5, 3_3), '''sentence'''),
((3_3, 3_4), '''.'''),
((0, 0), tokenizer_r.sep_token),
]
if not do_lower_case
else [
((0, 0), tokenizer_r.cls_token),
((0, 1), '''a'''),
((1, 2), ''','''),
((3, 8), '''naive'''),
((9, 1_5), tokenizer_r.mask_token),
((1_6, 2_1), '''allen'''),
((2_1, 2_3), '''##nl'''),
((2_3, 2_4), '''##p'''),
((2_5, 3_3), '''sentence'''),
((3_3, 3_4), '''.'''),
((0, 0), tokenizer_r.sep_token),
]
)
self.assertEqual(
[e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['''input_ids'''] ) )
self.assertEqual([e[0] for e in expected_results] , tokens['''offset_mapping'''] )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = ['''的''', '''人''', '''有''']
UpperCamelCase = ''''''.join(lowerCamelCase__ )
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ):
UpperCamelCase = True
UpperCamelCase = self.tokenizer_class.from_pretrained(lowerCamelCase__ , **lowerCamelCase__ )
UpperCamelCase = self.rust_tokenizer_class.from_pretrained(lowerCamelCase__ , **lowerCamelCase__ )
UpperCamelCase = tokenizer_p.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ )
UpperCamelCase = tokenizer_r.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ )
UpperCamelCase = tokenizer_r.convert_ids_to_tokens(lowerCamelCase__ )
UpperCamelCase = tokenizer_p.convert_ids_to_tokens(lowerCamelCase__ )
# it is expected that each Chinese character is not preceded by "##"
self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ )
self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ )
UpperCamelCase = False
UpperCamelCase = self.rust_tokenizer_class.from_pretrained(lowerCamelCase__ , **lowerCamelCase__ )
UpperCamelCase = self.tokenizer_class.from_pretrained(lowerCamelCase__ , **lowerCamelCase__ )
UpperCamelCase = tokenizer_r.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ )
UpperCamelCase = tokenizer_p.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ )
UpperCamelCase = tokenizer_r.convert_ids_to_tokens(lowerCamelCase__ )
UpperCamelCase = tokenizer_p.convert_ids_to_tokens(lowerCamelCase__ )
# it is expected that only the first Chinese character is not preceded by "##".
UpperCamelCase = [
f'##{token}' if idx != 0 else token for idx, token in enumerate(lowerCamelCase__ )
]
self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ )
self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ )
@slow
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file )
UpperCamelCase = tokenizer.encode('''你好''' , add_special_tokens=lowerCamelCase__ )
UpperCamelCase = tokenizer.encode('''你是谁''' , add_special_tokens=lowerCamelCase__ )
UpperCamelCase = tokenizer.build_inputs_with_special_tokens(lowerCamelCase__ )
UpperCamelCase = tokenizer.build_inputs_with_special_tokens(lowerCamelCase__ , lowerCamelCase__ )
assert encoded_sentence == [1] + text + [2]
assert encoded_pair == [1] + text + [2] + text_a + [2]
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = self.get_tokenizers(do_lower_case=lowerCamelCase__ )
for tokenizer in tokenizers:
with self.subTest(f'{tokenizer.__class__.__name__}' ):
UpperCamelCase = '''你好,你是谁'''
UpperCamelCase = tokenizer.tokenize(lowerCamelCase__ )
UpperCamelCase = tokenizer.convert_tokens_to_ids(lowerCamelCase__ )
UpperCamelCase = tokenizer.convert_tokens_to_shape_ids(lowerCamelCase__ )
UpperCamelCase = tokenizer.convert_tokens_to_pronunciation_ids(lowerCamelCase__ )
UpperCamelCase = tokenizer.prepare_for_model(
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , add_special_tokens=lowerCamelCase__ )
UpperCamelCase = tokenizer.encode_plus(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ )
self.assertEqual(lowerCamelCase__ , lowerCamelCase__ )
| 212 | 0 |
'''simple docstring'''
import argparse
import torch
from torch import nn
from transformers import MBartConfig, MBartForConditionalGeneration
def A ( _UpperCAmelCase : int ) -> List[str]:
'''simple docstring'''
__lowerCAmelCase : List[str] = [
'encoder.version',
'decoder.version',
'model.encoder.version',
'model.decoder.version',
'_float_tensor',
'decoder.output_projection.weight',
]
for k in ignore_keys:
state_dict.pop(_UpperCAmelCase ,_UpperCAmelCase )
def A ( _UpperCAmelCase : int ) -> Union[str, Any]:
'''simple docstring'''
__lowerCAmelCase , __lowerCAmelCase : Optional[Any] = emb.weight.shape
__lowerCAmelCase : List[Any] = nn.Linear(_UpperCAmelCase ,_UpperCAmelCase ,bias=_UpperCAmelCase )
__lowerCAmelCase : Tuple = emb.weight.data
return lin_layer
def A ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Union[str, Any]="facebook/mbart-large-en-ro" ,_UpperCAmelCase : List[Any]=False ,_UpperCAmelCase : int=False ) -> Union[str, Any]:
'''simple docstring'''
__lowerCAmelCase : Any = torch.load(_UpperCAmelCase ,map_location='cpu' )['model']
remove_ignore_keys_(_UpperCAmelCase )
__lowerCAmelCase : Tuple = state_dict['encoder.embed_tokens.weight'].shape[0]
__lowerCAmelCase : int = MBartConfig.from_pretrained(_UpperCAmelCase ,vocab_size=_UpperCAmelCase )
if mbart_aa and finetuned:
__lowerCAmelCase : List[str] = 'relu'
__lowerCAmelCase : Dict = state_dict['decoder.embed_tokens.weight']
__lowerCAmelCase : int = MBartForConditionalGeneration(_UpperCAmelCase )
model.model.load_state_dict(_UpperCAmelCase )
if finetuned:
__lowerCAmelCase : List[str] = make_linear_from_emb(model.model.shared )
return model
if __name__ == "__main__":
A_ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"fairseq_path", type=str, help="bart.large, bart.large.cnn or a path to a model.pt on local filesystem."
)
parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
parser.add_argument(
"--hf_config",
default="facebook/mbart-large-cc25",
type=str,
help="Which huggingface architecture to use: mbart-large",
)
parser.add_argument("--mbart_50", action="store_true", help="whether the model is mMART-50 checkpoint")
parser.add_argument("--finetuned", action="store_true", help="whether the model is a fine-tuned checkpoint")
A_ = parser.parse_args()
A_ = convert_fairseq_mbart_checkpoint_from_disk(
args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa
)
model.save_pretrained(args.pytorch_dump_folder_path)
| 123 |
'''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,
)
A_ = pytest.mark.integration
@pytest.mark.parametrize('path' ,['paws', 'csv'] )
def A ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ) -> Optional[Any]:
'''simple docstring'''
inspect_dataset(_UpperCAmelCase ,_UpperCAmelCase )
__lowerCAmelCase : str = path + '.py'
assert script_name in os.listdir(_UpperCAmelCase )
assert "__pycache__" not in os.listdir(_UpperCAmelCase )
@pytest.mark.filterwarnings('ignore:inspect_metric is deprecated:FutureWarning' )
@pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning' )
@pytest.mark.parametrize('path' ,['accuracy'] )
def A ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Union[str, Any] ) -> Dict:
'''simple docstring'''
inspect_metric(_UpperCAmelCase ,_UpperCAmelCase )
__lowerCAmelCase : List[Any] = path + '.py'
assert script_name in os.listdir(_UpperCAmelCase )
assert "__pycache__" not in os.listdir(_UpperCAmelCase )
@pytest.mark.parametrize(
'path, config_name, expected_splits' ,[
('squad', 'plain_text', ['train', 'validation']),
('dalle-mini/wit', 'dalle-mini--wit', ['train']),
('paws', 'labeled_final', ['train', 'test', 'validation']),
] ,)
def A ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ) -> Any:
'''simple docstring'''
__lowerCAmelCase : Union[str, Any] = get_dataset_config_info(_UpperCAmelCase ,config_name=_UpperCAmelCase )
assert info.config_name == config_name
assert list(info.splits.keys() ) == expected_splits
@pytest.mark.parametrize(
'path, config_name, expected_exception' ,[
('paws', None, ValueError),
] ,)
def A ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> str:
'''simple docstring'''
with pytest.raises(_UpperCAmelCase ):
get_dataset_config_info(_UpperCAmelCase ,config_name=_UpperCAmelCase )
@pytest.mark.parametrize(
'path, expected' ,[
('squad', 'plain_text'),
('acronym_identification', 'default'),
('lhoestq/squad', 'plain_text'),
('lhoestq/test', 'default'),
('lhoestq/demo1', 'lhoestq--demo1'),
('dalle-mini/wit', 'dalle-mini--wit'),
] ,)
def A ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : int ) -> int:
'''simple docstring'''
__lowerCAmelCase : Union[str, Any] = get_dataset_config_names(_UpperCAmelCase )
assert expected in config_names
@pytest.mark.parametrize(
'path, expected_configs, expected_splits_in_first_config' ,[
('squad', ['plain_text'], ['train', 'validation']),
('dalle-mini/wit', ['dalle-mini--wit'], ['train']),
('paws', ['labeled_final', 'labeled_swap', 'unlabeled_final'], ['train', 'test', 'validation']),
] ,)
def A ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : str ) -> str:
'''simple docstring'''
__lowerCAmelCase : Union[str, Any] = get_dataset_infos(_UpperCAmelCase )
assert list(infos.keys() ) == expected_configs
__lowerCAmelCase : List[str] = expected_configs[0]
assert expected_config in infos
__lowerCAmelCase : Dict = 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 A ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Dict ) -> Union[str, Any]:
'''simple docstring'''
__lowerCAmelCase : Optional[Any] = get_dataset_infos(_UpperCAmelCase )
assert expected_config in infos
__lowerCAmelCase : List[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 A ( _UpperCAmelCase : str ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Optional[Any] ) -> Optional[int]:
'''simple docstring'''
with pytest.raises(_UpperCAmelCase ):
get_dataset_split_names(_UpperCAmelCase ,config_name=_UpperCAmelCase )
| 123 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.